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 class codata2016: def __init__(self): self.mp = 1.672621898e-27 # kg self.me = 9.10938356e-31 # kg # end def # end class # HELPER FUNCTIONS # ====================================== from lxml import etree def xml_print(node): print etree.tostring(node,pretty_print=True) # end def from copy import deepcopy import numpy as np def matrix_to_text(matrix): text = "\n"+\ "\n".join([" ".join( map(str,pos) ) for pos in matrix])\ +"\n" return text # end def matrix_to_text # START EDIT QMCPACK INPUT XML # ====================================== def change_ion0_to_wf_ceneters(ion0): # change ion0 particle set to be artificial centers around which # to expand the wave function # ====================================== ion0.attrib['name'] = 'wf_centers' protons = ion0.find("group") if 'mass' in protons.attrib: protons.attrib.pop("mass") protons.attrib.pop("size") #protons.attrib["name"] = "centers" for child in protons: if child.attrib["name"] != "position" and child.attrib["name"] != "charge": protons.remove(child) elif child.attrib["name"] == "charge": child.text = child.text.replace("1","0") # end if # end for # record and return the wf_centers for later use # ====================================== centers_text = ion0.find("group/attrib").text centers = [map(float,center.split()) for center in centers_text.split("\n")[1:-1]] nions = len(centers) ion0.find("group").attrib["size"] = str(nions) return centers # end def change_ion0_to_wf_ceneters def edit_quantum_particleset(e_particleset,centers,rs,ion_width,hname='p'): # centers: wf_centers nions = len(centers) # average <R^2> sig2 = 1./(4.*ion_width) # not 3.* for each direction ion_sig = np.sqrt(sig2) # initialize electrons manually: remove random, add attrib positions # ====================================== # do not initialize eletrons at random # -------------------------------------- e_particleset.attrib.pop("random") def gaussian_move(centers,sigma): move = np.random.randn( *np.shape(centers) )*sigma return np.copy(centers + move) # end def # sprinkle particles around ion positions # -------------------------------------- electron_pos = gaussian_move(centers,0.2*rs) # electrons equilibrate quickly proton_pos = gaussian_move(centers,ion_sig) # protons are slow, initialize well # should be 2 groups in electronic wf, one u, one d spin_groups = e_particleset.findall("group") for i in range(2): # loop through u,d # 0 for up spin, 1 for down spin e_section = spin_groups[i] # assuming adjacent protons have adjacent indexing, the following will # place u on the even sublattice, d on the odd sublattice epos = electron_pos[i::2] epos_text = "\n"+"\n".join([" ".join( map(str,pos) ) for pos in epos])+"\n" new_section = etree.Element("attrib", {"name":"position","datatype":"posArray","condition":"0"}) new_section.text = epos_text e_section.append( new_section ) # end for i # add protons to the particleset # ====================================== # steal from electron section unit = codata2016() p_section = deepcopy( e_section ) p_section.attrib["name"] = hname p_section.attrib['mass'] = str(unit.mp/unit.me) p_section.attrib['size'] = str(nions) p_section.xpath('.//parameter[@name="charge"]')[0].text = ' 1 ' p_section.xpath('.//parameter[@name="mass"]')[0].text = ' %s ' % str(unit.mp/unit.me) ppos_text = "\n"+"\n".join([" ".join( map(str,pos) ) for pos in proton_pos])+"\n" p_section.find("attrib").text = ppos_text e_particleset.append(p_section) # end def def edit_jastrows(wf,hname='p'): # 1. grab Uep and remove ep jastrow j1 = wf.xpath('//jastrow[@name="J1"]')[0] Uep = j1.xpath(".//coefficients")[0].text wf.remove(j1) # 2. edit 2-body jastrow to add e-p correlation j2 = wf.xpath('//jastrow[@name="J2"]')[0] term = j2.find("correlation") etypes = {0:"u",1:"d"} for ie in range(2): eHterm = deepcopy(term) etype = etypes[ie] # 0:u, 1:d eHterm.attrib["speciesA"] = etype eHterm.attrib["speciesB"] = hname eHterm.attrib["cusp"] = "1.0" coeff = eHterm.find("coefficients") if (etype == "u"): coeff.attrib["id"] = etype+hname coeff.text = Uep # initialize e-p Jastrow to clamped values else: eHterm = etree.Element('correlation',{'speciesA':'d','speciesB':hname,'link':'u'+hname}) # end if j2.append(eHterm) # end for ie # explicitly link dd to uu j2.append(etree.Element('correlation',{'speciesA':'d','speciesB':'d','link':'uu'})) # 3. add an empty p-p correlation term pp_term = deepcopy(term) pp_term.set('speciesA',hname) pp_term.set('speciesB',hname) pp_term.set('cusp','0.0') coeff = pp_term.find('coefficients') nsize = int(term.get('size')) text = '\n'+' '.join(['0.0']*nsize)+'\n' coeff.set('id',hname+hname+'J') coeff.text = text j2.append(pp_term) # end def edit_jastrows def edit_backflows(wf,hname='p'): bf_node = wf.find('.//backflow') if bf_node is None: return # nothing to do # 1. grab eta_ei and remove e-I backflow bf1 = wf.find('.//transformation[@type="e-I"]') if bf1 is None: return # nothing to do eta1 = bf1.xpath('.//correlation') bf_node.remove(bf1) # 2. edit 2-body backflow to add e-p correlation bf2 = wf.find('.//transformation[@type="e-e"]') term = bf2.find('.//correlation') up_term = deepcopy(term) up_term.set('speciesA','u') up_term.set('speciesB',hname) etypes = {0:"u",1:"d"} for eta in eta1: ion_name = eta.attrib.pop('elementType') ion_name = 'p' # !!!! override ion name for ie in etypes.keys(): ename = etypes[ie] eta.set('speciesA',ename) eta.set('speciesB',ion_name) coeff = eta.find('.//coefficients') coeff.set('id',ename+ion_name+'B') bf2.append(deepcopy(eta)) # end for ie # end for eta # end def edit_jastrows def edit_hamiltonian(ham,hname='p'): # remove all interactions that requires the "ion0" particleset for interaction in ham: use_ion0 = False for key in interaction.attrib.keys(): if interaction.attrib[key]=="ion0": use_ion0 = True # end if # end for key if use_ion0: ham.remove(interaction) # end if # end for # add dynamic run specific estimators skinetic = etree.Element('estimator',{'type':'specieskinetic','name':'skinetic'}) latdev = etree.Element('estimator',{'type':'latticedeviation','name':'latdev', 'target':'e','tgroup':hname,'source':'wf_centers','sgroup':'H','hdf5':'yes','per_xyz':'yes'}) ham.append(skinetic) ham.append(latdev) # end def edit_hamiltonian def edit_determinantset(wf,centers,ion_width): """ construct <sposet_builder type="mo"> for protons and add one determinant to slater wf: the xml node pointing to <wavefunction> centers: proton positions of shape (natom,ndim) ion_width: exponent of Gaussian proton orbital """ nions = len(centers) # get electronic sposet_builder ebuilder = wf.find('sposet_builder[@source="ion0"]') if ebuilder is None: raise RuntimeError('electronic sposet_builder with source="ion0" not found.') # end if # build electronic single-particle orbitals around "wf_centers" instead of "ion0" ebuilder.set('source','wf_centers') # use double precision ebuilder.set('precision','double') # start parent -> construct children -> build kids # start <sposet_builder> for protons pbuilder = etree.Element('sposet_builder',attrib={ 'type':'mo', # use MolecularOrbitalBuilder 'source':'wf_centers', # use static lattice sites for proton w.f. 'transform':'yes', # use numerical radial function and NGOBuilder 'name':'proton_builder' }) # !!!! transformOpt flag forces cuspCorr="yes" and key="NMO" # construct <basisset> pbasis = etree.Element("basisset") pao_basis = etree.Element('atomicBasisSet',attrib={ 'elementType':'H', # identifier for aoBuilder 'angular':'cartesian', # Use Gamess-style order of angular functions 'type':'GTO', # use Gaussians in NGOBuilder::addRadialOrbital() 'normalized':'yes' # do not mess with my input coefficients }) # build <grid> bgrid = etree.Element('grid',{ 'npts':'1001', 'rf':'100', 'ri':'1.e-6', 'type':'log' }) # build <basisGroup> bgroup = etree.Element('basisGroup',{ 'l':'0', 'n':'1', 'rid':'R0' }) bgroup.append(etree.Element('radfunc',{'contraction':'1.0','exponent':str(ion_width)})) pao_basis.append(bgrid) pao_basis.append(bgroup) pbasis.append(pao_basis) # finished construct </basisset> # build <sposet> psposet = etree.Element('sposet',attrib={ 'name':'spo_p', 'id':'proton_orbs', 'size':str(nions) # SPOSetBase::put # no 'cuspInfo' }) pbuilder.append(pbasis) # done construct </basisset> # construct <sposet> # <coefficient> is not needed for identity matrix #coeff = etree.Element("coefficient", # {"id":"HdetC","type":"constArray","size":str(nions)}) #coeff.text = matrix_to_text(np.eye(nions)) #psposet.append(coeff) pbuilder.append(etree.Comment("Identity coefficient matrix by default SPOSetBase::setIdentity")) pbuilder.append(psposet) # build single-particle orbitals # done construct </sposet> # end </sposet_builder> # build <determinant> pdet = etree.Element('determinant',{ 'group':'p', 'id':'pdet', 'size':str(nions), 'sposet':psposet.get('name'), 'no_bftrans':'yes' # do not transform proton coordinates }) slater = wf.find('determinantset/slaterdeterminant') ebuilder_idx = wf.index(ebuilder) wf.insert(ebuilder_idx+1,pbuilder) # insert proton_builder after electronic sposet_builder slater.append(pdet) # end def edit_determinantset # Main Routine # ====================================== def bo_to_nobo(bo_input_name,nobo_input_name,ion_width=10.0,rs=1.31): parser = etree.XMLParser(remove_blank_text=True) xml = etree.parse(bo_input_name,parser) ion0 = xml.xpath('//particleset[@name="ion0"]')[0] centers = change_ion0_to_wf_ceneters(ion0) e_particleset = xml.xpath('//particleset[@name="e"]')[0] edit_quantum_particleset(e_particleset,centers,rs,ion_width) wf = xml.xpath("//wavefunction")[0] edit_jastrows(wf) edit_backflows(wf) edit_determinantset(wf,centers,ion_width) ham = xml.xpath("//hamiltonian")[0] edit_hamiltonian(ham) xml.write(nobo_input_name,pretty_print=True) # end def bo_to_nobo if __name__ == "__main__": import sys #prefix = sys.argv[1] #bo_to_nobo(prefix+"-dmc.in.xml",prefix+"-nobo.in.xml") inp_xml = sys.argv[1] out_xml = 'nobo-'+inp_xml bo_to_nobo(inp_xml,out_xml,ion_width=9.0) # end __main__
Paul-St-Young/QMC
setup_polarized.py
Python
mit
11,381
[ "GAMESS", "Gaussian", "QMCPACK" ]
c19599d38560cf21553ecdb950e3a837bc075a5caecdb73a9ce71952d57af093
"""Configuration for the documentation scripts.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import logging import argparse from pprint import pformat from configparser import ConfigParser LOG = logging.getLogger(__name__) K_DOCS = "Docs" K_CFG = "CFG" DEF_CFG_BASEFILE = "../dirac.cfg" DEF_CFG_TARGETFILE = "source/ExampleConfig.rst" K_CODE = "Code" DEF_CODE_TARGETPATH = "source/CodeDocumentation" DEF_CODE_CUSTOMDOCS = "diracdoctools/CustomizedDocs" DEF_CODE_COMMANDSECTION = "false" K_COMMANDS = "Commands" DEF_COMMANDS_FILENAME = "index.rst" DEF_COMMANDS_SECTIONPATH = "source/Commands" def listify(values: str) -> list: """Listify string""" return [entry.strip() for entry in values.split(",") if entry] class Configuration(object): """Provide configuration to the scripts.""" def __init__(self, confFile, sections=None): if sections is None: sections = [K_CODE, K_COMMANDS, K_CFG] LOG.info("Reading configFile %r", os.path.join(os.getcwd(), confFile)) self.config = ConfigParser(dict_type=dict) self.config.read(confFile) # self.config.optionxform = str # do not transform options to lowercase self.docsPath = os.path.dirname(os.path.abspath(confFile)) # Read Docs section self.moduleName = self.getOption(K_DOCS, "module_name", mandatory=True) self.sourcePath = self._fullPath(self.getOption(K_DOCS, "source_folder", f"../src/{self.moduleName}")) # Read Code section if K_CODE in sections: self.code_customDocsPath = self._fullPath(self.getOption(K_CODE, "customdocs_folder", DEF_CODE_CUSTOMDOCS)) self.code_targetPath = self._fullPath(self.getOption(K_CODE, "docs_target_path", DEF_CODE_TARGETPATH)) self.code_privateMembers = listify(self.getOption(K_CODE, "document_private_members")) self.code_noInherited = listify(self.getOption(K_CODE, "no_inherited_members")) self.code_dummyFiles = listify(self.getOption(K_CODE, "create_dummy_files")) self.code_ignoreFolders = listify(self.getOption(K_CODE, "ignore_folders")) self.code_ignoreFiles = listify(self.getOption(K_CODE, "ignore_files")) self.code_add_commands_section = self.getOption( K_CODE, "add_commands_section", DEF_CODE_COMMANDSECTION ).lower() in ["true", "yes", "y"] # Read Commands section if K_COMMANDS in sections: self.com_rst_path = os.path.join( self.getOption(K_COMMANDS, "sectionpath", DEF_COMMANDS_SECTIONPATH), self.getOption(K_COMMANDS, "filename", DEF_COMMANDS_FILENAME), ) self.com_ignore_commands = listify(self.getOption(K_COMMANDS, "ignore_commands")) # List all scripts paths self.allScripts = glob.glob(os.path.join(self.sourcePath, "*", "scripts", "[!_]*.py")) self.allScripts += glob.glob(os.path.join(self.sourcePath, "*", "scripts", "[!_]*.sh")) self.allScripts.sort() self.scripts = {} # Sorted by group/subgroup for section in [s for s in sorted(self.config.sections()) if s.startswith("commands.")]: # Identify group/subgroup names from the section name sp = section.split(".") group, subgroup = (sp[-1], None) if len(sp) == 2 else (sp[-2], sp[-1]) LOG.info("Parsing config section: %r", section) # Read general group/subgroup settings title = self.getOption(section, "title", mandatory=True) pattern = listify(self.getOption(section, "pattern", mandatory=True)) exclude = listify(self.getOption(section, "exclude")) prefix = self.getOption(section, "prefix") # Search scripts for group/subgroup pattern _scripts = [] for sPath in self.allScripts: path = sPath[len(self.sourcePath) :].replace("_", "-") if any(p in path for p in pattern) and not any(p in path for p in exclude): name = os.path.basename(sPath) _scripts.append(name[:-3].replace("_", "-") if name.endswith(".py") else name) # Sort scripts _scripts.sort() # Grouping/subgrouping if not subgroup: # group case # Path to RST file fileName = self.getOption(section, "filename", "index.rst").strip() sectionPath = self._fullPath(self.getOption(section, "sectionpath").replace(" ", "")) # Collect scripts paths and metadata for group self.scripts[group] = dict( scripts=_scripts, title=title, prefix=prefix, rstPath=os.path.join(sectionPath, fileName), subgroups=[], ) else: # subgroup case # Collect scripts paths and metadata for subgroup self.scripts[group]["subgroups"].append(subgroup) # Sub group scripts is a subset of the group scripts subgroupScripts = [s for s in _scripts if s in self.scripts[group]["scripts"]] self.scripts[group][subgroup] = dict(title=title, prefix=prefix, scripts=subgroupScripts) # Remove subgroup scripts from group self.scripts[group]["scripts"] = [s for s in self.scripts[group]["scripts"] if s not in _scripts] # Read CFG section if K_CFG in sections: self.cfg_targetFile = self._fullPath(self.getOption(K_CFG, "target_file", DEF_CFG_TARGETFILE)) self.cfg_baseFile = self._fullPath(self.getOption(K_CFG, "base_file", DEF_CFG_BASEFILE)) for var, val in sorted(vars(self).items()): LOG.debug("Parsed options: %s = %s", var, pformat(val)) def _fullPath(self, path): """Return absolute path based on docsPath.""" return os.path.abspath(os.path.join(self.docsPath, path)) def getOption(self, section: str, option: str, default="", mandatory: bool = False) -> "option value": """Get option from TOML configuration :param section: section name :param option: option name :param default: default value :param mandatory: if option is mandatory""" if mandatory: return self.config.get(section, option) value = self.config.get(section, option) if self.config.has_option(section, option) else "" if not value and default: LOG.debug(f"Since the '{section}.{option}' is not specified, use default: {default}") return default return value def __str__(self): """Return string containing options and values.""" theStr = "" for var, val in vars(self).items(): theStr += "%s = %s\n" % (var, val) return theStr class CLParser(object): def __init__(self): self.log = LOG.getChild("CLParser") self.parsed = None self.debug = False self.parser = argparse.ArgumentParser("DiracDocTool", formatter_class=argparse.RawTextHelpFormatter) self.parser.add_argument( "--configFile", action="store", default="docs.conf", dest="configFile", help="Name of the config file" ) self.parser.add_argument("-d", "--debug", action="count", dest="debug", help="d, dd, ddd", default=0) def parse(self): self.log.info("Parsing common options") self.parsed = self.parser.parse_args() self.logLevel = self._parsePrintLevel(self.parsed.debug) self.configFile = self.parsed.configFile def optionDict(self): """Return dictionary of options.""" if not self.parsed: self.parse() return dict( configFile=self.configFile, logLevel=self.logLevel, debug=self.debug, ) def _parsePrintLevel(self, level): """Translate debug count to logging level.""" level = level if level <= 2 else 2 self.debug = level == 2 return [ logging.INFO, logging.INFO, logging.DEBUG, ][level]
ic-hep/DIRAC
docs/diracdoctools/Config.py
Python
gpl-3.0
8,487
[ "DIRAC" ]
ec7a6bebdc954764d25ffc1153c1b2b3d345ac53edb236e422b1f950ed26e912
#!/usr/bin/env python """ TO-DO: * Define a constructor if one is not present in the Python File * Actually, we should ALWAYS define the "new" constructor ourselves. Need to track the parameters to the __init__ function so we can call it from our "new" * Find and Track instance variables so they can be set in the constructor - Partially done. * Internal function translation * Translate this code to lua, and set up calls to the C modules. """ import sys import parser import symbol import token import ast from lua_python_functions import builtin_functions class FunctionType(object): input_type = None output_type_defined = False output_type = None def __repr__(self): return str(self) def __str__(self): return "(" + str(self.input_type) + ") -> (" + str(self.output_type) + ")" def get_type_name(x): if type(x) == dict: return "dict" elif type(x) == list: return "list" elif x == None: return "None" else: return x.__name__ def get_inner_type(x): if type(x) == list or type(x) == dict: atypes = set([type(i) for i in x]) if len(atypes) == 0: return None elif len(atypes) == 1: return list(atypes)[0] else: return None class type_inference_visitor(ast.NodeVisitor): function_stack = [] known_types = {} ast_node_to_type = {} # the mechanism in place is that # frame_i = self.known_types[i] gets the known variables in stack frame i # # frame_i[varname] is then the known type of the variable # If type is None, its type is unknown # If the type is a list (i.e. [int, int, str]) then the variable is known # to be a list of elements, of the given types # If the type is a dictionary (i.e. ["a":int, "b":int]) then the variable is # known to be a dictionary of elements of the given types # If the type is FunctionType, it is a function with that input and output def __init__(self): self.currentScopeLevel = 0 self.known_types[self.currentScopeLevel] = {} for x in builtin_functions: f = FunctionType() f.input_type = builtin_functions[x].input_type f.output_type = builtin_functions[x].output_type f.output_type_defined = True self.known_types[0][x] = f def parse(self, ast): return self.visit(ast) # gets a type of a variable name def get_type(self, x): for i in range(self.currentScopeLevel, -1, -1): if x in self.known_types[i]: return self.known_types[i][x] return None def getScopeString(self): retVal = "" for x in range(self.currentScopeLevel): retVal = retVal + "\t" return retVal def add_type(self, x, t): self.known_types[self.currentScopeLevel][x] = t def increaseScope(self): self.currentScopeLevel = self.currentScopeLevel + 1 if not self.currentScopeLevel in self.known_types: self.known_types[self.currentScopeLevel] = {} self.clearScope() def clearScope(self): self.known_types[self.currentScopeLevel] = {} def decreaseScope(self): for i in self.known_types[self.currentScopeLevel].keys(): inner_scope_type = self.known_types[self.currentScopeLevel][i] if i in self.known_types[self.currentScopeLevel - 1]: outer_scope_type = self.known_types[self.currentScopeLevel - 1][i] if inner_scope_type != outer_scope_type: self.known_types[self.currentScopeLevel - 1][i] = None else: self.known_types[self.currentScopeLevel - 1][i] = inner_scope_type self.currentScopeLevel = self.currentScopeLevel - 1 def visit_Expr(self, node): return self.visit(node.value) def visit_Module(self, node): for line in node.body: self.visit(line) self.ast_node_to_type[node] = None return None def visit_Str(self, node): self.ast_node_to_type[node] = str return str def visit_Num(self, node): self.ast_node_to_type[node] = type(node.n) return type(node.n) def visit_List(self, node): retVal = [] for elt in node.elts: retVal += [self.visit(elt)] self.ast_node_to_type[node] = retVal return retVal def visit_Dict(self, node): retVal = {} for elt in range(len(node.keys)): if type(node.keys[elt]) == ast.Str: retVal[node.keys[elt].s] = self.visit(node.values[elt]) self.ast_node_to_type[node] = retVal return retVal def visit_Index(self, node): ret = self.visit(node.value) self.ast_node_to_type[node] = ret return ret def visit_Subscript(self, node): nvaluetype = self.visit(node.value) self.ast_node_to_type[node.value] = nvaluetype t = self.get_type(node.value.id) if type(node.slice.value) == ast.Num: val = node.slice.value if type(t) == dict and val.n in t: self.ast_node_to_type[node] = t[val.n] return t[val.n] elif type(t) == list and val.n < len(t): self.ast_node_to_type[node] = t[val.n] return t[val.n] elif type(node.slice.value) == ast.Str and type(t) == dict: val = node.slice.value if val.s in t: self.ast_node_to_type[node] = t[val.s] return t[val.s] self.ast_node_to_type[node] = None return None def visit_Print(self, node): for arg in node.values: self.visit(arg) self.ast_node_to_type[node] = None return None def visit_Attribute(self, node): s = self.visit(node.value) if (s != None): k = get_type_name(s) + "." + node.attr ret = self.get_type(k) self.ast_node_to_type[node] = ret return ret else: return None def visit_Call(self, node): s = self.visit(node.func) # function calls can change the values of lists/dicts for arg in node.args: self.visit(arg) # if pass a list/dict by reference # the contents may change try: name = arg.id if (type(self.get_type(name)) == list): self.add_type(name, []) elif (type(self.get_type(name)) == dict): self.add_type(name, {}) except: pass if s and type(s) == FunctionType: self.ast_node_to_type[node] = s.output_type return s.output_type else: self.ast_node_to_type[node] = None return None def visit_ListComp(self, node): self.increaseScope() for gen in node.generators: itertype = self.visit(gen.iter) innertype = get_inner_type(itertype) if "ifs" in dir(gen): for ifs in gen.ifs: self.visit(gen.ifs) if "target" in dir(gen): self.visit(gen.target) self.ast_node_to_type[gen.target] = innertype self.add_type(gen.target.id, innertype) self.visit(node.elt) self.clearScope() self.decreaseScope() self.ast_node_to_type[node] = [] return [] def visit_GeneratorExp(self, node): return self.visit_ListComp(node) def visit_For(self, node): itertype = self.visit(node.iter) self.ast_node_to_type[node.iter] = itertype self.add_type(node.target.id, itertype) targettype = self.visit(node.target) self.ast_node_to_type[node.target] = targettype self.increaseScope() for line in node.body: self.visit(line) self.decreaseScope() self.ast_node_to_type[node] = None return None def visit_While(self, node): self.increaseScope() for line in node.body: self.visit(line) self.decreaseScope() self.ast_node_to_type[node] = None return None def visit_IfExp(self, node): reta = self.visit(node.body) if "orelse" in dir(node) and node.orelse != None: retb = self.visit(node.orelse) if (reta == retb): self.ast_node_to_type[node] = reta return reta else: self.ast_node_to_type[node] = None return None def visit_If(self, node): self.increaseScope() for line in node.body: self.visit(line) self.decreaseScope() if "orelse" in dir(node) and node.orelse != None: self.increaseScope() for line in node.orelse: self.visit(line) self.decreaseScope() self.ast_node_to_type[node] = None return None def visit_BoolOp(self, node): self.ast_node_to_type[node] = bool return bool def visit_BinOp(self, node): ret = self.visit(node.left) self.visit(node.right) if type(ret) == list: self.ast_node_to_type[node] = [] return [] elif type(ret) == dict: self.ast_node_to_type[node] = {} return {} else: return ret def visit_Compare(self, node): self.visit(node.left) for x in node.comparators: self.visit(x) self.ast_node_to_type[node] = bool return bool def visit_Assign(self, node): value = self.visit(node.value) tnode = node.targets[0] if type(tnode) == ast.Name: target = tnode self.add_type(target.id, value) self.ast_node_to_type[node] = value elif type(tnode) == ast.Attribute and type(tnode.value) == ast.Name: target = tnode.value.id + "." + tnode.attr self.add_type(target, value) self.ast_node_to_type[node] = value value = self.visit(node.targets[0]) return value def visit_AugAssign(self, node): self.visit(node.target) self.visit(node.value) if type(self.get_type(node.target.id)) == list: self.add_type(node.target.id, []) elif type(self.get_type(node.target.id)) == dict: self.add_type(node.target.id, {}) else: self.add_type(node.target.id, None) self.ast_node_to_type[node] = self.get_type(node.target.id) return None def visit_arguments(self, node): ret = () for arg in node.args: ret += tuple([self.get_type(arg.id)]) self.ast_node_to_type[node] = ret return ret def visit_Name(self, node): ret = self.get_type(node.id) print node.lineno,node.col_offset,":", node.id,"=", ret self.ast_node_to_type[node] = ret return ret def visit_Return(self, node): rettype = self.visit(node.value) lastfn = self.function_stack[len(self.function_stack) - 1] if not lastfn.output_type_defined: lastfn.output_type = rettype lastfn.output_type_defined = True elif lastfn.output_type != rettype: lastfn.output_type = None self.ast_node_to_type[node] = None return None def visit_Lambda(self, node): ret = self.visit_FunctionDef(node) self.ast_node_to_type[node] = ret return ret def visit_FunctionDef(self, node): """ Need to go through the fields of this node to get the function name. Will have to do this again with the parameters """ funName = "" islambda = True if ("name" in dir(node)): funName = node.name islambda = False f = FunctionType() f.input_type = self.visit(node.args) self.function_stack.append(f) self.increaseScope() if islambda == False: for line in node.body: self.visit(line) else: lastfn = self.function_stack[len(self.function_stack) - 1] lastfn.outputtype = self.visit(node.body) lastfn.output_type_defined = True self.clearScope() self.decreaseScope() ret_type = self.function_stack.pop() if funName != "": self.add_type(funName, ret_type) self.ast_node_to_type[node] = ret_type return ret_type def visit_UAdd(self, node): """ This operator in python quite literally does nothing. """ return "" def visit_USub(self, node): """ this is just the negation operator. """ return "-" def visit_ClassDef(self, node): raise NotImplementedError("Classes are not implemented") class translator_NodeVisitor(ast.NodeVisitor): ifFlag = False # a dictionary from old function name to new function name # the substitute will only happen once. rename_function = {} # A dictionary from the function name to the known type of a # function(FunctionType). This happens after the function name. function_known_types = {} known_types = None predeclarations = [] builtin_declarations = [] def __init__(self, file): self.f = file self.currentScopeLevel = 0 self.known_types = type_inference_visitor() self.builtin_declarations = [] self.rename_function = {} self.function_known_types = {} self.builtin_declarations += ["list = require 'pl.List'"] self.builtin_declarations += ["dict = require 'pl.Map'"] def translate_ast(self, ast_node): print(ast.dump(ast_node)) self.known_types.visit(ast_node) t = self.visit(ast_node) self.predeclarations = list(set(self.predeclarations)) if not t: t = "" t = "\n".join(self.builtin_declarations) + "\n" + "\n".join(self.predeclarations) + "\n" + t if self.f: self.f.write(t) else: return t # gets a type of an ast node def get_type(self, x): if (x in self.known_types.ast_node_to_type): return self.known_types.ast_node_to_type[x] else: return None """Handle Scoping""" def increaseScope(self): self.currentScopeLevel = self.currentScopeLevel + 1 def decreaseScope(self): self.currentScopeLevel = self.currentScopeLevel - 1 def getScopeString(self): retVal = "" for x in range(self.currentScopeLevel): retVal = retVal + "\t" return retVal """"End Handle Scoping""" def visit_Expr(self, node): return self.visit(node.value) def visit_Module(self, node): ret = "" for line in node.body: retline = self.visit(line) if retline: ret += retline + "\n" return ret def visit_Str(self, node): return "\"" + node.s + "\"" def visit_Num(self, node): return str(node.n) def visit_List(self, node): retVal = "list({" commaFlag = 0 for elt in node.elts: if commaFlag: retVal = retVal + ", " retVal = retVal + self.visit(elt) commaFlag = 1 return retVal + "})" def visit_Dict(self, node): retVal = "dict({" commaFlag = 0 for elt in range(len(node.keys)): if commaFlag: retVal = retVal + ", " retVal = retVal + "[" + self.visit(node.keys[elt]) + "] = " + self.visit(node.values[elt]) commaFlag = 1 return retVal + "})" def visit_Index(self, node): if (type(node.value) == ast.Num): return self.visit(node.value) else: return self.visit(node.value) def visit_Subscript(self, node): idx = self.visit(node.slice) nodetype = self.get_type(node.value) if type(self.get_type(node.value)) == list: return node.value.id + "[(" + idx + ") + 1]" elif type(self.get_type(node.value)) == dict: return node.value.id + "[" + idx + "]" else: raise NotImplementedError("Ambiguous array index at " + str(node.lineno) + ":" + str(node.col_offset)) def visit_Print(self, node): retVal = "print(" commaFlag = 0 for arg in node.values: if commaFlag: retVal = retVal + ", " retVal = retVal + self.visit(arg) commaFlag = 1 retVal = retVal + ")" return retVal def builtin_substitute(self, name): if name in builtin_functions: if builtin_functions[name].predeclarations and len(builtin_functions[name].predeclarations) > 0: self.predeclarations += [builtin_functions[name].predeclarations] return builtin_functions[name].translatefn else: return None def visit_Attribute(self, node): s = self.visit(node.value) # check if its a reference to a builtin function function k = get_type_name(self.get_type(node.value)) + "." + node.attr ret = self.builtin_substitute(k) if ret: return ret % s else: return s + "." + node.attr def visit_Call(self, node): retVal = "" funcName = self.visit(node.func) funcArgs = "" commaFlag = 0 for arg in node.args: if commaFlag: funcArgs = funcArgs + ", " funcArgs = funcArgs + self.visit(arg) commaFlag = 1 retVal = funcName + "(" + funcArgs + ")" return retVal def visit_GeneratorExp(self, node): return self.visit_ListComp(node) def visit_ListComp(self, node): if len(node.generators) != 1: raise NotImplementedError("List comprehension with only one generator not implemented") tab = self.visit(node.generators[0].iter) var = node.generators[0].target.id vartype = self.get_type(node.generators[0].iter) ifs = [] if "ifs" in dir(node.generators[0]): ifs = node.generators[0].ifs # we generate a lambda function which iterates over the table s = "(function() \n" self.increaseScope() s += self.getScopeString() + "local __rett__ = list({})\n" s += self.getScopeString() + "local __t__ = " + tab + "\n" if (type(vartype) == list): s += self.getScopeString() + "for " + var + " in list.iter(__t__) do\n" elif (type(vartype) == dict): s += self.getScopeString() + "for " + var + " in pairs(__t__) do\n" else: raise NotImplementedError("We can only iterate over dictionaries and lists") self.increaseScope() s += self.getScopeString() + "local __v__ = " + self.visit(node.elt) + "\n" if len(ifs) > 0: ifvars = [] for i in range(len(ifs)): ifvar = "__t" + str(i) + "__" s += self.getScopeString() + "local " + ifvar + " = " + self.visit(ifs[i]) + "\n" ifvars += [ifvar] s += self.getScopeString() + "if " + " and ".join(ifvars) + " then \n" self.increaseScope() s += self.getScopeString() + "__rett__[#__rett__ + 1] = __v__\n" if len(ifs) > 0: self.decreaseScope() s += self.getScopeString() + "end\n" self.decreaseScope() s += self.getScopeString() + "end\n" s += self.getScopeString() + "return __rett__\n" self.decreaseScope() s += self.getScopeString() + "end)()" return s """ Begin Conditionals """ def getBodyString(self, body): retVal = "" for line in body: retVal = retVal + self.getScopeString() + self.visit(line) + "\n" return retVal; def visit_For(self, node): retVal = "" self.visit(node.iter) loopVar = self.visit(node.target) iterVar = self.visit(node.iter) vartype = self.get_type(node.iter) if (type(vartype) == list): retVal += self.getScopeString() + "for " + loopVar + " in list.iter(" + iterVar + ") do\n" elif (type(vartype) == dict): retVal += self.getScopeString() + "for " + loopVar + " in pairs(" + iterVar + ") do\n" else: raise NotImplementedError("We can only iterate over dictionaries and lists") self.increaseScope() #Note that body is a list. for line in node.body: retVal += self.getScopeString() + self.visit(line) + "\n" #loopBody = self.visit(node.body) self.decreaseScope() retVal += self.getScopeString() + "end\n" return retVal def visit_While(self, node): condition = self.visit(node.test) bodyString = "" self.increaseScope() for line in node.body: bodyString = self.getScopeString() + self.visit(line) + "\n" self.decreaseScope() return "while " + condition + " do\n" + bodyString + self.getScopeString() + "end" def visit_IfExp(self, node): ret = self.visit(node.test) + " and " + self.visit(node.body) if "orelse" in dir(node) and node.orelse != None: ret += " or " + self.visit(node.orelse) return ret def visit_If(self, node): retVal = "" topLevel = False if self.ifFlag: retVal = "elseif " else: retVal = "if " self.ifFlag = True topLevel = True condition = self.visit(node.test) retVal += condition + " then\n" self.increaseScope() bodyString = self.getBodyString(node.body).rstrip() self.decreaseScope() retVal = retVal + bodyString + "\n" + self.getScopeString() orelse_list = [] for elt in node.orelse: orelse_list.append(self.visit(elt)) shift="" if orelse_list[0].split()[0] != "elseif": retVal = retVal + "else\n" self.increaseScope() shift = self.getScopeString() self.decreaseScope() for line in orelse_list: retVal = retVal + shift + line.rstrip() + "\n" if topLevel: retVal = retVal.rstrip() + "\n" + self.getScopeString() + "end" self.ifFlag = False return retVal """ End conditionals """ """ Binary Operators Begin """ def visit_Add(self, node): return "+" def visit_Sub(self, node): return "-" def visit_Mult(self, node): return "*" def visit_Div(self, node): return "/" def visit_FloorDiv(self, node): return "/" #In Lua, there's only one type of division. This will have to do. def visit_Mod(self, node): return "%" def visit_Pow(self, node): return "^" """ Binary Operators End """ """ Unary Operators Begin """ def visit_Invert(self, node): """ This returns the bitwise inversion of the operand. For example, in python, ~x == -(x+1) !!Will need a library for this!! """ return "" def visit_Not(self, node): return "not" def visit_UAdd(self, node): """ This operator in python quite literally does nothing. """ return "" def visit_USub(self, node): """ this is just the negation operator. """ return "-" """ Unary Operators End """ """ Comparison Operators Begin """ def visit_Eq(self, node): return "==" def visit_NotEq(self, node): return "~=" def visit_Lt(self, node): return "<" def visit_LtE(self, node): return "<=" def visit_Gt(self, node): return ">" def visit_GtE(self, node): return ">=" def visit_Is(self, node): print("ERROR: Operation not supported!!!") return "ERROR: Operation not supported!!!" def visit_IsNot(self, node): print("ERROR: Operation not supported!!!") return "ERROR: Operation not supported!!!" def visit_In(self, node): print("ERROR: Operation not supported!!!") return "ERROR: Operation not supported!!!" def visit_NotIn(self, node): print("ERROR: Operation not supported!!!") return "ERROR: Operation not supported!!!" def visit_AugAssign(self, node): return self.visit(node.target) + "=" + self.visit(node.target) + self.visit(node.op) + self.visit(node.value) """ Comparison Operators End """ """ expr Begin """ def visit_BoolOp(self, node): op = self.visit(node.op) values = self.visit(node.values) return op + " " + values def visit_BinOp(self, node): l = self.visit(node.left) op = self.visit(node.op) r = self.visit(node.right) if (op == "+"): ltype = self.get_type(node.left) rtype = self.get_type(node.right) if ltype == str and rtype == str: retVal = l + " .. " + r elif ltype == str or rtype == str: raise TypeError("Cannot add " + str(ltype) + " and " + str(rtype) + " at " + str(node.lineno) + ":" + str(node.col_offset)) elif ltype in [int, float] and rtype in [int, float]: retVal = l + " + " + r elif ltype == None or rtype == None: raise NotImplementedError("Ambiguous addition at " + str(node.lineno) + ":" + str(node.col_offset)) else: retVal = l + " + " + r else: retVal = l + " " + op + " " + r return retVal def visit_Compare(self, node): l = self.visit(node.left); op = "" r = "" for x in node.ops: if op == "": op = self.visit(x) else: print "Error: Too many compare operations" for x in node.comparators: if r == "": r = self.visit(x) else: print "Error: Too many comparators" return l + " " + op + " " + r def visit_Assign(self, node): target = node.targets[0].id value = self.visit(node.value) return target + " = " + value def visit_arguments(self, node): #push the work down another level commaFlag = 0 ret = "" for arg in node.args: #Skip the self arguements, for now if arg.id != "self": if not commaFlag: commaFlag = 1 else: ret += (", ") ret += (arg.id) return ret def visit_Name(self, node): ret = self.builtin_substitute(node.id) if ret: return ret else: return node.id def visit_Return(self, node): return "return " + self.visit(node.value) def visit_Lambda(self, node): return self.visit_FunctionDef(node) def visit_FunctionDef(self, node): funName = "" islambda = True if ("name" in dir(node)): funName = node.name islambda = False newline = "\n" if islambda: newline = "" outstr = "" if funName in self.rename_function: oldfname = funName funName = self.rename_function[funName] del self.rename_function[oldfname] elif funName == None and "" in self.rename_function: funName = self.rename_function[""] del self.rename_function[""] if funName in self.function_known_types: # ok. we need to reannotate this vertex self.known_types.increaseScope() i = 0 for arg in node.args.args: itype = self.function_known_types[funName].input_type[i] self.known_types.add_type(arg.id, itype) i += 1 self.known_types.visit_FunctionDef(node) self.known_types.decreaseScope() if (funName == None or len(funName) == 0): outstr += "function (" else: outstr += ("function " + funName + "(") outstr += self.visit(node.args) outstr += ")" bodyString = "" if (islambda): outstr += " return "; self.increaseScope() if islambda == False: for line in node.body: res = self.visit(line) if res: bodyString = bodyString + self.getScopeString() + self.visit(line) + newline else: bodyString = bodyString + self.visit(node.body) + newline #because of how LUA works, have to define the instance #variables in the new function outstr += (newline + bodyString); outstr += (" end" + newline) self.decreaseScope() return outstr def visit_ClassDef(self, node): raise NotImplementedError("Classes are not implemented") if __name__ == "__main__": if len(sys.argv) <= 1: print("Usage:\n\t./Lua_Translator.py <FILENAME>\n") exit(-1) f = open(sys.argv[1] , 'r') l = f.readlines() f.close() s = "" for x in l: s = s + x ast_node = ast.parse(s) f = open(sys.argv[1].rpartition(".")[0] + "_trans.lua", 'w') test = translator_NodeVisitor(f) test.translate_ast(ast_node) f.close()
ypkang/Dato-Core
src/unity/python/graphlab/Lua_Translator.py
Python
agpl-3.0
30,207
[ "VisIt" ]
1196f8f351d7236f69173d82d0c1a8060e2d885e16cdb671bca089ebd659f096
try: from ..nbody_graph_search import Ugraph except: # not installed as a module from nbody_graph_search import Ugraph # To find 4-body "improper" interactions, # (by default, most of the time), we would use this subgraph: # 0 # * 1st bond connects atoms 1 and 0 # | => 2nd bond connects atoms 1 and 2 # _.*._ 3rd bond connects atoms 1 and 3 # *' 1 `* # 2 3 # # In OPLS, the central atom is the second atom ("1"). # This differs from other force-fields. # We take this detail into account in the line below: bond_pattern = Ugraph([(1,0), (1,2), (1,3)]) # As with other force-fields, the improper-angle is the angle between the planes # defined by the first three atoms (0,1,2) and last three atoms (1,2,3). # (This is implemented in LAMMPS using an improper_style which requires # that the atoms in the interaction will be listed in this order: 0,1,2,3.) def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 4 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of an improper interactions is a function of the improper angle. The "improper angle" is often defined as the angle between planes formed by atoms 0,1,2 & 1,2,3. (Alternately, it is sometimes defined as the angle between the 0,1,2 plane and atom 3.) This angle does not change when swapping the OUTER pair of atoms (0 and 3) (except for a change of sign, which does not matter since the energy functions used are typically sign invariant. Furthermore, neither of OUTER pair of atoms are the central atom. There are 3!=6 ways of ordering the remaining 3 atoms.) Consequently it does not make sense to define a separate 4-body improper- interaction between atoms 0,1,2,3 AS WELL AS between 3,1,2,0. So we sort the atoms and bonds so that the first atom has a always has a lower atomID than the last atom. (Later we will check to see if we have already defined an interaction between these 4 atoms. If not then we create a new one.) """ atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] atom3 = match[0][3] # match[1][0:2] contains the ID numbers for the 3 bonds bond0 = match[1][0] bond1 = match[1][1] bond2 = match[1][2] if atom0 <= atom3: #return ((atom0,atom1,atom2,atom3), (bond0, bond1, bond2)) # But this is the same thing as: return match else: return ((atom3,atom1,atom2,atom0), (bond2,bond1,bond0))
quang-ha/lammps
tools/moltemplate/moltemplate/nbody_alt_symmetry/cenJswapIL.py
Python
gpl-2.0
3,203
[ "LAMMPS" ]
3b1cb9be667cebc0b8784b96e7b063e6d871e1d382df56840f48a9bcd6145662
#!/usr/bin/env python # Dan Blankenberg from __future__ import print_function import optparse import os import subprocess import sys from json import dumps, loads CHUNK_SIZE = 2**20 TWO_GB = 2**30 * 2 DEFAULT_DATA_TABLE_NAME = "bwa_mem_indexes" def get_id_name( params, dbkey, fasta_description=None): # TODO: ensure sequence_id is unique and does not already appear in location file sequence_id = params['param_dict']['sequence_id'] if not sequence_id: sequence_id = dbkey sequence_name = params['param_dict']['sequence_name'] if not sequence_name: sequence_name = fasta_description if not sequence_name: sequence_name = dbkey return sequence_id, sequence_name def build_bwa_index( data_manager_dict, fasta_filename, params, target_directory, dbkey, sequence_id, sequence_name, data_table_name=DEFAULT_DATA_TABLE_NAME ): # TODO: allow multiple FASTA input files fasta_base_name = os.path.split( fasta_filename )[-1] sym_linked_fasta_filename = os.path.join( target_directory, fasta_base_name ) os.symlink( fasta_filename, sym_linked_fasta_filename ) if params['param_dict']['index_algorithm'] == 'automatic': if os.stat( fasta_filename ).st_size < TWO_GB: # use 2 GB as cut off for memory vs. max of 2gb database size; this is somewhat arbitrary index_algorithm = 'is' else: index_algorithm = 'bwtsw' else: index_algorithm = params['param_dict']['index_algorithm'] args = [ 'bwa', 'index', '-a', index_algorithm ] args.append( sym_linked_fasta_filename ) proc = subprocess.Popen( args=args, shell=False, cwd=target_directory ) return_code = proc.wait() if return_code: print("Error building index.", file=sys.stderr) sys.exit( return_code ) data_table_entry = dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_name ) _add_data_table_entry( data_manager_dict, data_table_name, data_table_entry ) def _add_data_table_entry( data_manager_dict, data_table_name, data_table_entry ): data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} ) data_manager_dict['data_tables'][ data_table_name ] = data_manager_dict['data_tables'].get( data_table_name, [] ) data_manager_dict['data_tables'][ data_table_name ].append( data_table_entry ) return data_manager_dict def main(): parser = optparse.OptionParser() parser.add_option( '-f', '--fasta_filename', dest='fasta_filename', action='store', type="string", default=None, help='fasta_filename' ) parser.add_option( '-d', '--fasta_dbkey', dest='fasta_dbkey', action='store', type="string", default=None, help='fasta_dbkey' ) parser.add_option( '-t', '--fasta_description', dest='fasta_description', action='store', type="string", default=None, help='fasta_description' ) parser.add_option( '-n', '--data_table_name', dest='data_table_name', action='store', type="string", default=None, help='data_table_name' ) (options, args) = parser.parse_args() filename = args[0] params = loads( open( filename ).read() ) target_directory = params[ 'output_data' ][0]['extra_files_path'] os.mkdir( target_directory ) data_manager_dict = {} dbkey = options.fasta_dbkey if dbkey in [ None, '', '?' ]: raise Exception( '"%s" is not a valid dbkey. You must specify a valid dbkey.' % ( dbkey ) ) sequence_id, sequence_name = get_id_name( params, dbkey=dbkey, fasta_description=options.fasta_description ) # build the index build_bwa_index( data_manager_dict, options.fasta_filename, params, target_directory, dbkey, sequence_id, sequence_name, data_table_name=options.data_table_name or DEFAULT_DATA_TABLE_NAME ) # save info to json file open( filename, 'wb' ).write( dumps( data_manager_dict ) ) if __name__ == "__main__": main()
blankclemens/tools-iuc
data_managers/data_manager_bwa_mem_index_builder/data_manager/bwa_mem_index_builder.py
Python
mit
3,896
[ "BWA" ]
efd5466e1256c298010c6eb6659df4bee1b5bab553f736030718c9e25db61ec1
""" ============================================================ Sparse recovery: feature selection for sparse linear models ============================================================ Given a small number of observations, we want to recover which features of X are relevant to explain y. For this :ref:`sparse linear models <l1_feature_selection>` can outperform standard statistical tests if the true model is sparse, i.e. if a small fraction of the features are relevant. As detailed in :ref:`the compressive sensing notes <compressive_sensing>`, the ability of L1-based approach to identify the relevant variables depends on the sparsity of the ground truth, the number of samples, the number of features, the conditionning of the design matrix on the signal subspace, the amount of noise, and the absolute value of the smallest non-zero coefficient [Wainwright2006] (http://statistics.berkeley.edu/tech-reports/709.pdf). Here we keep all parameters constant and vary the conditionning of the design matrix. For a well-conditionned design matrix (small mutual incoherence) we are exactly in compressive sensing conditions (i.i.d Gaussian sensing matrix), and L1-recovery with the Lasso performs very well. For an ill-conditionned matrix (high mutual incoherence), regressors are very correlated, and the Lasso randomly selects one. However, randomized-Lasso can recover the ground truth well. In each situation, we first vary the alpha parameter setting the sparsity of the estimated model and look at the stability scores of the randomized Lasso. This analysis, knowing the ground truth, shows an optimal regime in which relevant features stand out from the irrelevant ones. If alpha is chosen too small, non-relevant variables enter the model. On the opposite, if alpha is selected too large, the Lasso is equivalent to stepwise regression, and thus brings no advantage over a univariate F-test. In a second time, we set alpha and compare the performance of different feature selection methods, using the area under curve (AUC) of the precision-recall. """ print __doc__ # Author: Alexandre Gramfort and Gael Varoquaux # License: BSD import pylab as pl import numpy as np from scipy import linalg from sklearn.linear_model import (RandomizedLasso, lasso_stability_path, LassoLarsCV) from sklearn.feature_selection import f_regression from sklearn.preprocessing import StandardScaler from sklearn.metrics import auc, precision_recall_curve from sklearn.ensemble import ExtraTreesRegressor from sklearn.utils.extmath import pinvh def mutual_incoherence(X_relevant, X_irelevant): """Mutual incoherence, as defined by formula (26a) of [Wainwright2006]. """ projector = np.dot(np.dot(X_irelevant.T, X_relevant), pinvh(np.dot(X_relevant.T, X_relevant))) return np.max(np.abs(projector).sum(axis=1)) for conditionning in (1, 1e-4): ########################################################################### # Simulate regression data with a correlated design n_features = 501 n_relevant_features = 3 noise_level = .2 coef_min = .2 # The Donoho-Tanner phase transition is around n_samples=25: below we # will completely fail to recover in the well-conditionned case n_samples = 25 block_size = n_relevant_features rng = np.random.RandomState(42) # The coefficients of our model coef = np.zeros(n_features) coef[:n_relevant_features] = coef_min + rng.rand(n_relevant_features) # The correlation of our design: variables correlated by blocs of 3 corr = np.zeros((n_features, n_features)) for i in range(0, n_features, block_size): corr[i:i + block_size, i:i + block_size] = 1 - conditionning corr.flat[::n_features + 1] = 1 corr = linalg.cholesky(corr) # Our design X = rng.normal(size=(n_samples, n_features)) X = np.dot(X, corr) # Keep [Wainwright2006] (26c) constant X[:n_relevant_features] /= np.abs( linalg.svdvals(X[:n_relevant_features])).max() X = StandardScaler().fit_transform(X.copy()) # The output variable y = np.dot(X, coef) y /= np.std(y) # We scale the added noise as a function of the average correlation # between the design and the output variable y += noise_level * rng.normal(size=n_samples) mi = mutual_incoherence(X[:, :n_relevant_features], X[:, n_relevant_features:]) ########################################################################### # Plot stability selection path, using a high eps for early stopping # of the path, to save computation time alpha_grid, scores_path = lasso_stability_path(X, y, random_state=42, eps=0.05) pl.figure() # We plot the path as a function of alpha/alpha_max to the power 1/3: the # power 1/3 scales the path less brutally than the log, and enables to # see the progression along the path hg = pl.plot(alpha_grid[1:] ** .333, scores_path[coef != 0].T[1:], 'r') hb = pl.plot(alpha_grid[1:] ** .333, scores_path[coef == 0].T[1:], 'k') ymin, ymax = pl.ylim() pl.xlabel(r'$(\alpha / \alpha_{max})^{1/3}$') pl.ylabel('Stability score: proportion of times selected') pl.title('Stability Scores Path - Mutual incoherence: %.1f' % mi) pl.axis('tight') pl.legend((hg[0], hb[0]), ('relevant features', 'irrelevant features'), loc='best') ########################################################################### # Plot the estimated stability scores for a given alpha # Use 6-fold cross-validation rather than the default 3-fold: it leads to # a better choice of alpha: lars_cv = LassoLarsCV(cv=6).fit(X, y) # Run the RandomizedLasso: we use a paths going down to .1*alpha_max # to avoid exploring the regime in which very noisy variables enter # the model alphas = np.linspace(lars_cv.alphas_[0], .1 * lars_cv.alphas_[0], 6) clf = RandomizedLasso(alpha=alphas, random_state=42).fit(X, y) trees = ExtraTreesRegressor(100, compute_importances=True).fit(X, y) # Compare with F-score F, _ = f_regression(X, y) pl.figure() for name, score in [('F-test', F), ('Stability selection', clf.scores_), ('Lasso coefs', np.abs(lars_cv.coef_)), ('Trees', trees.feature_importances_), ]: precision, recall, thresholds = precision_recall_curve(coef != 0, score) pl.semilogy(np.maximum(score / np.max(score), 1e-4), label="%s. AUC: %.3f" % (name, auc(recall, precision))) pl.plot(np.where(coef != 0)[0], [2e-4] * n_relevant_features, 'mo', label="Ground truth") pl.xlabel("Features") pl.ylabel("Score") # Plot only the 100 first coefficients pl.xlim(0, 100) pl.legend(loc='best') pl.title('Feature selection scores - Mutual incoherence: %.1f' % mi) pl.show()
mrshu/scikit-learn
examples/linear_model/plot_sparse_recovery.py
Python
bsd-3-clause
7,103
[ "Gaussian" ]
9ad15b0768595b0d0ecb252ee84530a107905d2b5a706efa522e0366a13d03d0
#!/usr/bin/env python """ Reads amber .prmtop and .inpcrd Outputs gaussian .com """ import argparse import os import sys # oniomMacGyver modules from omg import prmtop def get_args(): """ Parse arguments of amb_prmtop2gaucom.py """ parser = argparse.ArgumentParser( description=""" Reads Amber topology (.prmtop) and coordinates (.inpcrd) to produce a Gaussian input (.com). """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('top', help='Amber topology (.prmtop / .top)') parser.add_argument('crd', help='Amber coordinates (.inpcrd / .crd)') parser.add_argument('--com', help='Name for new Gaussian input (.com)', default=None) parser.add_argument('--notip3p', help='dont print TIP3P HrmBnd1', default=False, action='store_true') parser.add_argument('--vmdsel', help='VMD like selection ("not resname WAT")', default='') args = parser.parse_args() if not args.com: args.com = os.path.splitext(args.top)[0] + '.com' # check if output exists if os.path.exists(args.com): sys.stderr.write('%s already exists. Aborting.\n' % (args.com)) sys.exit(2) return args def main(): """ Reads amber .prmtop and .inpcrd Outputs gaussian .com """ args = get_args() mytop = prmtop.Prmtop(args.top) mytop.gen_oniom(args.com, args.crd, args.notip3p, args.vmdsel) if __name__ == "__main__": main()
eduardoftoliveira/qt_scripts
scripts/gau_prmtop2gaucom.py
Python
gpl-3.0
1,560
[ "Amber", "Gaussian", "VMD" ]
cb6b924ffd93f9c989e68de6b30aa7da58e1b23f1da43097751a74afd5bdaa47
#!/usr/bin/env python # # Appcelerator Titanium Module Packager # # import os, subprocess, 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 = ['architectures', '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 find_sdk(config): sdk = config['TITANIUM_SDK'] return os.path.expandvars(os.path.expanduser(sdk)) 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): docdir = os.path.join(cwd,'..','documentation') if not os.path.exists(docdir): print "Couldn't find documentation file at: %s" % docdir return None 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','co.kommit.gtm.js') if not os.path.exists(js_file): js_file = os.path.join(cwd,'..','assets','co.kommit.gtm.js') if not os.path.exists(js_file): return from compiler import Compiler try: import json except: import simplejson as json compiler = Compiler(cwd, manifest['moduleid'], manifest['name'], 'commonjs') root_asset, module_assets = compiler.compile_module() root_asset_content = """ %s return filterDataInRange([NSData dataWithBytesNoCopy:data length:sizeof(data) freeWhenDone:NO], ranges[0]); """ % root_asset module_asset_content = """ %s NSNumber *index = [map objectForKey:path]; if (index == nil) { return nil; } return filterDataInRange([NSData dataWithBytesNoCopy:data length:sizeof(data) freeWhenDone:NO], ranges[index.integerValue]); """ % module_assets from tools import splice_code assets_router = os.path.join(cwd,'Classes','CoKommitGtmModuleAssets.m') splice_code(assets_router, 'asset', root_asset_content) splice_code(assets_router, 'resolve_asset', module_asset_content) # Generate the exports after crawling all of the available JS source exports = open('metadata.json','w') json.dump({'exports':compiler.exports }, exports) exports.close() def die(msg): print msg sys.exit(1) def warn(msg): print "[WARN] %s" % msg def validate_license(): license_file = os.path.join(cwd,'LICENSE') if not os.path.exists(license_file): license_file = os.path.join(cwd,'..','LICENSE') if os.path.exists(license_file): c = open(license_file).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 manifest[key].strip() == '': die("manifest key '%s' missing required value" % 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'] ignoreDirs = ['.DS_Store','.svn','.git','CVSROOT'] def zip_dir(zf,dir,basepath,ignore=[],includeJSFiles=False): 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 if not includeJSFiles and len(e) == 2 and e[1] == '.js': 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): from tools import ensure_dev_path ensure_dev_path() 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 verify_build_arch(manifest, config): binaryname = 'lib%s.a' % manifest['moduleid'] binarypath = os.path.join('build', binaryname) manifestarch = set(manifest['architectures'].split(' ')) output = subprocess.check_output('xcrun lipo -info %s' % binarypath, shell=True) builtarch = set(output.split(':')[-1].strip().split(' ')) if ('arm64' not in builtarch): warn('built module is missing 64-bit support.') if (manifestarch != builtarch): warn('there is discrepancy between the architectures specified in module manifest and compiled binary.') warn('architectures in manifest: %s' % ', '.join(manifestarch)) warn('compiled binary architectures: %s' % ', '.join(builtarch)) die('please update manifest to match module binary architectures.') 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) p = os.path.join(cwd, 'assets') if not os.path.exists(p): p = os.path.join(cwd, '..', 'assets') if os.path.exists(p): zip_dir(zf,p,'%s/%s' % (modulepath,'assets'),['README']) # for dn in ('example','platform'): # p = os.path.join(cwd, dn) # if not os.path.exists(p): # p = os.path.join(cwd, '..', dn) # if os.path.exists(p): # zip_dir(zf,p,'%s/%s' % (modulepath,dn),['README'],True) license_file = os.path.join(cwd,'LICENSE') if not os.path.exists(license_file): license_file = os.path.join(cwd,'..','LICENSE') if os.path.exists(license_file): zf.write(license_file,'%s/LICENSE' % modulepath) zf.write('module.xcconfig','%s/module.xcconfig' % modulepath) exports_file = 'metadata.json' if os.path.exists(exports_file): zf.write(exports_file, '%s/%s' % (modulepath, exports_file)) zf.close() os.rename(modulezip, "dist/%s" % modulezip) subprocess.call(["unzip","-o", "dist/%s" % modulezip, "-d", "../example"]) if __name__ == '__main__': manifest,mf = validate_manifest() validate_license() config = read_ti_xcconfig() sdk = find_sdk(config) sys.path.insert(0,os.path.join(sdk,'iphone')) sys.path.append(os.path.join(sdk, "common")) compile_js(manifest,config) build_module(manifest,config) verify_build_arch(manifest, config) package_module(manifest,mf,config) sys.exit(0)
kommitters/co.kommit.gtm
iphone/build.py
Python
mit
8,618
[ "VisIt" ]
bcb3525d645c0b0b17c90a617b4bc1129facbf8091430ecc128898eaf92be67d
# -*- coding: utf-8 -*- # # Buildbot documentation build configuration file, created by # sphinx-quickstart on Tue Aug 10 15:13:31 2010. # # This file is exec()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import pkg_resources import sys import textwrap # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(1, os.path.dirname(os.path.abspath(__file__))) try: from buildbot.util.raml import RamlSpec except ImportError: sys.path.insert(2, os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) from buildbot.util.raml import RamlSpec # -- General configuration ----------------------------------------------- try: import sphinxcontrib.blockdiag assert sphinxcontrib.blockdiag except ImportError: raise RuntimeError("sphinxcontrib.blockdiag is not installed. " "Please install documentation dependencies with `pip install buildbot[docs]`") try: pkg_resources.require('docutils>=0.8') except pkg_resources.ResolutionError: raise RuntimeError("docutils is not installed or has incompatible version. " "Please install documentation dependencies with `pip install buildbot[docs]`") # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.extlinks', 'bbdocs.ext', 'bbdocs.highlighterrors', 'sphinxcontrib.blockdiag', 'sphinxcontrib.jinja', ] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Buildbot' copyright = u'Buildbot Team Members' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. if 'VERSION' in os.environ: version = os.environ['VERSION'] else: gl = {'__file__': '../buildbot/__init__.py'} with open('../buildbot/__init__.py') as f: exec(f.read(), gl) version = gl['version'] # The full version, including alpha/beta/rc tags. release = version # blocksiag/seqdiag blockdiag_html_image_format = 'svg' blocdiag_transparency = True # add a loud note for anyone looking at the latest docs if release == 'latest': rst_prolog = textwrap.dedent("""\ .. caution:: This page documents the latest, unreleased version of Buildbot. For documentation for released versions, see http://docs.buildbot.net/current/. """) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'release-notes/*.rst'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'trac' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] intersphinx_mapping = { 'python': ('https://python.readthedocs.io/en/latest/', None), 'sqlalchemy': ('https://sqlalchemy.readthedocs.io/en/latest/', None), } extlinks = { 'pull': ('https://github.com/buildbot/buildbot/pull/%s', 'pull request '), 'issue': ('https://github.com/buildbot/buildbot/issues/%s', 'issue # '), # deprecated. Use issue instead, and point to Github 'bug': ('http://trac.buildbot.net/ticket/%s', 'bug #'), # Renders as link with whole url, e.g. # :src-link:`master` # renders as # "https://github.com/buildbot/buildbot/blob/master/master". # Explicit title can be used for customizing how link looks like: # :src-link:`master's directory <master>` 'src-link': ('https://github.com/buildbot/buildbot/blob/master/%s', None), # "pretty" reference that looks like relative path in Buildbot source tree # by default. 'src': ('https://github.com/buildbot/buildbot/blob/master/%s', ''), 'contrib-src': ('https://github.com/buildbot/buildbot-contrib/blob/master/%s', ''), } # Sphinx' link checker. linkcheck_ignore = [ # Local URLs: r'^http://localhost.*', # Available only to logged-in users: r'^https://github\.com/settings/applications$', # Sites which uses SSL that Python 2 can't handle: r'^https://opensource\.org/licenses/gpl-2.0\.php$', r'^https://docs\.docker\.com/engine/installation/$', # Looks like server doesn't like user agent: r'^https://www\.microsoft\.com/en-us/download/details\.aspx\?id=17657$', # Example domain. r'^https?://(.+\.)?example\.org', # Anchor check fails on rendered user files on GitHub, since GitHub uses # custom prefix for anchors in user generated content. r'https://github\.com/buildbot/guanlecoja-ui/tree/master#changelog', r'http://mesosphere.github.io/marathon/docs/rest-api.html#post-v2-apps', ] linkcheck_timeout = 10 linkcheck_retries = 3 linkcheck_workers = 20 # -- Options for HTML output --------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'qtile' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {'stickysidebar': 'true'} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [ '_themes' ] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = os.path.join('_images', 'header-text-transparent.png') # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = os.path.join('_static', 'buildbot.ico') # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = False # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': ['searchbox.html', 'localtoc.html', 'relations.html', 'sourcelink.html'] } # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True html_use_index = True html_use_modindex = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Buildbotdoc' # -- Options for LaTeX output -------------------------------------------- latex_elements = {} # The paper size ('letter' or 'a4'). latex_elements['papersize'] = 'a4' # The font size ('10pt', '11pt' or '12pt'). # latex_font_size = '11pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Buildbot.tex', u'Buildbot Documentation', u'Brian Warner', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. latex_logo = os.path.join('_images', 'header-text-transparent.png') # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # Three possible values for this option (see sphinx config manual) are: # 1. 'no' - do not display URLs (default) # 2. 'footnote' - display URLs in footnotes # 3. 'inline' - display URLs inline in parentheses latex_show_urls = 'inline' # Additional stuff for the LaTeX preamble. # latex_preamble = '' # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'buildbot', u'Buildbot Documentation', [u'Brian Warner'], 1) ] jinja_contexts = { "data_api": {'raml': RamlSpec()} } # Spell checker. try: import enchant # noqa # pylint: disable=unused-import except ImportError as ex: print("enchant module import failed:\n" "{0}\n" "Spell checking disabled.".format(ex), file=sys.stderr) else: extensions.append('sphinxcontrib.spelling') spelling_show_suggestions = True
shoelzer/buildbot
master/docs/conf.py
Python
gpl-2.0
11,555
[ "Brian" ]
4d51b3fc7aacd2fa1e9b478edc36a16034b6e1a86b408788b3624e65c754d3b3
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, Anima Istanbul # # This module is part of anima-tools and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause import functools import os import re import tempfile from anima.ui.progress_dialog import ProgressDialogManager from anima.env.mayaEnv.camera_tools import cam_to_chan from anima.utils import do_db_setup import pymel.core as pm import maya.mel as mel import maya.cmds as cmds from anima.env.mayaEnv import auxiliary, camera_tools __last_commands__ = [] # list of dictionaries __last_tab__ = 'ANIMA_TOOLBOX_LAST_TAB_INDEX' def repeater(index): """repeats the last command with the given index """ global __last_commands__ try: call_data = __last_commands__[index] return call_data[0](*call_data[1], **call_data[2]) except IndexError: return None def repeat_last(call_data): """own implementation of pm.repeatLast """ global __last_commands__ index = len(__last_commands__) callable_ = call_data[0] args = call_data[1] kwargs = call_data[2] command = \ 'print \\"\\";python(\\\"from anima.env.mayaEnv.toolbox import ' \ 'repeater; repeater(%s);\\\");' % index repeat_last_command = 'repeatLast -ac "%(command)s" -acl "%(label)s";' % { 'command': command, 'label': callable_.__name__ } print(repeat_last_command) pm.mel.eval(repeat_last_command) __last_commands__.append(call_data) # also call the callable callable_(*args, **kwargs) def RepeatedCallback(callable_, *args, **kwargs): """Adds the given callable to the last commands list and adds a caller to the pm.repeatLast """ return pm.Callback( repeat_last, [callable_, args, kwargs] ) class Color(object): """a simple color class """ colors = [ (1.000, 0.500, 0.666), (1.000, 0.833, 0.500), (0.666, 1.000, 0.500), (0.500, 1.000, 0.833), (0.500, 0.666, 1.000), (0.833, 0.500, 1.000) ] def __init__(self, index=0): self.index = index self.max_colors = len(self.colors) def change(self): """updates the index to the next one """ self.index = int((self.index + 1) % self.max_colors) def reset(self): """resets the color index """ self.index = 0 @property def color(self): """returns the current color values """ return self.colors[self.index] def UI(): #window setup width = 260 height = 650 row_spacing = 3 color = Color() if pm.dockControl("toolbox_dockControl", q=True, ex=True): pm.deleteUI("toolbox_dockControl") if pm.window("toolbox_window", q=True, ex=True): pm.deleteUI("toolbox_window", wnd=True) toolbox_window = pm.window( 'toolbox_window', wh=(width, height), title="Anima ToolBox" ) #the layout that holds the tabs main_formLayout = pm.formLayout( 'main_formLayout', nd=100, parent=toolbox_window ) main_tabLayout = pm.tabLayout( 'main_tabLayout', scr=True, cr=True, parent=main_formLayout ) #attach the main_tabLayout to main_formLayout pm.formLayout( main_formLayout, edit=True, attachForm=[ (main_tabLayout, "top", 0), (main_tabLayout, "bottom", 0), (main_tabLayout, "left", 0), (main_tabLayout, "right", 0) ] ) with main_tabLayout: # ----- GENERAL ------ general_columnLayout = pm.columnLayout( 'general_columnLayout', adj=True, cal="center", rs=row_spacing ) with general_columnLayout: color.change() pm.button( 'selectionManager_button', l="Selection Manager", c=RepeatedCallback(General.selection_manager), ann="Selection Manager", bgc=color.color ) color.change() pm.button( 'removeColonFromNames_button', l="remove colon(:) from node names", c=RepeatedCallback(General.remove_colon_from_names), ann="removes the colon (:) character from all " "selected object names", bgc=color.color ) pm.button( 'removePastedFromNames_button', l="remove \"pasted_\" from node names", c=RepeatedCallback(General.remove_pasted), ann="removes the \"passed__\" from all selected " "object names", bgc=color.color ) color.change() pm.button( 'togglePolyMeshes_button', l="toggle polymesh visibility", c=RepeatedCallback(General.toggle_poly_meshes), ann="toggles the polymesh display in the active model " "panel", bgc=color.color ) color.change() pm.button( 'selectSetMembers_button', l="select set members", c=RepeatedCallback(General.select_set_members), ann="selects the selected set members in correct " "order", bgc=color.color ) color.change() pm.button( 'delete_unused_intermediate_shapes_button', l='Delete Unused Intermediate Shape Nodes', c=RepeatedCallback(General.delete_unused_intermediate_shapes), ann='Deletes unused (no connection) intermediate shape nodes', bgc=color.color ) color.change() pm.button( 'export_transform_info_button', l='Export Transform Info', c=RepeatedCallback(General.export_transform_info), ann='exports transform info', bgc=color.color ) pm.button( 'import_transform_info_button', l='Import Transform Info', c=RepeatedCallback(General.import_transform_info), ann='imports transform info', bgc=color.color ) color.change() pm.button( 'export_component_transform_info_button', l='Export Component Transform Info', c=RepeatedCallback(General.export_component_transform_info), ann='exports component transform info', bgc=color.color ) pm.button( 'import_component_transform_info_button', l='Import Component Transform Info', c=RepeatedCallback(General.import_component_transform_info), ann='imports component transform info', bgc=color.color ) color.change() pm.button( 'generate_thumbnail_button', l='Generate Thumbnail', c=RepeatedCallback(General.generate_thumbnail), ann='Generates thumbnail for current scene', bgc=color.color ) color.change() pm.button( 'cleanup_light_cameras_button', l='Cleanup Light Cameras', c=RepeatedCallback(General.cleanup_light_cameras), ann=General.cleanup_light_cameras.__doc__, bgc=color.color ) # ----- REFERENCE ------ reference_columnLayout = pm.columnLayout( 'reference_columnLayout', adj=True, cal="center", rs=row_spacing) with reference_columnLayout: color.reset() pm.text(l='===== Reference Tools =====') pm.button( 'duplicate_selected_reference_button', l='Duplicate Selected Reference', c=RepeatedCallback(Reference.duplicate_selected_reference), ann='Duplicates the selected reference', bgc=color.color ) color.change() pm.button( 'get_selected_reference_path_button', l='Get Selected Reference Path', c=RepeatedCallback(Reference.get_selected_reference_path), ann='Prints the selected reference full path', bgc=color.color ) pm.button( 'open_selected_reference_button', l='Open Selected Reference in New Maya', c=RepeatedCallback(Reference.open_reference_in_new_maya), ann='Opens the selected reference in new Maya ' 'instance', bgc=color.color ) color.change() pm.button( 'publish_model_as_look_dev_button', l='Model -> LookDev', c=RepeatedCallback(Reference.publish_model_as_look_dev), ann='References the current Model scene to the LookDev scene ' 'of the same task, creates the LookDev scene if ' 'necessary, also reopens the current model scene.', bgc=color.color ) color.change() pm.button( 'fix_reference_namespace_button', l='Fix Reference Namespace', c=RepeatedCallback(Reference.fix_reference_namespace), ann='Fixes old style reference namespaces with new one, ' 'creates new versions if necessary.', bgc=color.color ) color.change() pm.button( 'fix_reference_paths_button', l='Fix Reference Paths', c=RepeatedCallback(Reference.fix_reference_paths), ann='Fixes reference paths deeply, so they will use' '$REPO env var.', bgc=color.color ) pm.button( 'archive_button', l='Archive Current Scene', c=RepeatedCallback(Reference.archive_current_scene), ann='Creates a ZIP file containing the current scene and its' 'references in a flat Maya default project folder ' 'structure', bgc=color.color ) pm.button( 'bind_to_original_button', l='Bind To Original', c=RepeatedCallback(Reference.bind_to_original), ann='Binds the current local references to the ones on the ' 'repository', bgc=color.color ) pm.button( 'unload_unselected_references_button', l='Unload UnSelected References', c=RepeatedCallback(Reference.unload_unselected_references), ann='Unloads any references that is not related with the ' 'selected objects', bgc=color.color ) color.change() pm.text(l='===== Representation Tools =====') with pm.rowLayout(nc=2, adj=1): pm.checkBoxGrp( 'generate_repr_types_checkbox_grp', label='Reprs', numberOfCheckBoxes=3, labelArray3=['GPU', 'ASS', 'RS'], cl4=['left', 'left', 'left', 'left'], cw4=[51, 50, 50, 50], valueArray3=[1, 1, 1] ) pm.checkBox( 'generate_repr_skip_existing_checkBox', label='Skip existing Reprs.', value=0 ) pm.button( 'generate_repr_of_all_references_button', l='Deep Generate Repr Of All References', c=RepeatedCallback( Reference.generate_repr_of_all_references_caller ), ann='Deeply generates desired Representations of all ' 'references of this scene', bgc=color.color ) pm.button( 'generate_repr_of_scene_button', l='Generate Repr Of This Scene', c=RepeatedCallback(Reference.generate_repr_of_scene_caller), ann='Generates desired Representations of this scene', bgc=color.color ) color.change() with pm.rowLayout(nc=2, adj=1): pm.radioButtonGrp( 'repr_apply_to_radio_button_grp', label='Apply To', # ad3=1, labelArray2=['Selected', 'All References'], numberOfRadioButtons=2, cl3=['left', 'left', 'left'], cw3=[50, 65, 65], sl=1 ) pm.button( 'to_base_button', l='To Base', c=RepeatedCallback(Reference.to_base), ann='Convert selected to Base representation', bgc=color.color ) pm.button( 'to_gpu_button', l='To GPU', c=RepeatedCallback(Reference.to_gpu), ann='Convert selected to GPU representation', bgc=color.color ) pm.button( 'to_ass_button', l='To ASS', c=RepeatedCallback(Reference.to_ass), ann='Convert selected to ASS representation', bgc=color.color ) # ----- MODELING ------ modeling_columnLayout = pm.columnLayout( 'modeling_columnLayout', adj=True, cal="center", rs=row_spacing) with modeling_columnLayout: color.reset() pm.button('toggleFaceNormalDisplay_button', l="toggle face normal display", c=RepeatedCallback( pm.runtime.ToggleFaceNormalDisplay), ann="toggles face normal display", bgc=color.color) pm.button('reverseNormals_button', l="reverse normals", c=RepeatedCallback(Modeling.reverse_normals), ann="reverse normals", bgc=color.color) pm.button('fixNormals_button', l="fix normals", c=RepeatedCallback(Modeling.fix_normals), ann="applies setToFace then conform and then " "soften edge to all selected objects", bgc=color.color) color.change() pm.button( 'oyHierarchyInstancer_button', l="hierarchy_instancer on selected", c=RepeatedCallback(Modeling.hierarchy_instancer), ann="hierarchy_instancer on selected", bgc=color.color ) color.change() pm.button( 'oyRelaxVerts_button', l="relax_vertices", c=RepeatedCallback(Modeling.relax_vertices), ann="opens relax_vertices", bgc=color.color ) color.change() pm.button( 'create_curve_from_mesh_edges_button', l="Curve From Mesh Edges", c=RepeatedCallback(Modeling.create_curve_from_mesh_edges), ann="Creates a curve from selected mesh edges", bgc=color.color ) color.change() pm.button( 'vertex_aligned_locator_button', l="Vertex Aligned Locator", c=RepeatedCallback(Modeling.vertex_aligned_locator), ann="Creates an aligned locator from selected vertices", bgc=color.color ) color.change() pm.button( 'select_zero_uv_area_faces_button', l="Filter Zero UV Area Faces", c=RepeatedCallback(Modeling.select_zero_uv_area_faces), ann="Selects faces with zero uv area", bgc=color.color ) color.change() with pm.rowLayout(nc=8, rat=(1, "both", 0), adj=1): pm.text('set_pivot_text', l='Set Pivot', bgc=color.color) pm.button( 'center_button', l="C", c=RepeatedCallback( Modeling.set_pivot, 0 ), bgc=(0.8, 0.8, 0.8) ) pm.button( 'minus_X_button', l="-X", c=RepeatedCallback( Modeling.set_pivot, 1 ), bgc=(1.000, 0.500, 0.666) ) pm.button( 'plus_X_button', l="+X", c=RepeatedCallback( Modeling.set_pivot, 2 ), bgc=(1.000, 0.500, 0.666) ) pm.button( 'minus_Y_button', l="-Y", c=RepeatedCallback( Modeling.set_pivot, 3 ), bgc=(0.666, 1.000, 0.500) ) pm.button( 'plus_Y_button', l="+Y", c=RepeatedCallback( Modeling.set_pivot, 4 ), bgc=(0.666, 1.000, 0.500) ) pm.button( 'minus_Z_button', l="-X", c=RepeatedCallback( Modeling.set_pivot, 5 ), bgc=(0.500, 0.666, 1.000) ) pm.button( 'plus_Z_button', l="+X", c=RepeatedCallback( Modeling.set_pivot, 6 ), bgc=(0.500, 0.666, 1.000) ) color.change() with pm.rowLayout(nc=7, rat=(1, "both", 0), adj=1): pm.text(l='Text. Res', bgc=color.color) pm.button( l="128", c=RepeatedCallback( Modeling.set_texture_res, 128 ), bgc=Color.colors[0] ) pm.button( l="256", c=RepeatedCallback( Modeling.set_texture_res, 256 ), bgc=Color.colors[1] ) pm.button( l="512", c=RepeatedCallback( Modeling.set_texture_res, 512 ), bgc=Color.colors[2] ) pm.button( l="1024", c=RepeatedCallback( Modeling.set_texture_res, 1024 ), bgc=Color.colors[3] ) pm.button( l='2048', c=RepeatedCallback( Modeling.set_texture_res, 2048 ), bgc=Color.colors[4] ) pm.button( l='4096', c=RepeatedCallback( Modeling.set_texture_res, 4096 ), bgc=Color.colors[5] ) # ----- RIGGING ------ rigging_columnLayout = pm.columnLayout( 'rigging_columnLayout', adj=True, cal="center", rs=row_spacing ) with rigging_columnLayout: color.reset() pm.button( 'oyCreateJointOnCurve_button', l="oyCreateJointOnCurve", c=RepeatedCallback(mel.eval, 'oyCreateJointOnCurve'), ann="opens oyCreateJointOnCurve", bgc=color.color ) pm.button( 'oyIKFKSetup_button', l="oyIKFKSetup", c=RepeatedCallback(mel.eval, 'oyIKFKSetup'), ann="opens oyIKFKSetup", bgc=color.color ) pm.button( 'oySpineSetupSetup_button', l="oySpineSetupSetup", c=RepeatedCallback(mel.eval, 'oyStretchySpineSetup'), ann="opens oySpineSetupSetup", bgc=color.color ) pm.button( 'setupStretchySplineIKCurve_button', l="setup stretchy splineIK curve", c=RepeatedCallback(Rigging.setup_stretchy_spline_IKCurve), ann="connects necessary nodes to calculate arcLength " "change in percent", bgc=color.color ) pm.button( 'selectJointsDeformingTheObject_button', l="select joints deforming the object", c=RepeatedCallback(Rigging.select_joints_deforming_object), ann="select joints that deform the object", bgc=color.color ) color.change() pm.button( 'oyCreateAxialCorrectionGroup_button', l="create axialCorrectionGroups", c=RepeatedCallback(Rigging.axial_correction_group), ann="creates a group node above the selected objects " "to zero-out the transformations", bgc=color.color ) pm.button( 'createAxialCorrectionGroupForClusters_button', l="create axialCorrectionGroup for clusters", c=RepeatedCallback( Rigging.create_axial_correction_group_for_clusters ), ann="create Axial Correction Group For Clusters", bgc=color.color ) color.change() pm.button( 'setClustersToAbsolute_button', l="set selected clusters to absolute", c=RepeatedCallback(Rigging.set_clusters_relative_state, 0), ann="set Clusters to Absolute", bgc=color.color ) pm.button( 'setClustersToRelative_button', l="set selected clusters to relative", c=RepeatedCallback( Rigging.set_clusters_relative_state, 1 ), ann="set Clusters to Relative", bgc=color.color ) color.change() pm.button( 'addControllerShape_button', l="add controller shape", c=RepeatedCallback(Rigging.add_controller_shape), ann="add the shape in the selected joint", bgc=color.color ) pm.button( 'replaceControllerShape_button', l="replace controller shape", c=RepeatedCallback(Rigging.replace_controller_shape), ann="replaces the shape in the selected joint", bgc=color.color ) color.change() pm.button('rivet_button', l="create rivet", c=RepeatedCallback(mel.eval, 'rivet'), ann="create rivet", bgc=color.color) pm.button('oyAutoRivet_button', l="auto rivet", c=RepeatedCallback(mel.eval, 'oyAutoRivet'), ann="auto rivet", bgc=color.color) pm.button( 'oyAutoRivetFollicle_button', l="auto rivet (Follicle)", c=RepeatedCallback(auxiliary.auto_rivet), ann="creates a rivet setup by using hair follicles", bgc=color.color ) pm.button('create_hair_from_curves_button', l="Create Hair From Curves", c=RepeatedCallback(auxiliary.hair_from_curves), ann="creates hair from curves", bgc=color.color) color.change() pm.button('artPaintSkinWeightsTool_button', l="paint weights tool", c=RepeatedCallback(mel.eval, 'ArtPaintSkinWeightsTool'), ann="paint weights tool", bgc=color.color) pm.button('oySkinTools_button', l="oySkinTools", c=RepeatedCallback(mel.eval, 'oySkinTools'), ann="skin tools", bgc=color.color) pm.button('oyFixBoundJoint_button', l="fix_bound_joint", c=RepeatedCallback(Rigging.fix_bound_joint), ann="fix_bound_joint", bgc=color.color) pm.button('toggleLocalRotationAxes_button', l="toggle local rotation axes", c=RepeatedCallback(General.toggle_attributes, "displayLocalAxis"), ann="toggle local rotation axes", bgc=color.color) pm.button('seroBlendController_button', l="seroBlendController", c=RepeatedCallback(mel.eval, 'seroBlendController'), ann="seroBlendController", bgc=color.color) pm.button('align_to_pole_vector_button', l="Align To Pole Vector", c=RepeatedCallback(auxiliary.align_to_pole_vector), ann="align to pole vector", bgc=color.color) color.change() pm.button('oyResetCharSet_button', l="oyResetCharSet", c=RepeatedCallback(mel.eval, 'oyResetCharSet'), ann="reset char set", bgc=color.color) pm.button('export_blend_connections_button', l="Export blend connections", c=RepeatedCallback(auxiliary.export_blend_connections), ann="export blend connections", bgc=color.color) color.change() pm.button('createFollicles_button', l="create follicles", c=RepeatedCallback(Rigging.create_follicles), ann="create follicles", bgc=color.color) color.change() pm.button('oyResetTweaks_button', l="reset tweaks", c=RepeatedCallback(Rigging.reset_tweaks), ann="reset tweaks", bgc=color.color) # ----- RENDER ------ render_columnLayout = pm.columnLayout( 'render_columnLayout', adj=True, cal="center", rs=row_spacing ) with render_columnLayout: color.reset() pm.button( 'open_node_in_browser_button', l="Open node in browser", c=RepeatedCallback(Render.open_node_in_browser), ann="Open node in browser", bgc=color.color ) color.change() pm.button('auto_convert_to_redshift_button', l="Auto Convert Scene To RedShift (BETA)", c=RepeatedCallback(Render.auto_convert_to_redshift), ann="Automatically converts the scene from Arnold to " "Redshift, including materials and lights", bgc=color.color) pm.button('convert_nodes_to_redshift_button', l="Convert Selected To RedShift (BETA)", c=RepeatedCallback(Render.convert_nodes_to_redshift), ann="Automatically converts the selected node from " "Arnold to Redshift", bgc=color.color) color.change() pm.button( 'fix_render_layer_out_adjustment_errors_button', l="fixRenderLayerOutAdjustmentErrors", c='pm.mel.eval("fixRenderLayerOutAdjustmentErrors();")', ann="fixRenderLayerOutAdjustmentErrors", bgc=color.color ) pm.separator() color.change() with pm.rowLayout(nc=2, adj=2): apply_to_hierarchy_checkBox = pm.checkBox( 'apply_to_hierarchy_checkBox', l="Apply to Hierarchy", value=True, bgc=color.color ) disable_undo_queue_check_box = pm.checkBox( 'disable_undo_queue_checkBox', l="Disable Undo", value=False, bgc=color.color ) def set_shape_attribute_wrapper(attr_name, value): """a wrapper function for set_shape_attribute """ apply_to_hierarchy = pm.checkBox( apply_to_hierarchy_checkBox, q=True, v=True ) disable_undo = pm.checkBox( disable_undo_queue_check_box, q=True, v=True ) Render.set_shape_attribute( attr_name, value, apply_to_hierarchy, disable_undo ) attr_names = [ 'castsShadows', 'receiveShadows', 'motionBlur', 'primaryVisibility', 'visibleInReflections', 'visibleInRefractions', 'aiSelfShadows', 'aiOpaque', 'aiVisibleInDiffuse', 'aiVisibleInGlossy', 'aiMatte', 'overrideShaders' ] for attr_name in attr_names: with pm.rowLayout(nc=4, rat=(1, "both", 0), adj=1): pm.text('%s_text' % attr_name, l=attr_name, bgc=color.color) pm.button( 'set_%s_ON_button' % attr_name, l="ON", c=RepeatedCallback( set_shape_attribute_wrapper, attr_name, 1, ), bgc=(0, 1, 0) ) pm.button( 'set_%s_OFF_button' % attr_name, l="OFF", c=RepeatedCallback( set_shape_attribute_wrapper, attr_name, 0 ), bgc=(1, 0, 0) ) pm.button( 'set_%s_REMOVE_button' % attr_name, l="REM", ann='Remove Override', c=RepeatedCallback( set_shape_attribute_wrapper, attr_name, -1 ), bgc=(0, 0.5, 1) ) pm.separator() color.change() with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('renderThumbnailUpdate_text', l="renderThumbnailUpdate", bgc=color.color) pm.button('set_renderThumbnailUpdate_ON_button', l="ON", c=RepeatedCallback(pm.renderThumbnailUpdate, 1), bgc=(0, 1, 0)) pm.button('set_renderThumbnailUpdate_OFF_button', l="OFF", c=RepeatedCallback(pm.renderThumbnailUpdate, 0), bgc=(1, 0, 0)) color.change() pm.button('replaceShadersWithLast_button', l="replace shaders with last", c=RepeatedCallback(Render.replace_shaders_with_last), ann="replace shaders with last", bgc=color.color) color.change() pm.button('createTextureRefObject_button', l="create texture ref. object", c=RepeatedCallback(Render.create_texture_ref_object), ann="create texture ref. object", bgc=color.color) color.change() pm.button( 'CameraFilmOffsetTool_button', l="Camera Film Offset Tool", c=RepeatedCallback( camera_tools.camera_film_offset_tool ), ann="Camera Film Offset Tool", bgc=color.color ) pm.button( 'CameraFocusPlaneTool_button', l="Camera Focus Plane Tool", c=RepeatedCallback( camera_tools.camera_focus_plane_tool ), ann="Camera Film Offset Tool", bgc=color.color ) pm.button('oyTracker2Null_button', l="oyTracker2Null", c=RepeatedCallback(mel.eval, 'oyTracker2Null'), ann="Tracker2Null", bgc=color.color) color.change() pm.button('reloadFileTextures_button', l="reload file textures", c=RepeatedCallback(Render.reload_file_textures), ann="reload file textures", bgc=color.color) color.change() pm.button('transfer_shaders_button', l="Transfer Shaders", c=RepeatedCallback(Render.transfer_shaders), ann="Transfers shaders from one group to other, use it" "for LookDev -> Alembic", bgc=color.color) pm.button('transfer_uvs_button', l="Transfer UVs", c=RepeatedCallback(Render.transfer_uvs), ann="Transfers UVs from one group to other, use it" "for LookDev -> Alembic", bgc=color.color) color.change() pm.button('fitPlacementToUV_button', l="fit placement to UV", c=RepeatedCallback(Render.fit_placement_to_UV), ann="fit placement to UV", bgc=color.color) color.change() enable_matte_row_layout = pm.rowLayout(nc=6, adj=1) with enable_matte_row_layout: pm.text( l='Enable Arnold Matte', ) pm.button( l='Default', c=RepeatedCallback(Render.enable_matte, 0), ann='Enables Arnold Matte on selected objects with <b>No Color</b>', bgc=color.color ) pm.button( l='R', c=RepeatedCallback(Render.enable_matte, 1), ann='Enables Arnold Matte on selected objects with <b>Red</b>', bgc=[1, 0, 0] ) pm.button( l='G', c=RepeatedCallback(Render.enable_matte, 2), ann='Enables Arnold Matte on selected objects with <b>Green</b>', bgc=[0, 1, 0] ) pm.button( l='B', c=RepeatedCallback(Render.enable_matte, 3), ann='Enables Arnold Matte on selected objects with <b>Blue</b>', bgc=[0, 0, 1] ) pm.button( l='A', c=RepeatedCallback(Render.enable_matte, 4), ann='Enables Arnold Matte on selected objects with <b>Alpha</b>', bgc=[0.5, 0.5, 0.5] ) pm.button( l='Setup Z-Layer', c=RepeatedCallback(Render.create_z_layer), ann=Render.create_z_layer.__doc__, bgc=color.color ) pm.button( l='Setup EA Matte', c=RepeatedCallback(Render.create_ea_matte), ann=Render.create_ea_matte.__doc__, bgc=color.color ) color.change() pm.button( 'enable_subdiv_on_selected_objects_button', l='Enable Arnold Subdiv', c=RepeatedCallback(Render.enable_subdiv), ann='Enables Arnold Subdiv (catclark 2) on selected objects', bgc=color.color ) color.change() pm.text(l='===== BarnDoor Simulator =====') pm.button( 'barn_door_simulator_setup_button', l='Setup', c=RepeatedCallback(Render.barndoor_simulator_setup), ann='Creates a arnold barn door simulator to the selected ' 'light', bgc=color.color ) pm.button( 'barn_door_simulator_unsetup_button', l='Un-Setup', c=RepeatedCallback(Render.barndoor_simulator_unsetup), ann='Removes the barn door simulator nodes from the selected ' 'light', bgc=color.color ) pm.button( 'fix_barndoors_button', l='Fix BarnDoors', c=RepeatedCallback(Render.fix_barndoors), ann=Render.fix_barndoors.__doc__, bgc=color.color ) color.change() pm.button( 'ai_skin_sss_to_ai_skin_button', l='aiSkinSSS --> aiSkin', c=RepeatedCallback(Render.convert_aiSkinSSS_to_aiSkin), ann=Render.convert_aiSkinSSS_to_aiSkin.__doc__, bgc=color.color ) pm.button( 'normalize_sss_weights_button', l='Normalize SSS Weights', c=RepeatedCallback(Render.normalize_sss_weights), ann=Render.normalize_sss_weights.__doc__, bgc=color.color ) color.change() pm.button( 'create_eye_shader_and_controls_button', l='Create Eye Shader and Controls', c=RepeatedCallback(Render.create_eye_shader_and_controls), ann='Creates eye shaders and controls for the selected eyes', bgc=color.color ) pm.button( 'setup_outer_eye_render_attributes_button', l='Setup Outer Eye Render Attributes', c=RepeatedCallback(Render.setup_outer_eye_render_attributes), ann=Render.setup_outer_eye_render_attributes.__doc__, bgc=color.color ) pm.button( 'setup_window_glass_render_attributes_button', l='Setup **Window Glass** Render Attributes', c=RepeatedCallback(Render.setup_window_glass_render_attributes), ann=Render.setup_window_glass_render_attributes.__doc__, bgc=color.color ) pm.button( 'setup_dummy_window_light_button', l='Setup/Update **Dummy Window** Light Plane', c=RepeatedCallback(Render.dummy_window_light_plane), ann=Render.dummy_window_light_plane.__doc__, bgc=color.color ) color.change() pm.button( 'create_generic_tooth_shader_button', l='Create Generic TOOTH Shader', c=RepeatedCallback(Render.create_generic_tooth_shader), ann=Render.create_generic_gum_shader.__doc__, bgc=color.color ) pm.button( 'create_generic_gum_shader_button', l='Create Generic GUM Shader', c=RepeatedCallback(Render.create_generic_gum_shader), ann=Render.create_generic_gum_shader.__doc__, bgc=color.color ) pm.button( 'create_generic_tongue_shader_button', l='Create Generic TONGUE Shader', c=RepeatedCallback(Render.create_generic_tongue_shader), ann=Render.create_generic_tongue_shader.__doc__, bgc=color.color ) color.change() pm.button('convert_to_ai_image_button', l="To aiImage", c=RepeatedCallback(Render.convert_file_node_to_ai_image_node), ann="Converts the selected File (file texture) nodes to " "aiImage nodes, also connects the place2dTexture " "node if necessary", bgc=color.color) color.change() pm.button('to_bbox_button', l="aiStandIn To BBox", c=RepeatedCallback(Render.standin_to_bbox), ann="Convert selected stand ins to bbox", bgc=color.color) pm.button('to_polywire_button', l="aiStandIn To Polywire", c=RepeatedCallback(Render.standin_to_polywire), ann="Convert selected stand ins to polywire", bgc=color.color) color.change() with pm.rowLayout(nc=3, adj=3, bgc=color.color): min_range_field = pm.floatField( minValue=1000, maxValue=50000, step=1, pre=0, value=3500, w=50, bgc=color.color, ann='Min Value' ) max_range_field = pm.floatField( minValue=1000, maxValue=50000, step=1, pre=0, value=6500, w=50, bgc=color.color, ann='Max Value' ) pm.button( ann="Randomize Color Temperature", l="Randomize Color Temp.", w=70, c=RepeatedCallback( Render.randomize_light_color_temp, min_range_field, max_range_field ), bgc=color.color ) with pm.rowLayout(nc=3, adj=3, bgc=color.color): min_range_field = pm.floatField( minValue=0, maxValue=200, step=0.1, pre=1, value=10, w=50, bgc=color.color, ann='Min Value' ) max_range_field = pm.floatField( minValue=0, maxValue=200, step=0.1, pre=1, value=20, w=50, bgc=color.color, ann='Max Value' ) pm.button( ann="Randomize Exposure", l="Randomize Exposure", w=70, c=RepeatedCallback( Render.randomize_light_intensity, min_range_field, max_range_field ), bgc=color.color ) color.change() pm.button( ann="Create Reflection Curve", l="Reflection Curve", c=RepeatedCallback( Render.generate_reflection_curve ), bgc=color.color ) color.change() pm.button( ann="Import GPU Content", l="Import GPU Content", c=RepeatedCallback( Render.import_gpu_content ), bgc=color.color ) color.change() with pm.rowLayout(nc=3, adj=3, bgc=color.color): source_driver_field = pm.textField( text='S:', w=50, bgc=color.color, ann='Source Driver' ) target_driver_field = pm.textField( text='L:', w=50, bgc=color.color, ann='Target Driver' ) pm.button( ann="Move Cache Files to Another Location", l="Move Cache Files", w=70, c=RepeatedCallback( Render.move_cache_files_wrapper, source_driver_field, target_driver_field ), bgc=color.color ) # ----- ANIMATION ------ animation_columnLayout = pm.columnLayout( 'animation_columnLayout', adj=True, cal="center", rs=row_spacing ) with animation_columnLayout: color.reset() color.change() from anima.env.mayaEnv import picker pm.text(l='===== Object Picker =====') pm.button('picker_setParent_button', l="Set Parent", c=RepeatedCallback(picker.set_parent), ann="Set Parent", bgc=color.color) pm.button('picker_releaseObject_button', l="Release", c=RepeatedCallback(picker.release_object), ann="Release Object", bgc=color.color) pm.button('picker_editKeyframes_button', l="Edit Keyframes", c=RepeatedCallback(picker.edit_keyframes), ann="Edit Keyframes", bgc=color.color) pm.button('picker_fixJump_button', l="Fix Jump", c=RepeatedCallback(picker.fix_jump), ann="Fix Jump", bgc=color.color) pm.button('picker_explodeSetup_button', l="Explode", c=RepeatedCallback(picker.explode_setup), ann="Explode Setup", bgc=color.color) color.change() from anima.env.mayaEnv import pivot_switcher pm.text(l='===== Pivot Switcher =====') pm.button('oyPivotSwitcher_setupPivot_button', l="Setup", c=RepeatedCallback(pivot_switcher.setup_pivot), ann="Setup Pivot", bgc=color.color) pm.button('oyPivotSwitcher_switchPivot_button', l="Switch", c=RepeatedCallback(pivot_switcher.switch_pivot), ann="Switch Pivot", bgc=color.color) pm.button('oyPivotSwitcher_togglePivot_button', l="Toggle", c=RepeatedCallback(pivot_switcher.toggle_pivot), ann="Toggle Pivot", bgc=color.color) color.change() pm.text(l='===== Vertigo =====') pm.button('oyVertigo_setupLookAt_button', l="Setup -> Look At", c=RepeatedCallback(Animation.vertigo_setup_look_at), ann="Setup Look At", bgc=color.color) pm.button('oyVertigo_setupVertigo_button', l="Setup -> Vertigo", c=RepeatedCallback(Animation.vertigo_setup_vertigo), ann="Setup Vertigo", bgc=color.color) pm.button('oyVertigo_delete_button', l="Delete", c=RepeatedCallback(Animation.vertigo_delete), ann="Delete", bgc=color.color) color.change() pm.text(l='===== Alembic Tools =====') rowLayout = pm.rowLayout(nc=2, adj=1, bgc=color.color) with rowLayout: pm.button( 'abc_from_selected_button', l='From Selected', c=RepeatedCallback(Animation.create_alembic_command), ann='Creates Alembic Cache from selected nodes', bgc=color.color ) from_top_node_checkBox = pm.checkBox( 'from_top_node_checkBox', l="Top Node", value=True, bgc=color.color ) # pm.button( # 'abc_from_source_to_target_button', # l='Source -> Target', # c=RepeatedCallback(Animation.copy_alembic_data), # ann='Copy Alembic Data from Source to Target by the matching ' # 'node names', # bgc=color.color # ) pm.text(l='===== Exporters =====') color.change() rowLayout = pm.rowLayout(nc=3, adj=3, bgc=color.color) with rowLayout: start = int(pm.playbackOptions(q=1, minTime=1)) end = int(pm.playbackOptions(q=1, maxTime=1)) startButtonField = pm.textField( text=start, w=50, bgc=color.color, ann='start frame' ) endButtonField = pm.textField( text=end, w=50, bgc=color.color, ann='end frame' ) pm.button(ann="Exports maya camera to nuke", l="cam2chan", w=70, c=RepeatedCallback( Animation.cam_2_chan, startButtonField, endButtonField ), bgc=color.color) pm.text(l='===== Component Animation =====') color.change() smooth_component_anim = pm.textFieldButtonGrp( 'oySmoothComponentAnimation_button', bl="Smooth Component Animation", adj=2, tx=1, cw=(1, 40), ann="select components to smooth", bgc=color.color ) pm.textFieldButtonGrp( smooth_component_anim, e=1, bc=RepeatedCallback( Animation.oySmoothComponentAnimation, smooth_component_anim ) ) color.change() pm.button( 'bake_component_animation_button', l='Bake component animation to Locator', c=RepeatedCallback(Animation.bake_component_animation), ann='Creates a locator at the center of selected components ' 'and moves it with the components along the current ' 'frame range', bgc=color.color ) pm.button( 'create_follicle_button', l='Attach Follicle', c=RepeatedCallback(Animation.attach_follicle), ann='Attaches a follicle in the selected components', bgc=color.color ) color.change() pm.button( 'set_range_from_shot_node_button', l='Range From Shot', c=RepeatedCallback(Animation.set_range_from_shot), ann='Sets the playback range from the shot node in the scene', bgc=color.color ) color.change() pm.button( 'delete_base_anim_layer_button', l='Delete Base Anim Layer', c=RepeatedCallback(Animation.delete_base_anim_layer), ann=Animation.delete_base_anim_layer.__doc__, bgc=color.color ) # Obsolete obsolete_columnLayout = pm.columnLayout( 'obsolete_columnLayout', adj=True, cal="center", ann="Obsolete", rs=row_spacing ) with obsolete_columnLayout: color.reset() pm.button('addMiLabel_button', l="add miLabel to selected", c=RepeatedCallback(Render.add_miLabel), ann="add miLabel to selected", bgc=color.color) color.change() pm.button('connectFacingRatioToVCoord_button', l="connect facingRatio to vCoord", c=RepeatedCallback( Render.connect_facingRatio_to_vCoord), ann="connect facingRatio to vCoord", bgc=color.color) color.change() with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherCast_text', l="miFinalGatherCast", bgc=color.color) pm.button('set_miFinalGatherCast_ON_button', l="ON", c=RepeatedCallback( set_shape_attribute_wrapper, "miFinalGatherCast", 1 ), bgc=(0, 1, 0)) pm.button('set_miFinalGatherCast_OFF_button', l="OFF", c=RepeatedCallback( set_shape_attribute_wrapper, "miFinalGatherCast", 0 ), bgc=(1, 0, 0)) with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherReceive_text', l="miFinalGatherReceive", bgc=color.color) pm.button('set_miFinalGatherReceive_ON_button', l="ON", c=RepeatedCallback( set_shape_attribute_wrapper, "miFinalGatherReceive", 1 ), bgc=(0, 1, 0)) pm.button('set_miFinalGatherReceive_OFF_button', l="OFF", c=RepeatedCallback( set_shape_attribute_wrapper, "miFinalGatherReceive", 0 ), bgc=(1, 0, 0)) with pm.rowLayout(nc=3, rat=(1, "both", 0), adj=1): pm.text('miFinalGatherHide_text', l="miFinalGatherHide", bgc=color.color) pm.button('set_miFinalGatherHide_ON_button', l="ON", c=RepeatedCallback(Render.set_finalGatherHide, 1), bgc=(0, 1, 0)) pm.button('set_miFinalGatherHide_OFF_button', l="OFF", c=RepeatedCallback(Render.set_finalGatherHide, 0), bgc=(1, 0, 0)) color.change() pm.button('convertToMRTexture_button', l="use mib_texture_filter_lookup", c=RepeatedCallback( Render.use_mib_texture_filter_lookup), ann=( "adds an mib_texture_filter_lookup node in \n" + "between the file nodes and their outputs, to \n" + "get a sharper look output from the texture file"), bgc=color.color) pm.button('convertToLinear_button', l="convert to Linear texture", c=RepeatedCallback(Render.convert_to_linear), ann="convert to Linear texture", bgc=color.color) pm.button('useImageSequence_button', l="use image sequence for \nmentalrayTexture", c=RepeatedCallback(Render.use_image_sequence), ann="use image sequence for \nmentalrayTexture", bgc=color.color) color.change() pm.button('oyAddToSelectedContainer_button', l="add to selected container", c=RepeatedCallback(Render.add_to_selected_container), ann="add to selected container", bgc=color.color) pm.button('oyRemoveFromContainer_button', l="remove from selected container", c=RepeatedCallback(Render.remove_from_container), ann="remove from selected container", bgc=color.color) color.change() pm.button('oySmedgeRenderSlicer_button', l="oySmedgeRenderSlicer", c=RepeatedCallback(mel.eval, 'oySmedgeRenderSlicer'), ann="SmedgeRenderSlicer", bgc=color.color) color.change() pm.button( 'exponentialSmooth_button', l="exponential smooth", c=RepeatedCallback(Modeling.polySmoothFace, 0), ann="applies exponential smooth to selected objects", bgc=color.color ) pm.button( 'linearSmooth_button', l="linear smooth", c=RepeatedCallback(Modeling.polySmoothFace, 1), ann="applies linear smooth to selected objects", bgc=color.color ) pm.button( 'deActivateSmooth_button', l="deActivate smooth", c=RepeatedCallback(Modeling.activate_deActivate_smooth, 1), ann="deActivates all polySmoothFace nodes in the " "scene", bgc=color.color ) pm.button( 'activateSmooth_button', l="activate smooth", c=RepeatedCallback(Modeling.activate_deActivate_smooth, 0), ann="activates all deActivated polySmoothFace nodes " "in the scene", bgc=color.color ) pm.button( 'deleteSmooth_button', l="delete smooth", c=RepeatedCallback(Modeling.delete_smooth), ann="deletes all the polySmoothFace nodes from the " "scene", bgc=color.color ) pm.button( 'deleteSmoothOnSelected_button', l="delete smooth on selected", c=RepeatedCallback(Modeling.delete_smooth_on_selected), ann="deletes selected polySmoothFace nodes from scene", bgc=color.color ) color.change() pm.button( 'deleteAllSound_button', l="delete all sound", c=RepeatedCallback(General.delete_all_sound), ann="delete all sound", bgc=color.color ) pm.button( 'displayHandlesOfSelectedObjects_button', l="toggle handles of selected objects", c=RepeatedCallback( General.toggle_attributes, "displayHandle" ), ann="select objects to toggle handle", bgc=color.color ) color.change() pm.button( 'referenceSelectedObjects_button', l="reference selected objects", c=RepeatedCallback( General.reference_selected_objects ), ann="sets objects display override to reference", bgc=color.color ) pm.button( 'dereferenceSelectedObjects_button', l="de-reference selected objects", c=RepeatedCallback( General.dereference_selected_objects ), ann="sets objects display override to reference", bgc=color.color ) color.change() pm.button( 'oyDeReferencer_button', l="dereferencer", c=RepeatedCallback(General.dereferencer), ann="sets all objects display override to normal", bgc=color.color ) pm.tabLayout( main_tabLayout, edit=True, tabLabel=[ (general_columnLayout, "Gen"), (reference_columnLayout, "Ref"), (modeling_columnLayout, "Mod"), (rigging_columnLayout, "Rig"), (render_columnLayout, "Ren"), (animation_columnLayout, "Ani"), (obsolete_columnLayout, "Obs") ], cc=functools.partial(store_tab_index, main_tabLayout) ) # pm.showWindow(toolbox_window) # pm.window(toolbox_window, edit=True, w=width) #print toolbox_window.name() dock_control = pm.dockControl( "toolbox_dockControl", l='toolbox', content=toolbox_window, area="left", allowedArea=["left", "right"], width=width ) # switch to last tab last_tab_index = get_last_tab_index() if last_tab_index: pm.tabLayout( main_tabLayout, e=1, sti=last_tab_index ) def store_tab_index(tab_layout): val = pm.tabLayout(tab_layout, q=1, sti=1) os.environ[__last_tab__] = str(val) def get_last_tab_index(): """returns the last tab index from settings """ return int(os.environ.get(__last_tab__, 0)) class General(object): """General tools """ transform_info_temp_file_path = os.path.join( tempfile.gettempdir(), 'transform_info' ) @classmethod def export_transform_info(cls): """exports the transformation data in to a temp file """ data = [] for node in pm.ls(sl=1, type='transform'): tra = node.t.get() rot = node.r.get() sca = node.s.get() # tra = pm.xform(node, q=1, ws=1, t=1) # node.t.get() # rot = pm.xform(node, q=1, ws=1, ro=1) # node.r.get() # sca = pm.xform(node, q=1, ws=1, s=1) # node.s.get() data.append('%s' % tra[0]) data.append('%s' % tra[1]) data.append('%s' % tra[2]) data.append('%s' % rot[0]) data.append('%s' % rot[1]) data.append('%s' % rot[2]) data.append('%s' % sca[0]) data.append('%s' % sca[1]) data.append('%s' % sca[2]) with open(cls.transform_info_temp_file_path, 'w') as f: f.write('\n'.join(data)) @classmethod def import_transform_info(cls): """imports the transform info from the temp file """ with open(cls.transform_info_temp_file_path) as f: data = f.readlines() for i, node in enumerate(pm.ls(sl=1, type='transform')): j = i * 9 node.t.set(float(data[j]), float(data[j + 1]), float(data[j + 2])) node.r.set(float(data[j + 3]), float(data[j + 4]), float(data[j + 5])) node.s.set(float(data[j + 6]), float(data[j + 7]), float(data[j + 8])) # pm.xform(node, ws=1, t=(float(data[j]), float(data[j + 1]), float(data[j + 2]))) # pm.xform(node, ws=1, ro=(float(data[j + 3]), float(data[j + 4]), float(data[j + 5]))) # pm.xform(node, ws=1, s=(float(data[j + 6]), float(data[j + 7]), float(data[j + 8]))) @classmethod def export_component_transform_info(cls): """exports the transformation data in to a temp file """ data = [] for node in pm.ls(sl=1, fl=1): tra = pm.xform(node, q=1, ws=1, t=1) # node.t.get() data.append('%s' % tra[0]) data.append('%s' % tra[1]) data.append('%s' % tra[2]) with open(cls.transform_info_temp_file_path, 'w') as f: f.write('\n'.join(data)) @classmethod def import_component_transform_info(cls): """imports the transform info from the temp file """ with open(cls.transform_info_temp_file_path) as f: data = f.readlines() for i, node in enumerate(pm.ls(sl=1, fl=1)): j = i * 3 pm.xform(node, ws=1, t=(float(data[j]), float(data[j + 1]), float(data[j + 2]))) @classmethod def toggle_attributes(cls, attribute_name): """toggles the given attribute for the given list of objects """ objs = pm.ls(sl=1) new_list = [] attribute_count = 0 set_to_state = 1 for obj in objs: if obj.hasAttr(attribute_name): if obj.getAttr(attribute_name): attribute_count += 1 new_list.append(obj) obj_count = len(new_list) if attribute_count == obj_count: set_to_state = 0 for obj in new_list: obj.setAttr(attribute_name, set_to_state) @classmethod def dereferencer(cls): """calls dereferencer """ selection = pm.ls() for item in selection: if pm.attributeQuery('overrideEnabled', node=item, exists=True): if not item.overrideEnabled.get(l=True): connections = pm.listConnections(item, d=True) in_layer = 0 for i in range(0, len(connections)): if connections[i].type() == "displayLayer": in_layer = 1 break if not in_layer: if not item.overrideDisplayType.get(l=True): item.overrideDisplayType.set(0) @classmethod def selection_manager(cls): from anima.env.mayaEnv import selection_manager selection_manager.UI() @classmethod def reference_selected_objects(cls): selection = pm.ls(sl=True) for item in selection: if item.overrideEnabled.get(se=True): item.overrideEnabled.set(1) if item.overrideDisplayType.get(se=True): item.overrideDisplayType.set(2) pm.select(cl=True) @classmethod def dereference_selected_objects(cls): selection = pm.ls(sl=True) for item in selection: if item.overrideEnabled.get(se=True): item.overrideEnabled.set(0) if item.overrideDisplayType.get(se=True): item.overrideDisplayType.set(0) pm.select(cl=True) @classmethod def remove_colon_from_names(cls): selection = pm.ls(sl=1) for item in selection: temp = item.split(':')[-1] pm.rename(item, temp) pm.ls(sl=1) @classmethod def remove_pasted(cls): """removes the string 'pasted__' from selected object names """ rmv_str = "pasted__" [ obj.rename(obj.name().split('|')[-1].replace(rmv_str, '')) for obj in pm.ls(sl=1) if rmv_str in obj.name() ] @classmethod def toggle_poly_meshes(cls): """toggles mesh selection in the current panel """ panel_in_focus = pm.getPanel(wf=True) panel_type = pm.getPanel(typeOf=panel_in_focus) if panel_type == "modelPanel": poly_vis_state = pm.modelEditor( panel_in_focus, q=True, polymeshes=True ) pm.modelEditor( panel_in_focus, e=True, polymeshes=(not poly_vis_state) ) @classmethod def select_set_members(cls): selection = pm.ls(sl=1) if not selection: pass else: pm.select(selection[0].inputs()) @classmethod def delete_unused_intermediate_shapes(cls): """clears unused intermediate shape nodes """ unused_nodes = [] for node in pm.ls(type=pm.nt.Mesh): if len(node.inputs()) == 0 and len(node.outputs()) == 0 \ and node.attr('intermediateObject').get(): unused_nodes.append(node) pm.delete(unused_nodes) @classmethod def delete_all_sound(cls): pm.delete(pm.ls(type="audio")) @classmethod def generate_thumbnail(cls): """generates thumbnail for current scene """ from anima.env.mayaEnv import auxiliary reload(auxiliary) result = auxiliary.generate_thumbnail() if result: pm.informBox('Done!', 'Thumbnail generated successfully!') else: pm.informBox('Fail!', 'Thumbnail generation was unsuccessful!') @classmethod def cleanup_light_cameras(cls): """Deletes all the light cameras in the current scene """ cameras_to_delete = [] for node in pm.ls(type='light'): parent = node.getParent() cameras = parent.listRelatives(ad=1, type='camera') if cameras: cameras_to_delete.extend(cameras) pm.delete(cameras_to_delete) class Reference(object): """supplies reference related tools """ @classmethod def get_no_parent_transform(cls, ref): """returns the top most parent node in the given subReferences :param ref: pm.nt.FileReference instance """ all_referenced_nodes = ref.nodes() for node in all_referenced_nodes: if isinstance(node, pm.nt.Transform): #print '%s has parent' % node.name() parent_node = node.getParent() if parent_node not in all_referenced_nodes: return node # check sub references sub_refs = pm.listReferences(ref) for sub_ref in sub_refs: no_parent_transform = cls.get_no_parent_transform(sub_ref) if no_parent_transform: return no_parent_transform @classmethod def duplicate_selected_reference(cls): """duplicates the selected referenced object as reference """ all_selected_refs = [] for sel_node in pm.ls(sl=1): ref = sel_node.referenceFile() if ref not in all_selected_refs: all_selected_refs.append(ref) for ref in all_selected_refs: # get the highest parent ref if ref.parent(): while ref.parent(): ref = ref.parent() namespace = ref.namespace dup_ref = pm.createReference( ref.path, gl=True, namespace=namespace, options='v=0' ) top_parent = cls.get_no_parent_transform(ref) if top_parent: node = top_parent tra = pm.xform(node, q=1, ws=1, t=1) rot = pm.xform(node, q=1, ws=1, ro=1) sca = pm.xform(node, q=1, ws=1, s=1) new_top_parent_node = cls.get_no_parent_transform(dup_ref) pm.xform(new_top_parent_node, ws=1, t=tra) pm.xform(new_top_parent_node, ws=1, ro=rot) pm.xform(new_top_parent_node, ws=1, s=sca) # parent to the same group group = node.getParent() if group: pm.parent(new_top_parent_node, group) # select the top node pm.select(new_top_parent_node) @classmethod def publish_model_as_look_dev(cls): """Publishes Model versions as LookDev versions of the same task. Also handles references etc. """ # # Create LookDev for Current Model Task # from stalker import db, Task, Version, Type, LocalSession, defaults from anima.env import mayaEnv do_db_setup() m = mayaEnv.Maya() local_session = LocalSession() logged_in_user = local_session.logged_in_user if not logged_in_user: raise RuntimeError('Please login to Stalker') model_type = Type.query.filter(Type.name=="Model").first() look_dev_type = \ Type.query.filter(Type.name=="Look Development").first() current_version = m.get_current_version() model_task = current_version.task if model_task.type != model_type: raise RuntimeError('This is not a Model version') if not current_version.is_published: raise RuntimeError('Please Publish this maya scene') if current_version.take_name != 'Main': raise RuntimeError('This is not the Main take') # find lookDev look_dev = Task.query\ .filter(Task.parent == model_task.parent)\ .filter(Task.type == look_dev_type).first() if not look_dev: raise RuntimeError( 'There is no LookDev task, please inform your Stalker admin' ) previous_look_dev_version = \ Version.query\ .filter(Version.task == look_dev)\ .filter(Version.take_name == 'Main')\ .first() description = 'Auto Created By %s ' % logged_in_user.name take_name = defaults.version_take_name if not previous_look_dev_version: # do the trick pm.newFile(f=1) # create a new version new_version = Version( task=look_dev, description=description, take_name=take_name, created_by=logged_in_user ) new_version.is_published = True m.save_as(new_version) # reference the model version pm.createReference( current_version.absolute_full_path, gl=True, namespace=current_version.nice_name, options='v=0' ) pm.saveFile() db.DBSession.add(new_version) else: latest_look_dev_version = previous_look_dev_version.latest_version reference_resolution = m.open(latest_look_dev_version, force=True, skip_update_check=True) m.update_versions(reference_resolution) if reference_resolution['update'] \ or reference_resolution['create']: # create a new version new_version = Version( task=look_dev, description=description, take_name=take_name, created_by=logged_in_user, parent=latest_look_dev_version ) new_version.is_published = True m.save_as(new_version) # reopen model scene m.open(current_version, force=True, skip_update_check=True) @classmethod def get_selected_reference_path(cls): """prints the path of the selected reference path """ selection = pm.ls(sl=1) if len(selection): node = selection[0] ref = node.referenceFile() if ref: print(ref.path) parent_ref = ref.parent() while parent_ref is not None: print(parent_ref.path) parent_ref = parent_ref.parent() @classmethod def open_reference_in_new_maya(cls): """opens the selected references in new maya session """ import subprocess selection = pm.ls(sl=1) if len(selection): node = selection[0] ref = node.referenceFile() if ref: process = subprocess.Popen( ['maya', ref.path], stderr=subprocess.PIPE ) @classmethod def fix_reference_namespace(cls): """fixes reference namespace """ ref_count = len(pm.listReferences(recursive=True)) if ref_count > 25: result = pm.windows.confirmBox( 'Fix Reference Namespace', 'You have %s references in your scene,\n' 'this will take too much time\n\nIs that Ok?' % ref_count ) if not result: return from stalker import db, LocalSession from anima.env import mayaEnv m = mayaEnv.Maya() local_session = LocalSession() logged_in_user = local_session.logged_in_user if not logged_in_user: raise RuntimeError('Please login before running the script') versions = m.fix_reference_namespaces() for version in versions: version.created_by = logged_in_user db.DBSession.commit() @classmethod def fix_reference_paths(cls): """Fixes reference paths that are not using environment vars """ # list current scene references from anima.env import mayaEnv m_env = mayaEnv.Maya() current_version = m_env.get_current_version() all_refs = pm.listReferences(recursive=True) refs_with_wrong_prefix = [] for ref in all_refs: if '$REPO' not in ref.unresolvedPath(): parent = ref.parent() if parent: refs_with_wrong_prefix.append(parent) ref_paths = [ref.path for ref in refs_with_wrong_prefix] for ref_path in ref_paths: version = m_env.get_version_from_full_path(ref_path) if version: m_env.open(version, force=True, skip_update_check=True) pm.saveFile() if pm.env.sceneName() != current_version.absolute_full_path: m_env.open(current_version, force=True, skip_update_check=True) @classmethod def archive_current_scene(cls): """archives the current scene """ # before doing anything ask it response = pm.confirmDialog( title='Do Archive?', message='This will create a ZIP file containing\n' 'the current scene and all its references\n' '\n' 'Is that OK?', button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No' ) if response == 'No': return import os import shutil import anima from anima.env.mayaEnv import Maya from anima.env.mayaEnv.archive import Archiver m_env = Maya() version = m_env.get_current_version() if version: path = version.absolute_full_path arch = Archiver() task = version.task if False: from stalker import Version, Task assert(isinstance(version, Version)) assert(isinstance(task, Task)) project_name = version.nice_name project_path = arch.flatten(path, project_name=project_name) # append link file stalker_link_file_path = \ os.path.join(project_path, 'scenes/stalker_links.txt') version_upload_link = '%s/tasks/%s/versions/list' % ( anima.stalker_server_external_address, task.id ) request_review_link = '%s/tasks/%s/view' % ( anima.stalker_server_external_address, task.id ) with open(stalker_link_file_path, 'w+') as f: f.write("Version Upload Link: %s\n" "Request Review Link: %s\n" % (version_upload_link, request_review_link)) zip_path = arch.archive(project_path) new_zip_path = os.path.join( version.absolute_path, os.path.basename(zip_path) ) # move the zip right beside the original version file shutil.move(zip_path, new_zip_path) # open the zip file in browser from anima.utils import open_browser_in_location open_browser_in_location(new_zip_path) @classmethod def bind_to_original(cls): """binds the current scene references to original references from the repository """ # get all reference paths import os from stalker import Repository, Version for ref in pm.listReferences(): unresolved_path = ref.unresolvedPath() filename = os.path.basename(unresolved_path) # find the corresponding version # TODO: get the versions from current project v = Version.query\ .filter(Version.full_path.endswith(filename))\ .first() if v: ref.replaceWith( Repository.to_os_independent_path(v.absolute_full_path) ) @classmethod def unload_unselected_references(cls): """unloads the references that is not related to the selected objects """ import copy selected_references = [] # store selected references for node in pm.ls(sl=1): ref = node.referenceFile() if ref is not None and ref not in selected_references: selected_references.append(ref) temp_selected_references = copy.copy(selected_references) # store parent references for ref in temp_selected_references: parent_ref = ref.parent() if parent_ref is not None \ and parent_ref not in selected_references: while parent_ref is not None: if parent_ref not in selected_references: selected_references.append(parent_ref) parent_ref = parent_ref.parent() # now unload all the other references for ref in reversed(pm.listReferences(recursive=1)): if ref not in selected_references: ref.unload() @classmethod def to_base(cls): """replaces the related references with Base representation """ cls.to_repr('Base') @classmethod def to_gpu(cls): """replaces the related references with GPU representation """ cls.to_repr('GPU') @classmethod def to_ass(cls): """replaces the related references with the ASS representation """ cls.to_repr('ASS') @classmethod def to_repr(cls, repr_name): """replaces the related references with the given representation :param str repr_name: Desired representation name """ # get apply to apply_to = \ pm.radioButtonGrp('repr_apply_to_radio_button_grp', q=1, sl=1) if apply_to == 1: # work on every selected object selection = pm.ls(sl=1) # collect reference files first references = [] for node in selection: ref = node.referenceFile() if ref is not None and ref not in references: references.append(ref) from anima.env.mayaEnv.repr_tools import RepresentationGenerator # now go over each reference for ref in references: if not ref.is_repr(repr_name): parent_ref = ref while parent_ref is not None: # check if it is a look dev node v = parent_ref.version if v: task = v.task if RepresentationGenerator.is_look_dev_task(task) \ or RepresentationGenerator.is_vegetation_task(task): # convert it to repr parent_ref.to_repr(repr_name) break else: # go to parent ref parent_ref = parent_ref.parent() else: parent_ref = parent_ref.parent() elif apply_to == 2: # apply to all references for ref in pm.listReferences(): ref.to_repr(repr_name) @classmethod def generate_repr_of_scene_caller(cls): """helper method to call Reference.generate_repr_of_scene() with data coming from UI """ generate_gpu = 1 if pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v1=1) else 0 generate_ass = 1 if pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v2=1) else 0 generate_rs = 1 if pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v3=1) else 0 skip_existing = \ pm.checkBox('generate_repr_skip_existing_checkBox', q=1, v=1) cls.generate_repr_of_scene( generate_gpu, generate_ass, generate_rs, skip_existing ) @classmethod def generate_repr_of_scene(cls, generate_gpu=True, generate_ass=True, generate_rs=True, skip_existing=False): """generates desired representations of this scene """ from anima.ui.progress_dialog import ProgressDialogManager from anima.env.mayaEnv import Maya, repr_tools, auxiliary reload(auxiliary) reload(repr_tools) response = pm.confirmDialog( title='Do Create Representations?', message='Create all Repr. for this scene?', button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No' ) if response == 'No': return # register a new caller from anima.env.mayaEnv import MayaMainProgressBarWrapper wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) m_env = Maya() source_version = m_env.get_current_version() gen = repr_tools.RepresentationGenerator() # open each version from stalker import Version if skip_existing: # check if there is a GPU or ASS repr # generated from this version child_versions = \ Version.query.filter(Version.parent == source_version).all() for cv in child_versions: if generate_gpu is True and '@GPU' in cv.take_name: generate_gpu = False if generate_ass is True and '@ASS' in cv.take_name: generate_ass = False if generate_rs is True and '@RS' in cv.take_name: generate_rs = False total_number_of_reprs = generate_gpu + generate_ass + generate_rs caller = pdm.register(total_number_of_reprs, title='Generate Reprs') gen.version = source_version # generate representations if generate_gpu: gen.generate_gpu() caller.step() if generate_ass: gen.generate_ass() caller.step() if generate_rs: gen.generate_rs() caller.step() # now open the source version again m_env.open(source_version, force=True, skip_update_check=True) @classmethod def generate_repr_of_all_references_caller(cls): """a helper method that calls References.generate_repr_of_all_references() with paremeters from the UI """ generate_gpu = pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v1=1) generate_ass = pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v2=1) generate_rs = pm.checkBoxGrp('generate_repr_types_checkbox_grp', q=1, v3=1) skip_existing = \ pm.checkBox('generate_repr_skip_existing_checkBox', q=1, v=1) cls.generate_repr_of_all_references( generate_gpu, generate_ass, generate_rs, skip_existing ) @classmethod def generate_repr_of_all_references(cls, generate_gpu=True, generate_ass=True, generate_rs=True, skip_existing=False): """generates all representations of all references of this scene """ from anima.ui.progress_dialog import ProgressDialogManager from anima.env.mayaEnv import Maya, repr_tools, auxiliary reload(auxiliary) reload(repr_tools) paths_visited = [] versions_to_visit = [] versions_cannot_be_published = [] # generate a sorted version list # and visit each reference only once from anima.env.mayaEnv import MayaMainProgressBarWrapper wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) use_progress_window = False if not pm.general.about(batch=1): use_progress_window = True all_refs = pm.listReferences(recursive=True) pdm.use_ui = use_progress_window caller = pdm.register(len(all_refs), 'List References') for ref in reversed(all_refs): ref_path = str(ref.path) caller.step(message=ref_path) if ref_path not in paths_visited: v = ref.version if v is not None: paths_visited.append(ref_path) versions_to_visit.append(v) response = pm.confirmDialog( title='Do Create Representations?', message='Create all Repr. for all %s FileReferences?' % len(versions_to_visit), button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No' ) if response == 'No': return # register a new caller caller = pdm.register(max_iteration=len(versions_to_visit), title='Generate Reprs') m_env = Maya() source_version = m_env.get_current_version() gen = repr_tools.RepresentationGenerator() # open each version from stalker import Version for v in versions_to_visit: local_generate_gpu = generate_gpu local_generate_ass = generate_ass local_generate_rs = generate_rs # check if this is a repr if '@' in v.take_name: # use the parent v = v.parent if not v: continue if skip_existing: # check if there is a GPU or ASS repr # generated from this version child_versions = Version.query.filter(Version.parent == v).all() for cv in child_versions: if local_generate_gpu is True and '@GPU' in cv.take_name: local_generate_gpu = False if local_generate_ass is True and '@ASS' in cv.take_name: local_generate_ass = False if local_generate_rs is True and '@RS' in cv.take_name: local_generate_rs = False gen.version = v # generate representations if local_generate_gpu: try: gen.generate_gpu() except RuntimeError: if v not in versions_cannot_be_published: versions_cannot_be_published.append(v) if local_generate_ass: try: gen.generate_ass() except RuntimeError: if v not in versions_cannot_be_published: versions_cannot_be_published.append(v) if local_generate_rs: try: gen.generate_rs() except RuntimeError: if v not in versions_cannot_be_published: versions_cannot_be_published.append(v) caller.step() # now open the source version again m_env.open(source_version, force=True, skip_update_check=True) # and generate representation for the source gen.version = source_version # generate representations if not versions_cannot_be_published: if generate_gpu: gen.generate_gpu() if generate_ass: gen.generate_ass() if generate_rs: gen.generate_rs() else: pm.confirmDialog( title='Error', message='The following versions can not be published ' '(check script editor):\n\n%s' % ( '\n'.join( map(lambda x: x.nice_name, versions_cannot_be_published) ) ), button=['OK'], defaultButton='OK', cancelButton='OK', dismissString='OK' ) pm.error( '\n'.join( map(lambda x: x.absolute_full_path, versions_cannot_be_published) ) ) class Modeling(object): """Modeling tools """ @classmethod def reverse_normals(cls): selection = pm.ls(sl=1) for item in selection: pm.polyNormal(item, normalMode=0, userNormalMode=0, ch=1) pm.delete(ch=1) pm.select(selection) @classmethod def fix_normals(cls): selection = pm.ls(sl=1) pm.polySetToFaceNormal() for item in selection: pm.polyNormal(item, normalMode=2, userNormalMode=0, ch=1) pm.polySoftEdge(item, a=180, ch=1) pm.delete(ch=1) pm.select(selection) @classmethod def polySmoothFace(cls, method): selection = pm.ls(sl=1) for item in selection: pm.polySmooth( item, mth=method, dv=1, c=1, kb=0, ksb=0, khe=0, kt=1, kmb=0, suv=1, peh=0, sl=1, dpe=1, ps=0.1, ro=1, ch=1 ) pm.select(selection) @classmethod def activate_deActivate_smooth(cls, nodeState): selection = pm.ls(type='polySmoothFace') for item in selection: item.nodeState.set(nodeState) @classmethod def delete_smooth(cls): Modeling.activate_deActivate_smooth(0) selection = pm.ls(type='polySmoothFace') if len(selection) > 0: pm.delete(selection) @classmethod def delete_smooth_on_selected(cls): selection = pm.ls(sl=1) deleteList = [] for item in selection: hist = pm.listHistory(item) for i in range(0, len(hist)): if hist[i].type() == 'polySmoothFace': deleteList.append(hist[i]) pm.delete(deleteList) @classmethod def hierarchy_instancer(cls): from anima.env.mayaEnv import hierarchy_instancer instancer = hierarchy_instancer.HierarchyInstancer() for node in pm.ls(sl=1): instancer.instance(node) @classmethod def relax_vertices(cls): from anima.env.mayaEnv import relax_vertices relax_vertices.relax() @classmethod def create_curve_from_mesh_edges(cls): """creates 3rd degree curves from the selected mesh edges """ def order_edges(edge_list): """orders the given edge list according to their connectivity """ edge_list = pm.ls(edge_list, fl=1) # find a starting edge starting_edge = None for e in edge_list: connected_edges = pm.ls(e.connectedEdges(), fl=1) number_of_connected_edges_in_selection = 0 for e2 in connected_edges: if e2 in edge_list: number_of_connected_edges_in_selection += 1 if number_of_connected_edges_in_selection == 1: starting_edge = e break if starting_edge is None: starting_edge = edge_list[0] current_edge = starting_edge ordered_edges = [current_edge] edge_list.remove(current_edge) i = 0 while current_edge and len(edge_list) and i < 1000: i += 1 # go over neighbours that are in the selection list next_edge = None connected_edges = pm.ls(current_edge.connectedEdges(), fl=1) for e in connected_edges: if e in edge_list: next_edge = e break if next_edge: edge_list.remove(next_edge) current_edge = next_edge ordered_edges.append(current_edge) return ordered_edges def order_vertices(ordered_edges): """orders the vertices of the given ordered edge list """ # now get an ordered list of vertices ordered_vertices = [] for i, e in enumerate(ordered_edges[0:-1]): v0, v1 = pm.ls(e.connectedVertices(), fl=1) # get the connected edges of v0 if ordered_edges[i+1] not in pm.ls(v0.connectedEdges(), fl=1): # v0 is the first vertex ordered_vertices.append(v0) else: # v0 is the second vertex ordered_vertices.append(v1) # append the vertex of the last edge which is not in the list v0, v1 = pm.ls(ordered_edges[-1].connectedVertices(), fl=1) # get the connected edges of v0 if ordered_edges[-2] not in pm.ls(v0.connectedEdges(), fl=1): # v0 is the last vertex ordered_vertices.append(v1) ordered_vertices.append(v0) else: # v1 is the last vertex ordered_vertices.append(v0) ordered_vertices.append(v1) return ordered_vertices selection = pm.ls(sl=1) ordered_edges = order_edges(selection) ordered_vertices = order_vertices(ordered_edges) # now create a curve from the given vertices pm.curve( p=map(lambda x: x.getPosition(space='world'), ordered_vertices), d=3 ) @classmethod def vertex_aligned_locator(cls): """creates vertex aligned locator, select 3 vertices """ selection = pm.ls(os=1, fl=1) # get the axises p0 = selection[0].getPosition(space='world') p1 = selection[1].getPosition(space='world') p2 = selection[2].getPosition(space='world') v1 = p0 - p1 v2 = p2 - p1 #v3 = p0 - p2 v1.normalize() v2.normalize() dcm = pm.createNode('decomposeMatrix') x = v1 z = v2 y = z ^ x y.normalize() dcm.inputMatrix.set( [x[0], x[1], x[2], 0, y[0], y[1], y[2], 0, z[0], z[1], z[2], 0, 0, 0, 0, 1], type='matrix') loc = pm.spaceLocator() loc.t.set(p1) loc.r.set(dcm.outputRotate.get()) pm.delete(dcm) @classmethod def select_zero_uv_area_faces(cls): """selects faces with zero UV area """ def area(p): return 0.5 * abs(sum(x0 * y1 - x1 * y0 for ((x0, y0), (x1, y1)) in segments(p))) def segments(p): return zip(p, p[1:] + [p[0]]) all_meshes = pm.ls( [node.getShape() for node in pm.ls(sl=1)], type='mesh' ) mesh_count = len(all_meshes) from anima.env.mayaEnv import MayaMainProgressBarWrapper from anima.ui.progress_dialog import ProgressDialogManager wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) if not pm.general.about(batch=1) and mesh_count: pdm.use_ui = True caller = pdm.register(mesh_count, 'check_uvs()') faces_with_zero_uv_area = [] for node in all_meshes: all_uvs = node.getUVs() for i in range(node.numFaces()): uvs = [] try: for j in range(node.numPolygonVertices(i)): #uvs.append(node.getPolygonUV(i, j)) uv_id = node.getPolygonUVid(i, j) uvs.append((all_uvs[0][uv_id], all_uvs[1][uv_id])) if area(uvs) == 0.0: #meshes_with_zero_uv_area.append(node) #break faces_with_zero_uv_area.append( '%s.f[%s]' % (node.fullPath(), i) ) except RuntimeError: faces_with_zero_uv_area.append( '%s.f[%s]' % (node.fullPath(), i) ) caller.step() if len(faces_with_zero_uv_area) == 0: pm.warning('No Zero UV area polys found!!!') else: pm.select(faces_with_zero_uv_area) @classmethod def set_pivot(cls, axis=0): """moves the object pivot to desired axis There are 7 options to move the pivot point to: c, -x, +x, -y, +y, -z, +z 0, 1, 2, 3, 4, 5, 6 :param int axis: One of [0-6] showing the desired axis to get the pivot point to """ from maya.OpenMaya import MBoundingBox, MPoint if not 0 <= axis <= 6: return for node in pm.ls(sl=1): # check if the node has children children = pm.ls(sl=1)[0].getChildren(ad=1, type='transform') # get the bounding box points # bbox = node.boundingBox() bbox = pm.xform(node, q=1, ws=1, boundingBox=1) bbox = MBoundingBox( MPoint(bbox[0], bbox[1], bbox[2]), MPoint(bbox[3], bbox[4], bbox[5]) ) if len(children): # get all the bounding boxes for child in children: if child.getShape() is not None: # child_bbox = child.boundingBox() child_bbox = pm.xform(child, q=1, ws=1, boundingBox=1) child_bbox = MBoundingBox( MPoint(child_bbox[0], child_bbox[1], child_bbox[2]), MPoint(child_bbox[3], child_bbox[4], child_bbox[5]) ) bbox.expand(child_bbox.min()) bbox.expand(child_bbox.max()) piv = bbox.center() if axis == 1: # -x piv.x = bbox.min().x elif axis == 2: # +x piv.x = bbox.max().x elif axis == 3: # -y piv.y = bbox.min().y elif axis == 4: # +y piv.y = bbox.max().y elif axis == 5: # -z piv.z = bbox.min().z elif axis == 6: # +z piv.z = bbox.max().z pm.xform(node, ws=1, rp=piv) pm.xform(node, ws=1, sp=piv) @classmethod def set_texture_res(cls, res): """sets the texture resolution :param res: :return: """ selection_list = pm.ls(sl=1) if not len(selection_list): return node = selection_list[0] # if the selection is a material try: node.resolution.set(res) except AttributeError: # not a material # try it as a DAG object try: shape = node.getShape() except RuntimeError: # not a DAG object with shape return shading_engines = shape.outputs(type='shadingEngine') if not len(shading_engines): # not an object either # so what the fuck are you amk return # consider the first material conn = shading_engines[0].surfaceShader.listConnections() if len(conn): material = conn[0] # now we can set the resolution material.resolution.set(res) class Rigging(object): """Rigging tools """ @classmethod def setup_stretchy_spline_IKCurve(cls): """ """ selection = pm.ls(sl=1) curve = selection[0] curve_info = pm.createNode("curveInfo") mult_div = pm.createNode("multiplyDivide") curve_shape = pm.listRelatives(curve, s=1) curve_shape[0].worldSpace >> curve_info.ic curve_info.arcLength >> mult_div.input1X curve_length = curve_info.arcLength.get() mult_div.input2X.set(curve_length) mult_div.operation.set(2) pm.select(mult_div, curve_info, curve_shape[0], add=True) @classmethod def select_joints_deforming_object(cls): selection = pm.ls(sl=1) conn = pm.listHistory(selection[0]) skin_cluster = "" for i in range(0, len(conn)): if conn[i].type() == "skinCluster": skin_cluster = conn[i] break conn = pm.listConnections(skin_cluster) joints = [] for item in conn: if item.type() == "joint": joints.append(item) pm.select(joints) @classmethod def axial_correction_group(cls): selection = pm.ls(sl=1) for item in selection: auxiliary.axial_correction_group(item) @classmethod def create_axial_correction_group_for_clusters(cls): selection = pm.ls(sl=1) Rigging.axial_correction_group() pm.select(cl=1) for cluster_handle in selection: cluster_handle_shape = pm.listRelatives(cluster_handle, s=True) cluster_parent = pm.listRelatives(cluster_handle, p=True) trans = cluster_handle_shape[0].origin.get() cluster_parent[0].translate.set(trans[0], trans[1], trans[2]) pm.select(selection) @classmethod def set_clusters_relative_state(cls, relative_state): selection = pm.ls(sl=1) cluster = "" for clusterHandle in selection: conn = pm.listConnections(clusterHandle) for i in range(0, len(conn)): if conn[i].type() == "cluster": cluster = conn[i] break cluster.relative.set(relative_state) @classmethod def add_controller_shape(cls): selection = pm.ls(sl=1) if len(selection) < 2: return objects = [] for i in range(0, (len(selection) - 1)): objects.append(selection[i]) joints = selection[len(selection) - 1] for i in range(0, len(objects)): parents = pm.listRelatives(objects[i], p=True) if len(parents) > 0: temp_list = pm.parent(objects[i], w=1) objects[i] = temp_list[0] temp_list = pm.parent(objects[i], joints) objects[i] = temp_list[0] pm.makeIdentity(objects[i], apply=True, t=1, r=1, s=1, n=0) temp_list = pm.parent(objects[i], w=True) objects[i] = temp_list[0] shapes = pm.listRelatives(objects, s=True, pa=True) for i in range(0, len(shapes)): temp_list = pm.parent(shapes[i], joints, r=True, s=True) shapes[i] = temp_list[0] joint_shapes = pm.listRelatives(joints, s=True, pa=True) for i in range(0, len(joint_shapes)): name = "%sShape%f" % (joints, (i + 1)) temp = ''.join(name.split('|', 1)) pm.rename(joint_shapes[i], temp) pm.delete(objects) pm.select(joints) @classmethod def replace_controller_shape(cls): selection = pm.ls(sl=1) if len(selection) < 2: return objects = selection[0] joints = selection[1] shape = pm.listRelatives(objects, s=True) joint_shape = pm.listRelatives(joints, s=True) parents = pm.listRelatives(objects, p=True) if len(parents): temp_list = pm.parent(objects, w=True) objects = temp_list temp_list = pm.parent(objects, joints) objects = temp_list[0] pm.makeIdentity(objects, apply=True, t=1, r=1, s=1, n=0) temp_list = pm.parent(objects, w=True) objects = temp_list[0] if len(joint_shape): pm.delete(joint_shape) for i in range(0, len(shape)): name = "%sShape%f" % (joints, (i + 1)) shape[i] = pm.rename(shape[i], name) temp_list = pm.parent(shape[i], joints, r=True, s=True) shape[i] = temp_list[0] pm.delete(objects) pm.select(joints) @classmethod def fix_bound_joint(cls): from anima.env.mayaEnv import fix_bound_joint fix_bound_joint.UI() @classmethod def create_follicle(cls, component): """creates a follicle at given component """ follicleShape = pm.createNode('follicle') geometry = component.node() uv = None if isinstance(geometry, pm.nt.Mesh): geometry.attr('outMesh') >> follicleShape.attr('inputMesh') # get uv uv = component.getUV() elif isinstance(geometry, pm.nt.NurbsSurface): geometry.attr('local') >> follicleShape.attr('inputSurface') # get uv # TODO: Fix this uv = [0, 0] geometry.attr('worldMatrix[0]') >> follicleShape.attr( 'inputWorldMatrix') follicleShape.setAttr('pu', uv[0]) follicleShape.setAttr('pv', uv[1]) # set simulation to static follicleShape.setAttr('simulationMethod', 0) # connect to its transform node follicle = follicleShape.getParent() follicleShape.attr('outTranslate') >> follicle.attr('t') follicleShape.attr('outRotate') >> follicle.attr('r') return follicle @classmethod def create_follicles(cls): for comp in pm.ls(sl=1, fl=1): Rigging.create_follicle(comp) @classmethod def reset_tweaks(cls): """Resets the tweaks on the selected deformed objects """ for obj in pm.ls(sl=1): for tweak_node in pm.ls(obj.listHistory(), type=pm.nt.Tweak): try: for i in tweak_node.pl[0].cp.get(mi=1): tweak_node.pl[0].cv[i].vx.set(0) tweak_node.pl[0].cv[i].vy.set(0) tweak_node.pl[0].cv[i].vz.set(0) except TypeError: try: for i in tweak_node.vl[0].vt.get(mi=1): tweak_node.vl[0].vt[i].vx.set(0) tweak_node.vl[0].vt[i].vy.set(0) tweak_node.vl[0].vt[i].vz.set(0) except TypeError: pass class Render(object): """Tools for render """ @classmethod def auto_convert_to_redshift(cls): """converts the current scene to Redshift """ from anima.env.mayaEnv import ai2rs cm = ai2rs.ConversionManager() cm.auto_convert() @classmethod def convert_nodes_to_redshift(cls): """converts the selected nodes to Redshift """ from anima.env.mayaEnv import ai2rs cm = ai2rs.ConversionManager() for node in pm.selected(): cm.convert(node) @classmethod def standin_to_bbox(cls): """convert the selected stand-in nodes to bbox """ [node.mode.set(0) for node in pm.ls(sl=1) if isinstance(node.getShape(), pm.nt.AiStandIn)] @classmethod def standin_to_polywire(cls): """convert the selected stand-in nodes to bbox """ [node.mode.set(2) for node in pm.ls(sl=1) if isinstance(node.getShape(), pm.nt.AiStandIn)] @classmethod def add_miLabel(cls): selection = pm.ls(sl=1) for node in selection: if node.type() == 'Transform': if node.hasAttr('miLabel'): pass else: pm.addAttr(node, ln='miLabel', at='long', keyable=True) @classmethod def connect_facingRatio_to_vCoord(cls): selection = pm.ls(sl=1) for i in range(1, len(selection)): selection[0].facingRatio.connect((selection[i] + '.vCoord'), force=True) @classmethod def set_shape_attribute(cls, attr_name, value, apply_to_hierarchy, disable_undo_queue=False): """sets shape attributes """ undo_state = pm.undoInfo(q=1, st=1) if disable_undo_queue: pm.undoInfo(st=False) supported_shapes = [ 'aiStandIn', 'mesh', 'nurbsCurve' ] attr_mapper = { 'castsShadows': 'overrideCastsShadows', 'receiveShadows': 'overrideReceiveShadows', 'primaryVisibility': 'overridePrimaryVisibility', 'visibleInReflections': 'overrideVisibleInReflections', 'visibleInRefractions': 'overrideVisibleInRefractions', 'doubleSided': 'overrideDoubleSided', 'aiSelfShadows': 'overrideSelfShadows', 'aiOpaque': 'overrideOpaque', 'aiVisibleInDiffuse': 'overrideVisibleInDiffuse', 'aiVisibleInGlossy': 'overrideVisibleInGlossy', 'aiMatte': 'overrideMatte', } pre_selection_list = pm.ls(sl=1) if apply_to_hierarchy: pm.select(hierarchy=1) objects = pm.ls(sl=1, type=supported_shapes) # get override_attr_name from dictionary if attr_name in attr_mapper: override_attr_name = attr_mapper[attr_name] else: override_attr_name = None # register a caller from anima.env.mayaEnv import MayaMainProgressBarWrapper wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) pdm.use_ui = True if len(objects) > 3 else False caller = pdm.register(len(objects), 'Setting Shape Attribute') layers = pm.ls(type='renderLayer') is_default_layer = \ layers[0].currentLayer() == layers[0].defaultRenderLayer() if value != -1: for item in objects: attr_full_name = '%s.%s' % (item.name(), attr_name) override_attr_full_name = '%s.%s' % (item.name(), override_attr_name) caller.step(message=attr_full_name) if not is_default_layer: pm.editRenderLayerAdjustment(attr_full_name) item.setAttr(attr_name, value) # if there is an accompanying override attribute like it is # found in aiStandIn node # then also set override{Attr} to True if override_attr_name \ and cmds.attributeQuery(override_attr_name, n=item.name(), ex=1): if not is_default_layer: pm.editRenderLayerAdjustment( override_attr_full_name ) item.setAttr(override_attr_name, True) else: for item in objects: attr_full_name = '%s.%s' % (item.name(), attr_name) override_attr_full_name = '%s.%s' % (item.name(), override_attr_name) caller.step(message=attr_full_name) # remove any overrides if not is_default_layer: pm.editRenderLayerAdjustment( attr_full_name, remove=1 ) if override_attr_name \ and cmds.attributeQuery(override_attr_name, n=item.name(), ex=1) \ and not is_default_layer: pm.editRenderLayerAdjustment( override_attr_full_name, remove=1 ) # caller.end_progress() pm.undoInfo(st=undo_state) pm.select(pre_selection_list) @classmethod def set_finalGatherHide(cls, value): """sets the finalGatherHide to on or off for the given list of objects """ attr_name = "miFinalGatherHide" objects = pm.ls(sl=1) for obj in objects: shape = obj if isinstance(obj, pm.nt.Transform): shape = obj.getShape() if not isinstance(shape, (pm.nt.Mesh, pm.nt.NurbsSurface)): continue # add the attribute if it doesn't already exists if not shape.hasAttr(attr_name): pm.addAttr(shape, ln=attr_name, at="long", min=0, max=1, k=1) obj.setAttr(attr_name, value) @classmethod def replace_shaders_with_last(cls): """Assigns the last shader selected to all the objects using the shaders on the list """ sel_list = pm.ls(sl=1) target_node = sel_list[-1] for node in sel_list[:-1]: pm.hyperShade(objects=node) pm.hyperShade(assign=target_node) pm.select(None) @classmethod def create_texture_ref_object(cls): selection = pm.ls(sl=1) for obj in selection: pm.select(obj) pm.runtime.CreateTextureReferenceObject() pm.select(selection) @classmethod def use_mib_texture_filter_lookup(cls): """Adds texture filter lookup node to the selected file texture nodes for better texture filtering. The function is smart enough to use the existing nodes, if there is a connection from the selected file nodes to a mib_texture_filter_lookup node then it will not create any new node and just use the existing ones. It will also not create any place2dTexture nodes if the file node doesn't have a place2dTexture node but is connected to a filter lookup node which already has a connection to a place2dTexture node. """ file_nodes = pm.ls(sl=1, type="file") for file_node in file_nodes: # set the filter type to none file_node.filterType.set(0) # check if it is already connected to a mib_texture_filter_lookup node message_outputs = \ file_node.message.outputs(type="mib_texture_filter_lookup") if len(message_outputs): # use the first one mib_texture_filter_lookup = message_outputs[0] else: # create a texture filter lookup node mib_texture_filter_lookup = \ pm.createNode("mib_texture_filter_lookup") # do the connection file_node.message >> mib_texture_filter_lookup.tex # check if the mib_texture_filter_lookup has any connection to a # placement node mib_t_f_l_to_placement = \ mib_texture_filter_lookup.inputs(type="place2dTexture") placement_node = None if len(mib_t_f_l_to_placement): # do nothing placement_node = mib_t_f_l_to_placement[0].node() else: # get the texture placement placement_connections = \ file_node.inputs(type="place2dTexture", p=1, c=1) # if there is no placement create one placement_node = None if len(placement_connections): placement_node = placement_connections[0][1].node() # disconnect connections from placement to file node for conn in placement_connections: conn[1] // conn[0] else: placement_node = pm.createNode("place2dTexture") # connect placement to mr_texture_filter_lookup placement_node.outU >> mib_texture_filter_lookup.coordX placement_node.outV >> mib_texture_filter_lookup.coordY # connect color for output in file_node.outColor.outputs(p=1): mib_texture_filter_lookup.outValue >> output # connect alpha for output in file_node.outAlpha.outputs(p=1): mib_texture_filter_lookup.outValueA >> output @classmethod def convert_to_linear(cls): """adds a gamma_gain node in between the selected nodes outputs to make the result linear """ # # convert to linear # selection = pm.ls(sl=1) for file_node in selection: # get the connections outputs = file_node.outputs(plugs=True) if not len(outputs): continue # and insert a mip_gamma_gain gamma_node = pm.createNode('mip_gamma_gain') gamma_node.setAttr('gamma', 2.2) gamma_node.setAttr('reverse', True) # connect the file_node to gamma_node try: file_node.outValue >> gamma_node.input file_node.outValueA >> gamma_node.inputA except AttributeError: file_node.outColor >> gamma_node.input # do all the connections from the output of the gamma for output in outputs: try: gamma_node.outValue >> output except RuntimeError: gamma_node.outValueA >> output pm.select(selection) @classmethod def use_image_sequence(cls): """creates an expression to make the mentalrayTexture node also able to read image sequences Select your mentalrayTexture nodes and then run the script. The filename should use the file.%nd.ext format """ textures = pm.ls(sl=1, type="mentalrayTexture") for texture in textures: # get the filename filename = texture.getAttr("fileTextureName") splits = filename.split(".") if len(splits) == 3: base = ".".join(splits[0:-2]) + "." pad = len(splits[-2]) extension = "." + splits[-1] expr = 'string $padded_frame = python("\'%0' + str(pad) + \ 'd\'%" + string(frame));\n' + \ 'string $filename = "' + base + '" + \ $padded_frame + ".tga";\n' + \ 'setAttr -type "string" ' + texture.name() + \ '.fileTextureName $filename;\n' # create the expression pm.expression(s=expr) @classmethod def add_to_selected_container(cls): selection = pm.ls(sl=1) conList = pm.ls(sl=1, con=1) objList = list(set(selection) - set(conList)) if len(conList) == 0: pm.container(addNode=selection) elif len(conList) == 1: pm.container(conList, edit=True, addNode=objList) else: length = len(conList) - 1 for i in range(0, length): containerList = conList[i] pm.container(conList[-1], edit=True, f=True, addNode=containerList) pm.container(conList[-1], edit=True, f=True, addNode=objList) @classmethod def remove_from_container(cls): selection = pm.ls(sl=1) for i in range(0, len(selection)): con = pm.container(q=True, fc=selection[i]) pm.container(con, edit=True, removeNode=selection[i]) @classmethod def reload_file_textures(cls): fileList = pm.ls(type="file") for fileNode in fileList: mel.eval('AEfileTextureReloadCmd(%s.fileTextureName)' % fileNode) @classmethod def transfer_shaders(cls): """transfer shaders between selected objects. It can search for hierarchies both in source and target sides. """ selection = pm.ls(sl=1) pm.select(None) source = selection[0] target = selection[1] # auxiliary.transfer_shaders(source, target) # pm.select(selection) # check if they are direct parents of mesh or nurbs shapes source_shape = source.getShape() target_shape = target.getShape() if source_shape and target_shape: # do a direct assignment from source to target shading_engines = source_shape.outputs(type=pm.nt.ShadingEngine) pm.sets(shading_engines[0], fe=target) pm.select(selection) return lut = auxiliary.match_hierarchy(source, target) attr_names = [ 'castsShadows', 'receiveShadows', 'motionBlur', 'primaryVisibility', 'smoothShading', 'visibleInReflections', 'visibleInRefractions', 'doubleSided', 'opposite', 'aiSelfShadows', 'aiOpaque', 'aiVisibleInDiffuse', 'aiVisibleInGlossy', 'aiExportTangents', 'aiExportColors', 'aiExportRefPoints', 'aiExportRefNormals', 'aiExportRefTangents', 'color', 'intensity', 'aiExposure', 'aiColorTemperature', 'emitDiffuse', 'emitSpecular', 'aiDecayType', 'lightVisible', 'aiSamples', 'aiNormalize', 'aiCastShadows', 'aiShadowDensity', 'aiShadowColor', 'aiAffectVolumetrics', 'aiCastVolumetricShadows', 'aiVolumeSamples', 'aiDiffuse', 'aiSpecular', 'aiSss', 'aiIndirect', 'aiMaxBounces', 'aiSubdivType', 'aiSubdivIterations', 'aiSubdivAdaptiveMetric', 'aiSubdivPixelError', 'aiSubdivUvSmoothing', 'aiSubdivSmoothDerivs', 'aiDispHeight', 'aiDispPadding', 'aiDispZeroValue', 'aiDispAutobump', 'aiStepSize', 'rsEnableSubdivision', 'rsSubdivisionRule', 'rsScreenSpaceAdaptive', 'rsDoSmoothSubdivision', 'rsMinTessellationLength', 'rsMaxTessellationSubdivs', 'rsOutOfFrustumTessellationFactor', 'rsEnableDisplacement', 'rsMaxDisplacement', 'rsDisplacementScale', 'rsAutoBumpMap', ] # from anima.ui import progress_dialog # from anima.env.mayaEnv import MayaMainProgressBarWrapper # wrp = MayaMainProgressBarWrapper() # pdm = progress_dialog.ProgressDialogManager(dialog=wrp) # caller = pdm.register(2, title='Transferring materials') for source_node, target_node in lut['match']: auxiliary.transfer_shaders(source_node, target_node) # also transfer render attributes for attr_name in attr_names: try: target_node.setAttr( attr_name, source_node.getAttr(attr_name) ) except pm.MayaAttributeError: pass # caller.step() # caller.end_progress() if len(lut['no_match']): pm.select(lut['no_match']) print( 'The following nodes has no corresponding source:\n%s' % ( '\n'.join( [node.name() for node in lut['no_match']] ) ) ) @classmethod def transfer_uvs(cls): """transfer uvs between selected objects. It can search for hierarchies both in source and target sides. """ selection = pm.ls(sl=1) pm.select(None) source = selection[0] target = selection[1] # auxiliary.transfer_shaders(source, target) # pm.select(selection) lut = auxiliary.match_hierarchy(source, target) for source, target in lut['match']: pm.transferAttributes( source, target, transferPositions=0, transferNormals=0, transferUVs=2, transferColors=2, sampleSpace=4, sourceUvSpace='map1', searchMethod=3, flipUVs=0, colorBorders=1 ) @classmethod def fit_placement_to_UV(cls): selection = pm.ls(sl=1, fl=1) uvs = [] placements = [] for uv in selection: if isinstance(uv, pm.general.MeshUV): uvs.append(uv) for p in selection: if isinstance(p, pm.nodetypes.Place2dTexture): placements.append(p) minU = 1000 minV = 1000 maxU = -1000 maxV = -1000 for uv in uvs: uvCoord = pm.polyEditUV(uv, q=1) if uvCoord[0] > maxU: maxU = uvCoord[0] if uvCoord[0] < minU: minU = uvCoord[0] if uvCoord[1] > maxV: maxV = uvCoord[1] if uvCoord[1] < minV: minV = uvCoord[1] for p in placements: p.setAttr('coverage', (maxU - minU, maxV - minV)) p.setAttr('translateFrame', (minU, minV)) @classmethod def open_node_in_browser(cls): # get selected nodes node_attrs = { 'file': 'fileTextureName', 'aiImage': 'filename', 'aiStandIn': 'dso', } import os from anima.utils import open_browser_in_location for node in pm.ls(sl=1): type_ = pm.objectType(node) # special case: if transform use shape if type_ == 'transform': node = node.getShape() type_ = pm.objectType(node) attr_name = node_attrs.get(type_) if attr_name: # if any how it contains a "#" character use the path path = node.getAttr(attr_name) if "#" in path: path = os.path.dirname(path) open_browser_in_location(path) @classmethod def enable_matte(cls, color=0): """enables matte on selected objects """ # # Enable Matte on Selected Objects # colors = [ [0, 0, 0, 0], # Not Visible [1, 0, 0, 0], # Red [0, 1, 0, 0], # Green [0, 0, 1, 0], # Blue [0, 0, 0, 1], # Alpha ] arnold_shaders = ( pm.nt.AiStandard, pm.nt.AiHair, pm.nt.AiSkin, pm.nt.AiUtility ) for node in pm.ls(sl=1, dag=1, type=[pm.nt.Mesh, pm.nt.NurbsSurface, 'aiStandIn']): obj = node #if isinstance(node, pm.nt.Mesh): # obj = node #elif isinstance(node, pm.nt.Transform): # obj = node.getShape() shading_nodes = pm.listConnections(obj, type='shadingEngine') for shadingNode in shading_nodes: shader = shadingNode.attr('surfaceShader').connections()[0] if isinstance(shader, arnold_shaders): try: pm.editRenderLayerAdjustment(shader.attr("aiEnableMatte")) pm.editRenderLayerAdjustment(shader.attr("aiMatteColor")) pm.editRenderLayerAdjustment(shader.attr("aiMatteColorA")) shader.attr("aiEnableMatte").set(1) shader.attr("aiMatteColor").set(colors[color][0:3], type='double3') shader.attr("aiMatteColorA").set(colors[color][3]) except RuntimeError as e: # there is some connections print(str(e)) @classmethod def enable_subdiv(cls): """enables subdiv on selected objects """ # # Set SubDiv to CatClark on Selected nodes # for node in pm.ls(sl=1): shape = node.getShape() try: shape.aiSubdivIterations.set(2) shape.aiSubdivType.set(1) shape.aiSubdivPixelError.set(0) except AttributeError: pass @classmethod def barndoor_simulator_setup(cls): """creates a barndoor simulator """ bs = auxiliary.BarnDoorSimulator() bs.light = pm.ls(sl=1)[0] bs.setup() @classmethod def barndoor_simulator_unsetup(cls): """removes the barndoor simulator """ bs = auxiliary.BarnDoorSimulator() for light in pm.ls(sl=1): light_shape = light.getShape() if isinstance(light_shape, pm.nt.Light): bs.light = light bs.unsetup() @classmethod def fix_barndoors(cls): """fixes the barndoors on scene lights created in MtoA 1.0 to match the new behaviour of barndoors in MtoA 1.1 """ for light in pm.ls(type='spotLight'): # calculate scale cone_angle = light.getAttr('coneAngle') penumbra_angle = light.getAttr('penumbraAngle') if penumbra_angle < 0: light.setAttr( 'coneAngle', max(cone_angle + penumbra_angle, 0.1) ) else: light.setAttr( 'coneAngle', max(cone_angle - penumbra_angle, 0.1) ) @classmethod def convert_aiSkinSSS_to_aiSkin(cls): """converts aiSkinSSS nodes in the current scene to aiSkin + aiStandard nodes automatically """ attr_mapper = { # diffuse 'color': { 'node': 'aiStandard', 'attr_name': 'color' }, 'diffuseWeight': { 'node': 'aiStandard', 'attr_name': 'Kd', 'multiplier': 0.7 }, 'diffuseRoughness': { 'node': 'aiStandard', 'attr_name': 'diffuseRoughness' }, # sss 'sssWeight': { 'node': 'aiSkin', 'attr_name': 'sssWeight' }, # shallowScatter 'shallowScatterColor': { 'node': 'aiSkin', 'attr_name': 'shallowScatterColor', }, 'shallowScatterWeight': { 'node': 'aiSkin', 'attr_name': 'shallowScatterWeight' }, 'shallowScatterRadius': { 'node': 'aiSkin', 'attr_name': 'shallowScatterRadius' }, # midScatter 'midScatterColor': { 'node': 'aiSkin', 'attr_name': 'midScatterColor', }, 'midScatterWeight': { 'node': 'aiSkin', 'attr_name': 'midScatterWeight' }, 'midScatterRadius': { 'node': 'aiSkin', 'attr_name': 'midScatterRadius' }, # deepScatter 'deepScatterColor': { 'node': 'aiSkin', 'attr_name': 'deepScatterColor', }, 'deepScatterWeight': { 'node': 'aiSkin', 'attr_name': 'deepScatterWeight' }, 'deepScatterRadius': { 'node': 'aiSkin', 'attr_name': 'deepScatterRadius' }, # primaryReflection 'primaryReflectionColor': { 'node': 'aiSkin', 'attr_name': 'specularColor' }, 'primaryReflectionWeight': { 'node': 'aiSkin', 'attr_name': 'specularWeight' }, 'primaryReflectionRoughness': { 'node': 'aiSkin', 'attr_name': 'specularRoughness' }, # secondaryReflection 'secondaryReflectionColor': { 'node': 'aiSkin', 'attr_name': 'sheenColor' }, 'secondaryReflectionWeight': { 'node': 'aiSkin', 'attr_name': 'sheenWeight' }, 'secondaryReflectionRoughness': { 'node': 'aiSkin', 'attr_name': 'sheenRoughness' }, # bump 'normalCamera': { 'node': 'aiSkin', 'attr_name': 'normalCamera' }, # sss multiplier 'globalSssRadiusMultiplier': { 'node': 'aiSkin', 'attr_name': 'globalSssRadiusMultiplier' }, } all_skin_sss = pm.ls(type='aiSkinSss') for skin_sss in all_skin_sss: skin = pm.shadingNode('aiSkin', asShader=1) standard = pm.shadingNode('aiStandard', asShader=1) skin.attr('outColor') >> standard.attr('emissionColor') standard.setAttr('emission', 1.0) skin.setAttr('fresnelAffectSss', 0) # to match the previous behaviour node_mapper = { 'aiSkin': skin, 'aiStandard': standard } for attr in attr_mapper.keys(): inputs = skin_sss.attr(attr).inputs(p=1, c=1) if inputs: # copy inputs destination_attr_name = inputs[0][0].name().split('.')[-1] source = inputs[0][1] if destination_attr_name in attr_mapper: node = attr_mapper[destination_attr_name]['node'] attr_name = attr_mapper[destination_attr_name][ 'attr_name'] source >> node_mapper[node].attr(attr_name) else: source >> skin.attr(destination_attr_name) else: # copy values node = node_mapper[attr_mapper[attr]['node']] attr_name = attr_mapper[attr]['attr_name'] multiplier = attr_mapper[attr].get('multiplier', 1.0) attr_value = skin_sss.getAttr(attr) if isinstance(attr_value, tuple): attr_value = map(lambda x: x * multiplier, attr_value) else: attr_value *= multiplier node.attr(attr_name).set(attr_value) # after everything is set up # connect the aiStandard to the shadingEngine for source, dest in skin_sss.outputs(p=1, c=1): standard.attr('outColor') >> dest # and rename the materials orig_name = skin_sss.name() # delete the skinSSS node pm.delete(skin_sss) skin_name = orig_name standard_name = '%s_aiStandard' % orig_name skin.rename(skin_name) standard.rename(standard_name) print('updated %s' % skin_name) @classmethod def normalize_sss_weights(cls): """normalizes the sss weights so their total weight is 1.0 if a aiStandard is assigned to the selected object it searches for an aiSkin in the emission channel. the script considers 0.7 as the highest diffuse value for aiStandard """ # get the shader of the selected object assigned_shader = pm.ls( pm.ls(sl=1)[0].getShape().outputs(type='shadingEngine')[0].inputs(), mat=1 )[0] if assigned_shader.type() == 'aiStandard': sss_shader = assigned_shader.attr('emissionColor').inputs()[0] diffuse_weight = assigned_shader.attr('Kd').get() else: sss_shader = assigned_shader diffuse_weight = 0 def get_attr_or_texture(attr): if attr.inputs(): # we probably have a texture assigned # so use its multiply attribute texture = attr.inputs()[0] attr = texture.attr('multiply') if isinstance(texture, pm.nt.AiImage): attr = texture.attr('multiply') elif isinstance(texture, pm.nt.File): attr = texture.attr('colorGain') return attr shallow_attr = get_attr_or_texture( sss_shader.attr('shallowScatterWeight') ) mid_attr = get_attr_or_texture(sss_shader.attr('midScatterWeight')) deep_attr = get_attr_or_texture(sss_shader.attr('deepScatterWeight')) shallow_weight = shallow_attr.get() if isinstance(shallow_weight, tuple): shallow_weight = ( shallow_weight[0] + shallow_weight[1] + shallow_weight[2] ) / 3.0 mid_weight = mid_attr.get() if isinstance(mid_weight, tuple): mid_weight = ( mid_weight[0] + mid_weight[1] + mid_weight[2] ) / 3.0 deep_weight = deep_attr.get() if isinstance(deep_weight, tuple): deep_weight = ( deep_weight[0] + deep_weight[1] + deep_weight[2] ) / 3.0 total_sss_weight = shallow_weight + mid_weight + deep_weight mult = (1 - diffuse_weight / 0.7) / total_sss_weight try: shallow_attr.set(shallow_weight * mult) except RuntimeError: w = shallow_weight * mult shallow_attr.set(w, w, w) try: mid_attr.set(mid_weight * mult) except RuntimeError: w = mid_weight * mult mid_attr.set(w, w, w) try: deep_attr.set(deep_weight * mult) except RuntimeError: w = deep_weight * mult deep_attr.set(w, w, w) @classmethod def create_eye_shader_and_controls(cls): """This is pretty much specific to the way we are creating eye shaders for characters in KKS project, but it is a useful trick, select the inner eye objects before running """ eyes = pm.ls(sl=1) if not eyes: return char = eyes[0].getAllParents()[-1] place = pm.shadingNode('place2dTexture', asUtility=1) emission_image = pm.shadingNode('aiImage', asTexture=1) ks_image = pm.shadingNode('aiImage', asTexture=1) texture_paths = { 'emission': '$REPO1977/KKS/Assets/Characters/Body_Parts/Textures/' 'char_eyeInner_light_v001.png', 'Ks': '$REPO1977/KKS/Assets/Characters/Body_Parts/Textures/' 'char_eyeInner_spec_v002.png', } emission_image.setAttr('filename', texture_paths['emission']) ks_image.setAttr('filename', texture_paths['Ks']) place.outUV >> emission_image.attr('uvcoords') if not char.hasAttr('eyeLightStrength'): char.addAttr('eyeLightStrength', at='double', min=0, dv=0.0, k=1) else: # set the default char.attr('eyeLightStrength').set(0) if not char.hasAttr('eyeLightAngle'): char.addAttr("eyeLightAngle", at='double', dv=0, k=1) if not char.hasAttr('eyeDiffuseWeight'): char.addAttr( "eyeDiffuseWeight", at='double', dv=0.15, k=1, min=0, max=1 ) if not char.hasAttr('eyeSpecularWeight'): char.addAttr( 'eyeSpecularWeight', at='double', dv=1.0, k=1, min=0, max=1 ) if not char.hasAttr('eyeSSSWeight'): char.addAttr( 'eyeSSSWeight', at='double', dv=0.5, k=1, min=0, max=1 ) # connect eye light strength char.eyeLightStrength >> emission_image.attr('multiplyR') char.eyeLightStrength >> emission_image.attr('multiplyG') char.eyeLightStrength >> emission_image.attr('multiplyB') # connect eye light angle char.eyeLightAngle >> place.attr('rotateFrame') # connect specular weight char.eyeSpecularWeight >> ks_image.attr('multiplyR') char.eyeSpecularWeight >> ks_image.attr('multiplyG') char.eyeSpecularWeight >> ks_image.attr('multiplyB') for eye in eyes: shading_engine = eye.getShape().outputs(type='shadingEngine')[0] shader = pm.ls(shading_engine.inputs(), mat=1)[0] # connect the diffuse shader input to the emissionColor diffuse_texture = shader.attr('color').inputs(p=1, s=1)[0] diffuse_texture >> shader.attr('emissionColor') emission_image.outColorR >> shader.attr('emission') # also connect it to specular color diffuse_texture >> shader.attr('KsColor') # connect the Ks image to the specular weight ks_image.outColorR >> shader.attr('Ks') # also connect it to sss color diffuse_texture >> shader.attr('KsssColor') char.eyeDiffuseWeight >> shader.attr('Kd') char.eyeSSSWeight >> shader.attr('Ksss') # set some default values shader.attr('diffuseRoughness').set(0) shader.attr('Kb').set(0) shader.attr('directDiffuse').set(1) shader.attr('indirectDiffuse').set(1) shader.attr('specularRoughness').set(0.4) shader.attr('specularAnisotropy').set(0.5) shader.attr('specularRotation').set(0) shader.attr('specularFresnel').set(0) shader.attr('Kr').set(0) shader.attr('enableInternalReflections').set(0) shader.attr('Kt').set(0) shader.attr('transmittance').set([1, 1, 1]) shader.attr('opacity').set([1, 1, 1]) shader.attr('sssRadius').set([1, 1, 1]) pm.select(eyes) @classmethod def randomize_attr(cls, nodes, attr, min, max, pre=0.1): """Randomizes the given attributes of the given nodes :param list nodes: :param str attr: :param float, int min: :param float, int max: :return: """ import random import math rand = random.random floor = math.floor for node in nodes: r = rand() * float(max - min) + float(min) r = floor(r / pre) * pre node.setAttr(attr, r) @classmethod def randomize_light_color_temp(cls, min_field, max_field): """Randomizes the color temperature of selected lights :param min: :param max: :return: """ min = pm.floatField(min_field, q=1, v=1) max = pm.floatField(max_field, q=1, v=1) cls.randomize_attr( [node.getShape() for node in pm.ls(sl=1)], 'aiColorTemperature', min, max, 1 ) @classmethod def randomize_light_intensity(cls, min_field, max_field): """Randomizes the intensities of selected lights :param min: :param max: :return: """ min = pm.floatField(min_field, q=1, v=1) max = pm.floatField(max_field, q=1, v=1) cls.randomize_attr( [node.getShape() for node in pm.ls(sl=1)], 'aiExposure', min, max, 0.1 ) @classmethod def setup_outer_eye_render_attributes(cls): """sets outer eye render attributes for characters, select outer eye objects and run this """ for node in pm.ls(sl=1): shape = node.getShape() shape.setAttr('castsShadows', 0) shape.setAttr('visibleInReflections', 0) shape.setAttr('visibleInRefractions', 0) shape.setAttr('aiSelfShadows', 0) shape.setAttr('aiOpaque', 0) shape.setAttr('aiVisibleInDiffuse', 0) shape.setAttr('aiVisibleInGlossy', 0) @classmethod def setup_window_glass_render_attributes(cls): """sets window glass render attributes for environments, select window glass objects and run this """ shader_name = 'toolbox_glass_shader' shaders = pm.ls('%s*' % shader_name) selection = pm.ls(sl=1) if len(shaders) > 0: shader = shaders[0] else: shader = pm.shadingNode( 'aiStandard', asShader=1, name='%s#' % shader_name ) shader.setAttr('Ks', 1) shader.setAttr('specularRoughness', 0) shader.setAttr('Kr', 0) shader.setAttr('enableInternalReflections', 0) shader.setAttr('Kt', 0) shader.setAttr('KtColor', (0, 0, 0)) shape_attributes = [ ('castsShadows', 0), ('visibleInReflections', 0), ('visibleInRefractions', 0), ('aiSelfShadows', 0), ('aiOpaque', 1), ('aiVisibleInDiffuse', 0), ('aiVisibleInGlossy', 0), ] for node in selection: shape = node.getShape() map(lambda x: shape.setAttr(*x), shape_attributes) if isinstance(shape, pm.nt.AiStandIn): # get the glass shader or create one shape.overrideShaders.set(1) # assign it to the stand in pm.select(node) pm.hyperShade(assign=shader) @classmethod def dummy_window_light_plane(cls): """creates or updates the dummy window plane for the given area light """ area_light_list = pm.selected() from anima.env.mayaEnv import auxiliary reload(auxiliary) for light in area_light_list: dwl = auxiliary.DummyWindowLight() dwl.light = light dwl.update() @classmethod def setup_z_limiter(cls): """creates z limiter setup """ shader_name = 'z_limiter_shader#' shaders = pm.ls('%s*' * shader_name) if len(shaders) > 0: shader = shaders[0] else: shader = pm.shadingNode( 'surfaceShader', asShader=1, name='%s#' % shader_name ) @classmethod def convert_file_node_to_ai_image_node(cls): """converts the file node to aiImage node """ default_values = { 'coverageU': 1, 'coverageV': 1, 'translateFrameU': 0, 'translateFrameV': 0, 'rotateFrame': 0, 'repeatU': 1, 'repeatV': 1, 'offsetU': 0, 'offsetV': 0, 'rotateUV': 0, 'noiseU': 0, 'noiseV': 0 } for node in pm.ls(sl=1, type='file'): node_name = node.name() path = node.getAttr('fileTextureName') ai_image = pm.shadingNode('aiImage', asTexture=1) ai_image.setAttr('filename', path) # check the placement node placements = node.listHistory(type='place2dTexture') if len(placements): placement = placements[0] # check default values if any([placement.getAttr(attr_name) != default_values[attr_name] for attr_name in default_values]): # connect the placement to the aiImage placement.outUV >> ai_image.uvcoords else: # delete it pm.delete(placement) # connect the aiImage for attr_out, attr_in in node.outputs(p=1, c=1): attr_name = attr_out.name().split('.')[-1] if attr_name == 'message': continue ai_image.attr(attr_name) >> attr_in # delete the File node pm.delete(node) # rename the aiImage node ai_image.rename(node_name) @classmethod def create_generic_tooth_shader(cls): """creates generic tooth shader for selected objects """ shader_name = 'toolbox_generic_tooth_shader#' selection = pm.ls(sl=1) shader_tree = { 'type': 'aiStandard', 'class': 'asShader', 'attr': { 'color': [1, 0.909, 0.815], 'Kd': 0.2, 'KsColor': [1, 1, 1], 'Ks': 0.5, 'specularRoughness': 0.10, 'specularFresnel': 1, 'Ksn': 0.05, 'enableInternalReflections': 0, 'KsssColor': [1, 1, 1], 'Ksss': 1, 'sssRadius': [1, 0.853, 0.68], 'normalCamera': { 'output': 'outNormal', 'type': 'bump2d', 'class': 'asTexture', 'attr': { 'bumpDepth': 0.05, 'bumpValue': { 'output': 'outValue', 'type': 'aiNoise', 'class': 'asUtility', 'attr': { 'scaleX': 4, 'scaleY': 0.250, 'scaleZ': 4, } } } } } } shader = auxiliary.create_shader(shader_tree, shader_name) for node in selection: # assign it to the stand in pm.select(node) pm.hyperShade(assign=shader) @classmethod def create_generic_gum_shader(self): """set ups generic gum shader for selected objects """ shader_name = 'toolbox_generic_gum_shader#' selection = pm.ls(sl=1) shader_tree = { 'type': 'aiStandard', 'class': 'asShader', 'attr': { 'color': [0.993, 0.596, 0.612], 'Kd': 0.35, 'KsColor': [1, 1, 1], 'Ks': 0.010, 'specularRoughness': 0.2, 'enableInternalReflections': 0, 'KsssColor': [1, 0.6, 0.6], 'Ksss': 0.5, 'sssRadius': [0.5, 0.5, 0.5], 'normalCamera': { 'output': 'outNormal', 'type': 'bump2d', 'class': 'asTexture', 'attr': { 'bumpDepth': 0.1, 'bumpValue': { 'output': 'outValue', 'type': 'aiNoise', 'class': 'asUtility', 'attr': { 'scaleX': 4, 'scaleY': 1, 'scaleZ': 4, } } } } } } shader = auxiliary.create_shader(shader_tree, shader_name) for node in selection: # assign it to the stand in pm.select(node) pm.hyperShade(assign=shader) @classmethod def create_generic_tongue_shader(self): """set ups generic tongue shader for selected objects """ shader_name = 'toolbox_generic_tongue_shader#' selection = pm.ls(sl=1) shader_tree = { 'type': 'aiStandard', 'class': 'asShader', 'attr': { 'color': [0.675, 0.174, 0.194], 'Kd': 0.35, 'KsColor': [1, 1, 1], 'Ks': 0.010, 'specularRoughness': 0.2, 'enableInternalReflections': 0, 'KsssColor': [1, 0.3, 0.3], 'Ksss': 0.5, 'sssRadius': [0.5, 0.5, 0.5], 'normalCamera': { 'output': 'outNormal', 'type': 'bump2d', 'class': 'asTexture', 'attr': { 'bumpDepth': 0.1, 'bumpValue': { 'output': 'outValue', 'type': 'aiNoise', 'class': 'asUtility', 'attr': { 'scaleX': 4, 'scaleY': 1, 'scaleZ': 4, } } } } } } shader = auxiliary.create_shader(shader_tree, shader_name) for node in selection: # assign it to the stand in pm.select(node) pm.hyperShade(assign=shader) @classmethod def create_ea_matte(cls): """creates "ebesinin ami" matte shader with opacity for selected objects. It is called "EA Matte" for one reason, this matte is not necessary in normal working conditions. That is you change the color and look of some 3D element in 3D application and do an artistic grading at post to the whole plate, not to individual elements in the render. And because we are forced to create this matte layer, we thought that we should give it a proper name. """ # get the selected objects # for each object create a new surface shader with the opacity # channel having the opacity of the original shader # create a lut for objects that have the same material not to cause # multiple materials to be created daro = pm.PyNode('defaultArnoldRenderOptions') attrs = { 'AASamples': 4, 'GIDiffuseSamples': 0, 'GIGlossySamples': 0, 'GIRefractionSamples': 0, 'sssBssrdfSamples': 0, 'volumeIndirectSamples': 0, 'GITotalDepth': 0, 'GIDiffuseDepth': 0, 'GIGlossyDepth': 0, 'GIReflectionDepth': 0, 'GIRefractionDepth': 0, 'GIVolumeDepth': 0, 'ignoreTextures': 1, 'ignoreAtmosphere': 1, 'ignoreLights': 1, 'ignoreShadows': 1, 'ignoreBump': 1, 'ignoreSss': 1, } for attr in attrs: pm.editRenderLayerAdjustment(daro.attr(attr)) daro.setAttr(attr, attrs[attr]) try: aov_z = pm.PyNode('aiAOV_Z') pm.editRenderLayerAdjustment(aov_z.attr('enabled')) aov_z.setAttr('enabled', 0) except pm.MayaNodeError: pass try: aov_mv = pm.PyNode('aiAOV_motionvector') pm.editRenderLayerAdjustment(aov_mv.attr('enabled')) aov_mv.setAttr('enabled', 0) except pm.MayaNodeError: pass dad = pm.PyNode('defaultArnoldDriver') pm.editRenderLayerAdjustment(dad.attr('autocrop')) dad.setAttr('autocrop', 0) @classmethod def create_z_layer(cls): """creates z layer with arnold render settings """ daro = pm.PyNode('defaultArnoldRenderOptions') attrs = { 'AASamples': 4, 'GIDiffuseSamples': 0, 'GIGlossySamples': 0, 'GIRefractionSamples': 0, 'sssBssrdfSamples': 0, 'volumeIndirectSamples': 0, 'GITotalDepth': 0, 'GIDiffuseDepth': 0, 'GIGlossyDepth': 0, 'GIReflectionDepth': 0, 'GIRefractionDepth': 0, 'GIVolumeDepth': 0, 'ignoreShaders': 1, 'ignoreAtmosphere': 1, 'ignoreLights': 1, 'ignoreShadows': 1, 'ignoreBump': 1, 'ignoreNormalSmoothing': 1, 'ignoreDof': 1, 'ignoreSss': 1, } for attr in attrs: pm.editRenderLayerAdjustment(daro.attr(attr)) daro.setAttr(attr, attrs[attr]) try: aov_z = pm.PyNode('aiAOV_Z') pm.editRenderLayerAdjustment(aov_z.attr('enabled')) aov_z.setAttr('enabled', 1) except pm.MayaNodeError: pass try: aov_mv = pm.PyNode('aiAOV_motionvector') pm.editRenderLayerAdjustment(aov_mv.attr('enabled')) aov_mv.setAttr('enabled', 1) except pm.MayaNodeError: pass dad = pm.PyNode('defaultArnoldDriver') pm.editRenderLayerAdjustment(dad.attr('autocrop')) dad.setAttr('autocrop', 1) @classmethod def generate_reflection_curve(self): """Generates a curve which helps creating specular at the desired point """ from maya.OpenMaya import MVector, MPoint from anima.env.mayaEnv import auxiliary vtx = pm.ls(sl=1)[0] normal = vtx.getNormal(space='world') panel = auxiliary.Playblaster.get_active_panel() camera = pm.PyNode(pm.modelPanel(panel, q=1, cam=1)) camera_axis = MVector(0, 0, -1) * camera.worldMatrix.get() refl = camera_axis - 2 * normal.dot(camera_axis) * normal # create a new curve p1 = vtx.getPosition(space='world') p2 = p1 + refl curve = pm.curve(d=1, p=[p1, p2]) # move pivot to the first point pm.xform(curve, rp=p1, sp=p1) @classmethod def import_gpu_content(self): """imports the selected GPU content """ import os imported_nodes = [] for node in pm.ls(sl=1): gpu_node = node.getShape() gpu_path = gpu_node.getAttr('cacheFileName') new_nodes = pm.mel.eval( 'AbcImport -mode import -reparent "%s" "%s";' % (node.fullPath(), os.path.expandvars(gpu_path)) ) # get imported nodes new_nodes = node.getChildren() new_nodes.remove(gpu_node) imported_node = None # filter material node for n in new_nodes: if n.name() != 'materials': imported_node = n else: pm.delete(n) if imported_node: imported_node.t.set(0, 0, 0) imported_node.r.set(0, 0, 0) imported_node.s.set(1, 1, 1) pm.parent(imported_node, world=1) imported_nodes.append(imported_node) pm.select(imported_nodes) @classmethod def render_slicer(self): """A tool for slicing big render scenes :return: """ from anima.env.mayaEnv import render_slicer rs_UI = render_slicer.UI() @classmethod def move_cache_files_wrapper(cls, source_driver_field, target_driver_field): """Wrapper for move_cache_files() command :param source_driver_field: Text field for source driver :param target_driver_field: Text field for target driver :return: """ source_driver = source_driver_field.text() target_driver = target_driver_field.text() Render.move_cache_files( source_driver, target_driver ) @classmethod def move_cache_files(cls, source_driver, target_driver): """moves the selected cache files to another location :param source_driver: :param target_driver: :return: """ # # Move fur caches to new server # import os import shutil import glob # from maya import OpenMayaUI # # try: # from shiboken import wrapInstance # except ImportError: # from shiboken2 import wrapInstance # # from anima.ui import progress_dialog # # maya_main_window = wrapInstance( # long(OpenMayaUI.MQtUtil.mainWindow()), # progress_dialog.QtWidgets.QWidget # ) # from anima.env.mayaEnv import MayaMainProgressBarWrapper wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) selected_nodes = pm.ls(sl=1) caller = pdm.register(len(selected_nodes), title='Moving Cache Files') for node in selected_nodes: ass_node = node.getShape() if not isinstance(ass_node, (pm.nt.AiStandIn, pm.nt.AiVolume)): continue if isinstance(ass_node, pm.nt.AiStandIn): ass_path = ass_node.dso.get() elif isinstance(ass_node, pm.nt.AiVolume): ass_path = ass_node.filename.get() ass_path = os.path.normpath( os.path.expandvars(ass_path) ) # give info to user caller.title = 'Moving: %s' % ass_path # check if it is in the source location if source_driver not in ass_path: continue # check if it contains .ass.gz in its path if isinstance(ass_node, pm.nt.AiStandIn): if '.ass.gz' not in ass_path: continue elif isinstance(ass_node, pm.nt.AiVolume): if '.vdb' not in ass_path: continue # get the dirname ass_source_dir = os.path.dirname(ass_path) ass_target_dir = ass_source_dir.replace(source_driver, target_driver) # create the intermediate folders at destination try: os.makedirs( ass_target_dir ) except OSError: # dir already exists pass # get all files list pattern = re.subn(r'[#]+', '*', ass_path)[0].replace('.ass.gz', '.ass*') all_cache_files = glob.glob(pattern) inner_caller = pdm.register(len(all_cache_files)) for source_f in all_cache_files: target_f = source_f.replace(source_driver, target_driver) # move files to new location shutil.move(source_f, target_f) inner_caller.step(message='Moving: %s' % source_f) inner_caller.end_progress() # finally update DSO path if isinstance(ass_node, pm.nt.AiStandIn): ass_node.dso.set(ass_path.replace(source_driver, target_driver)) elif isinstance(ass_node, pm.nt.AiVolume): ass_node.filename.set( ass_path.replace(source_driver, target_driver) ) caller.step() caller.end_progress() class Animation(object): """animation tools """ @classmethod def delete_base_anim_layer(cls): """deletes the base anim layer """ base_layer = pm.PyNode('BaseAnimation') base_layer.unlock() pm.delete(base_layer) @classmethod def oySmoothComponentAnimation(cls, ui_item): """calls the mel script oySmoothComponentAnimation """ # get the frame range frame_range = pm.textFieldButtonGrp( ui_item, q=1, tx=1 ) pm.mel.eval('oySmoothComponentAnimation(%s)' % frame_range) @classmethod def vertigo_setup_look_at(cls): """sets up a the necessary locator for teh Vertigo effect for the selected camera """ from anima.env.mayaEnv import vertigo cam = pm.ls(sl=1)[0] vertigo.setup_look_at(cam) @classmethod def vertigo_setup_vertigo(cls): """sets up a Vertigo effect for the selected camera """ from anima.env.mayaEnv import vertigo cam = pm.ls(sl=1)[0] vertigo.setup_vertigo(cam) @classmethod def vertigo_delete(cls): """deletes the Vertigo setup for the selected camera """ from anima.env.mayaEnv import vertigo cam = pm.ls(sl=1)[0] vertigo.delete(cam) @classmethod def cam_2_chan(cls, startButton, endButton): start = int(pm.textField(startButton, q=True, tx=True)) end = int(pm.textField(endButton, q=True, tx=True)) cam_to_chan(start, end) @classmethod def create_alembic_command(cls): """for ui """ from_top_node = pm.checkBox('from_top_node_checkBox', q=1, v=1) cls.create_alembic(from_top_node) @classmethod def create_alembic(cls, from_top_node=1): """creates alembic cache from selected nodes """ import os root_flag = '-root %(node)s' mel_command = 'AbcExport -j "-frameRange %(start)s %(end)s -ro ' \ '-stripNamespaces -uvWrite -wholeFrameGeo -worldSpace ' \ '%(roots)s ' \ '-file %(path)s";' current_path = pm.workspace.path abc_path = os.path.join(current_path, 'cache', 'alembic') try: os.makedirs(abc_path) except OSError: pass abc_full_path = pm.fileDialog2(startingDirectory=abc_path) def find_top_parent(node): parents = node.listRelatives(p=1) parent = None while parents: parent = parents[0] parents = parent.listRelatives(p=1) if parents: parent = parents[0] else: return parent if not parent: return node else: return parent if abc_full_path: abc_full_path = abc_full_path[0] # this is dirty abc_full_path = os.path.splitext(abc_full_path)[0] + '.abc' # get nodes selection = pm.ls(sl=1) nodes = [] for node in selection: if from_top_node: node = find_top_parent(node) if node not in nodes: nodes.append(node) # generate root flags roots = [] for node in nodes: roots.append( root_flag % { 'node': node.fullPath() } ) roots_as_string = ' '.join(roots) start = int(pm.playbackOptions(q=1, minTime=1)) end = int(pm.playbackOptions(q=1, maxTime=1)) rendered_mel_command = mel_command % { 'start': start, 'end': end, 'roots': roots_as_string, 'path': abc_full_path } pm.mel.eval(rendered_mel_command) @classmethod def copy_alembic_data(cls, source=None, target=None): """Copies alembic data from source to target hierarchy """ selection = pm.ls(sl=1) if not source or not target: source = selection[0] target = selection[1] # # Move Alembic Data From Source To Target # #selection = pm.ls(sl=1) # #source = selection[0] #target = selection[1] source_nodes = source.listRelatives( ad=1, type=(pm.nt.Mesh, pm.nt.NurbsSurface) ) target_nodes = target.listRelatives( ad=1, type=(pm.nt.Mesh, pm.nt.NurbsSurface) ) source_node_names = [] target_node_names = [] for node in source_nodes: name = node.name().split(':')[-1].split('|')[-1] source_node_names.append(name) for node in target_nodes: name = node.name().split(':')[-1].split('|')[-1] target_node_names.append(name) lut = [] for i, target_node in enumerate(target_nodes): target_node_name = target_node_names[i] try: index = source_node_names.index(target_node_name) except ValueError: pass else: lut.append((source_nodes[index], target_nodes[i])) for source_node, target_node in lut: if isinstance(source_node, pm.nt.Mesh): in_attr_name = 'inMesh' out_attr_name = 'outMesh' else: in_attr_name = 'create' out_attr_name = 'worldSpace' conns = source_node.attr(in_attr_name).inputs(p=1) if conns: for conn in conns: if isinstance(conn.node(), pm.nt.AlembicNode): conn >> target_node.attr(in_attr_name) break else: # no connection # just connect the shape itself source_node.attr(out_attr_name) >> \ target_node.attr(in_attr_name) @classmethod def bake_component_animation(cls): """bakes the selected component animation to a space locator """ start = int(pm.playbackOptions(q=1, minTime=1)) end = int(pm.playbackOptions(q=1, maxTime=1)) vertices = pm.ls(sl=1, fl=1) locator = pm.spaceLocator() for i in range(start, end+1): pm.currentTime(i) point_positions = pm.xform(vertices, q=1, ws=1, t=1) point_count = len(point_positions) / 3 px = reduce(lambda x, y: x+y, point_positions[0::3]) / point_count py = reduce(lambda x, y: x+y, point_positions[1::3]) / point_count pz = reduce(lambda x, y: x+y, point_positions[2::3]) / point_count locator.t.set(px, py, pz) pm.setKeyframe(locator.tx) pm.setKeyframe(locator.ty) pm.setKeyframe(locator.tz) @classmethod def attach_follicle(cls): """attaches a follicle on selected mesh vertices """ pnts = pm.ls(sl=1) for pnt in pnts: mesh = pnt.node() follicle = pm.createNode('follicle') mesh.worldMesh[0] >> follicle.inputMesh uv = pnts[0].getUV() follicle.parameterU.set(uv[0]) follicle.parameterV.set(uv[1]) follicle_t = follicle.getParent() follicle.outTranslate >> follicle_t.t follicle.outRotate >> follicle_t.r @classmethod def set_range_from_shot(cls): """sets the playback range from a shot node in the scene """ shots = pm.ls(type='shot') min_frame = None max_frame = None if shots: # use the available shot node shot = shots[0] min_frame = shot.getAttr('startFrame') max_frame = shot.getAttr('endFrame') else: # check if this is a shot related scene from anima.env import mayaEnv m = mayaEnv.Maya() v = m.get_current_version() if v: t = v.task from stalker import Shot parents = t.parents parents.reverse() for p in parents: if isinstance(p, Shot): pm.warning( 'No shot node in the scene, ' 'using the Shot task!!!' ) min_frame = p.cut_in max_frame = p.cut_out break if min_frame is not None and max_frame is not None: pm.playbackOptions( ast=min_frame, aet=max_frame, min=min_frame, max=max_frame ) else: pm.error( 'No shot node in the scene, nor the task is related to a Shot!' ) def fur_map_unlocker(furD, lock=False): """unlocks all the fur map attributes for the given furDescription node """ fur_attrs = [ "BaseColorMap", "TipColorMap", "BaseAmbientColorMap", "TipAmbientColorMap", "SpecularColorMap", "SpecularSharpnessMap", "LengthMap", "BaldnessMap", "InclinationMap", "RollMap", "PolarMap", "BaseOpacityMap", "TipOpacityMap", "BaseWidthMap", "TipWidthMap", "BaseCurlMap", "TipCurlMap", "ScraggleMap", "ScraggleFrequencyMap", "ScraggleCorrelationMap", "ClumpingMap", "ClumpingFrequencyMap", "ClumpShapeMap", "SegmentsMap", "AttractionMap", "OffsetMap", "CustomEqualizerMap", ] # set lock state for attr in fur_attrs: try: print "setting lock: %s for %s.%s" % (lock, furD.name(), attr) furD.attr(attr).setLocked(lock) except pm.MayaAttributeError as e: print e print "%s attribute is not mapped" % attr pass
sergeneren/anima
anima/env/mayaEnv/toolbox.py
Python
bsd-2-clause
180,988
[ "VisIt" ]
ad1c1de23c313976e7ae8afb59eb8c112079903e511de78118879eed2eb95371
# convert_Genesis2Sbml.py --- # # Filename: convert_Genesis2Sbml.py # Description: # Author:Harsha Rani # Maintainer: # Created: Mon Jan 19 09:16:58 2015 (+0530) # Version: # Last-Updated: Mon Nov 7 15:155:38 2012 (+0530) # By: Harsha Rani # Update #: # URL: # Keywords: # Compatibility: # # # Commentary: # # The script demonstates to convert Chemical (Genesis) file to SBML file using moose # # # Change log: # # # # # 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 3, 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; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth # Floor, Boston, MA 02110-1301, USA. # # # Code: import moose def main(): """This example illustrates loading a kinetic model defined in Genesis format into Moose using loadModel function and using writeSBML function one can save the model into SBML format. \n **libsbml should be installed.** """ #This command loads the file into the path '/Kholodenko' moose.loadModel('../genesis/Kholodenko.g','/Kholodenko') #Writes model to xml file written = moose.writeSBML('/Kholodenko','../genesis/Kholodenko_tosbml.xml') print(written) if __name__ == '__main__': main()
BhallaLab/moose-examples
snippets/convert_Genesis2Sbml.py
Python
gpl-2.0
1,729
[ "MOOSE" ]
0e52447d27afd50cc0e34a6742ea7d49bf590009608cb50c83d4a4e0497a6a8f
from datetime import timedelta from django.conf import settings from django.db.models import Q from django.utils.timezone import now from user_sessions.models import Session from .models import PrivateMessage def inbox_messages(request): inbox_unread_count = 0 if request.user.is_authenticated: # get all messages to/from this user inbox_unread_count = PrivateMessage.objects \ .filter(Q(author=request.user) | Q(recipient=request.user)) # inbox visit time can be empty if request.user.inbox_visit_time: inbox_unread_count = inbox_unread_count \ .filter(created__gte=request.user.inbox_visit_time) # get count inbox_unread_count = inbox_unread_count.count() return { 'inbox_unread_count': inbox_unread_count } def active_users(request): active_threshold = now() - timedelta(minutes=settings.ACTIVE_USERS_TIMEOUT) active_users_count = Session.objects\ .filter(user__isnull=False, expire_date__gte=now(), last_activity__gte=active_threshold)\ .distinct('user__username')\ .count() return { 'active_users_count': active_users_count }
sairon/score-phorum
src/phorum/context_processors.py
Python
bsd-3-clause
1,201
[ "VisIt" ]
a7aa0187d0a110dccc501894f04ffff7abeeb70b9c1981f0a7b1be81b4dcefb1
# coding: utf-8 #!/usr/bin/env python """ Script to plot density of states (DOS) generated by an FEFF run either by site, element, or orbital """ from __future__ import division __author__ = "Alan Dozier" __credits__= "Anubhav Jain, Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "1.0" __maintainer__ = "Alan Dozier" __email__ = "adozier@uky.edu" __date__ = "April 7, 2012" import argparse from collections import OrderedDict from pymatgen.io.feffio import FeffLdos from pymatgen.electronic_structure.plotter import DosPlotter parser = argparse.ArgumentParser(description='''Convenient DOS Plotter for Feff runs. Author: Alan Dozier Version: 1.0 Last updated: April, 2013''') parser.add_argument('filename', metavar='filename', type=str, nargs=1, help='ldos%% file set to plot') parser.add_argument('filename1', metavar='filename1', type=str, nargs=1, help='feff.inp input file ') parser.add_argument('-s', '--site', dest='site', action='store_const', const=True, help='plot site projected DOS') parser.add_argument('-e', '--element', dest='element', action='store_const', const=True, help='plot element projected DOS') parser.add_argument('-o', '--orbital', dest="orbital", action='store_const', const=True, help='plot orbital projected DOS') args = parser.parse_args() f = FeffLdos.from_file(args.filename1[0], args.filename[0]) dos = f.complete_dos all_dos = OrderedDict() all_dos['Total'] = dos structure = f.complete_dos.structure if args.site: for i in xrange(len(structure)): site = structure[i] all_dos['Site ' + str(i) + " " + site.specie.symbol] = \ dos.get_site_dos(site) if args.element: all_dos.update(dos.get_element_dos()) if args.orbital: all_dos.update(dos.get_spd_dos()) plotter = DosPlotter() plotter.add_dos_dict(all_dos) plotter.show()
ctoher/pymatgen
scripts/feff_plot_dos.py
Python
mit
1,948
[ "FEFF", "pymatgen" ]
be2b5658108eb30849f74c66a2240d53724523127a0d3a6c411d365d4a03f354
import os import numpy as np from nose import tools as nt from neurom.core.types import NeuriteType import neurom.view._dendrogram as dm from neurom import load_neuron, get _PWD = os.path.dirname(os.path.abspath(__file__)) DATA_PATH = os.path.join(_PWD, '../../../test_data/h5/v1/Neuron.h5') NEURON = load_neuron(DATA_PATH) NEURITE = NEURON.neurites[0] TREE = NEURITE.root_node OLD_OFFS = [1.2, -1.2] NEW_OFFS = [2.3, -2.3] SPACING = (40., 0.) def test_n_rectangles_tree(): nt.assert_equal(dm._n_rectangles(NEURITE), 230) def test_n_rectangles_neuron(): nt.assert_equal(dm._n_rectangles(NEURON), 920) def test_vertical_segment(): radii = [10., 20.] res = np.array([[ -7.7, -1.2], [-17.7, -2.3], [ 22.3, -2.3], [ 12.3, -1.2]]) seg = dm._vertical_segment(OLD_OFFS, NEW_OFFS, SPACING, radii) nt.assert_true(np.allclose(seg, res)) def test_horizontal_segment(): diameter = 10. res = np.array([[ 1.2, -1.2], [ 2.3, -1.2], [ 2.3, -11.2], [ 1.2, -11.2]]) seg = dm._horizontal_segment(OLD_OFFS, NEW_OFFS, SPACING, diameter) nt.assert_true(np.allclose(seg, res)) def test_spacingx(): xoffset = 100. xspace = 40. max_dims = [10., 2.] spx = dm._spacingx(TREE, max_dims, xoffset, xspace) nt.assert_almost_equal(spx, -120.) nt.assert_almost_equal(max_dims[0], 440.) def test_update_offsets(): start_x = -10. length = 44. offs = dm._update_offsets(start_x, SPACING, 2, OLD_OFFS, length) nt.assert_almost_equal(offs[0], 30.) nt.assert_almost_equal(offs[1], 42.8) class TestDendrogram(object): def setUp(self): self.dtr = dm.Dendrogram(NEURITE) self.dnrn = dm.Dendrogram(NEURON) self.dtr.generate() self.dnrn.generate() def test_init(self): nt.assert_true(np.allclose(self.dnrn._rectangles.shape, (920, 4, 2))) def test_generate_tree(self): nt.assert_true(np.allclose(self.dtr._rectangles.shape, (230, 4, 2))) nt.assert_false(np.all(self.dtr._rectangles == 0.)) def test_generate_soma(self): vrec = self.dnrn.soma trec = np.array([[-0.17071068, -0.34142136], [-0.17071068, 0. ], [ 0.17071068, 0. ], [ 0.17071068, -0.34142136]]) nt.assert_true(np.allclose(vrec, trec)) vrec = self.dtr.soma nt.assert_true(vrec == None) def test_neuron_not_corrupted(self): # Regression for #492: dendrogram was corrupting # neuron used to construct it. # This caused the section path distance calculation # to raise a KeyError exception. get('section_path_distances', NEURON) def test_generate_neuron(self): total = 0 for n0, n1 in self.dnrn._groups: group = self.dnrn._rectangles[n0: n1] total += group.shape[0] nt.assert_false(np.all(group == 0.)) nt.assert_equal(total, 920) def test_data(self): nt.assert_false(np.all(self.dnrn.data == 0.)) nt.assert_false(np.all(self.dtr.data == 0.)) def test_groups(self): nt.ok_(self.dnrn.groups) nt.ok_(self.dtr.groups) def test_dims(self): nt.ok_(self.dnrn.dims) nt.ok_(self.dtr.dims) def test_types_tree(self): for ctype in self.dtr.types: nt.eq_(ctype, NeuriteType.apical_dendrite) def test_types_neuron(self): types = tuple(self.dnrn.types) nt.eq_(types[0], NeuriteType.apical_dendrite) nt.eq_(types[1], NeuriteType.basal_dendrite)
liesbethvanherpe/NeuroM
neurom/view/tests/test_dendrogram.py
Python
bsd-3-clause
3,738
[ "NEURON" ]
47bc3dc33cbd3e9d4365fbc9487bd703e8ec6f7cd42affb0fbae718236256b19
# 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. ''' Test feature reader and Tica by checking the properties of the ICs. cov(ic_i,ic_j) = delta_ij and cov(ic_i,ic_j,tau) = lambda_i delta_ij @author: Fabian Paul ''' import unittest import os import tempfile import numpy as np import mdtraj from pyemma.coordinates.api import tica, _TICA as TICA from pyemma.coordinates.data.feature_reader import FeatureReader from pyemma.util.log import getLogger log = getLogger('TestFeatureReaderAndTICAProjection') def random_invertible(n, eps=0.01): 'generate real random invertible matrix' m = np.random.randn(n, n) u, s, v = np.linalg.svd(m) s = np.maximum(s, eps) return u.dot(np.diag(s)).dot(v) from nose.plugins.attrib import attr @attr(slow=True) class TestFeatureReaderAndTICAProjection(unittest.TestCase): @classmethod def setUpClass(cls): c = super(TestFeatureReaderAndTICAProjection, cls).setUpClass() cls.dim = 99 # dimension (must be divisible by 3) N = 5000 # length of single trajectory # 500000 N_trajs = 10 # number of trajectories A = random_invertible(cls.dim) # mixing matrix # tica will approximate its inverse with the projection matrix mean = np.random.randn(cls.dim) # create topology file cls.temppdb = tempfile.mktemp('.pdb') with open(cls.temppdb, 'w') as f: for i in xrange(cls.dim // 3): print>>f, ('ATOM %5d C ACE A 1 28.490 31.600 33.379 0.00 1.00' % i) t = np.arange(0, N) cls.trajnames = [] # list of xtc file names for i in xrange(N_trajs): # set up data white = np.random.randn(N, cls.dim) brown = np.cumsum(white, axis=0) correlated = np.dot(brown, A) data = correlated + mean xyz = data.reshape((N, cls.dim // 3, 3)) # create trajectory file traj = mdtraj.load(cls.temppdb) traj.xyz = xyz traj.time = t tempfname = tempfile.mktemp('.xtc') traj.save(tempfname) cls.trajnames.append(tempfname) @classmethod def tearDownClass(cls): for fname in cls.trajnames: os.unlink(fname) os.unlink(cls.temppdb) super(TestFeatureReaderAndTICAProjection, cls).tearDownClass() def test_covariances_and_eigenvalues(self): reader = FeatureReader(self.trajnames, self.temppdb) for tau in [1, 10, 100, 1000, 2000]: trans = TICA(lag=tau, dim=self.dim, force_eigenvalues_le_one=True) trans.data_producer = reader log.info('number of trajectories reported by tica %d' % trans.number_of_trajectories()) trans.parametrize() data = trans.get_output() # print '@@cov', trans.cov # print '@@cov_tau', trans.cov_tau log.info('max. eigenvalue: %f' % np.max(trans.eigenvalues)) self.assertTrue(np.all(trans.eigenvalues <= 1.0)) # check ICs check = tica(data=data, lag=tau, dim=self.dim, force_eigenvalues_le_one=True) check.parametrize() self.assertTrue(np.allclose(np.eye(self.dim), check.cov)) self.assertTrue(np.allclose(check.mu, 0.0)) ic_cov_tau = np.zeros((self.dim, self.dim)) ic_cov_tau[np.diag_indices(self.dim)] = trans.eigenvalues self.assertTrue(np.allclose(ic_cov_tau, check.cov_tau)) # print '@@cov_tau', check.cov_tau if __name__ == "__main__": unittest.main()
arokem/PyEMMA
pyemma/coordinates/tests/test_featurereader_and_tica_projection.py
Python
bsd-2-clause
4,977
[ "MDTraj" ]
36f8d780fc36962019ee6c271e9b863dc0c76a27ba159f923eeb2eb1cf10834c
import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d from theano.tensor.shared_randomstreams import RandomStreams import numpy as np from toolbox import * from modelbase import * import itertools class FFN_bn(ModelSLBase): """ Feedforward neural network with batch normalization and contractive cost """ def save(self): if not os.path.exists('savedmodels\\'): os.makedirs('savedmodels\\') self.params.save(self.filename) self.shared_vars.save(self.filename + '_vars') def __init__(self, data, hp): super(FFN_bn, self).__init__(self.__class__.__name__, data, hp) self.params = Parameters() self.shared_vars = Parameters() n_h1 = 1200 n_h2 = 1000 n_h3 = 800 n_h4 = 800 if hp.load_model and os.path.isfile(self.filename): self.params.load(self.filename) self.shared_vars.load(self.filename + '_vars') else: with self.params: w_h = shared_normal((self.data['n_x'], n_h1), scale=hp.init_scale) b_h = shared_zeros((n_h1,)) w_h2 = shared_normal((n_h1, n_h2), scale=hp.init_scale) b_h2 = shared_zeros((n_h2,)) w_h3 = shared_normal((n_h2, n_h3), scale=hp.init_scale) b_h3 = shared_zeros((n_h3,)) w_h4 = shared_normal((n_h3, n_h4), scale=hp.init_scale) b_h4 = shared_zeros((n_h4,)) w_o = shared_normal((n_h4, self.data['n_y']), scale=hp.init_scale) with self.shared_vars: m_shared = shared_zeros((1, n_h1), broadcastable=(True, False)) v_shared = shared_zeros((1, n_h1), broadcastable=(True, False)) m_shared2 = shared_zeros((1, n_h2), broadcastable=(True, False)) v_shared2 = shared_zeros((1, n_h2), broadcastable=(True, False)) m_shared3 = shared_zeros((1, n_h3), broadcastable=(True, False)) v_shared3 = shared_zeros((1, n_h3), broadcastable=(True, False)) m_shared4 = shared_zeros((1, n_h4), broadcastable=(True, False)) v_shared4 = shared_zeros((1, n_h4), broadcastable=(True, False)) def batch_norm(X, m_shared, v_shared, test, add_updates, epsilon = 0.0001): if X.ndim > 2: output_shape = X.shape X = X.flatten(2) if test is False: m = T.mean(X, axis=0, keepdims=True) v = T.sqrt(T.var(X, axis=0, keepdims=True) + epsilon) mulfac = 1.0/100.0 add_updates.append((m_shared, (1.0-mulfac)*m_shared + mulfac*m)) add_updates.append((v_shared, (1.0-mulfac)*v_shared + mulfac*v)) else: m = m_shared v = v_shared X_hat = (X - m) / v if X.ndim > 2: X_hat = T.reshape(X_hat, output_shape) return X_hat def model(X, params, sv, p_drop_hidden, test, add_updates): h = batch_norm(T.dot(X, params.w_h), sv.m_shared, sv.v_shared, test, add_updates) + params.b_h h = dropout(rectify(h), p_drop_hidden) h2 = batch_norm(T.dot(h, params.w_h2), sv.m_shared2, sv.v_shared2, test, add_updates) + params.b_h2 h2 = dropout(rectify(h2), p_drop_hidden) h3 = batch_norm(T.dot(h2, params.w_h3), sv.m_shared3, sv.v_shared3, test, add_updates) + params.b_h3 h3 = dropout(rectify(h3), p_drop_hidden) h4 = batch_norm(T.dot(h3, params.w_h4), sv.m_shared4, sv.v_shared4, test, add_updates) + params.b_h4 h4 = dropout(rectify(h4), p_drop_hidden) py_x = softmax(T.dot(h4, params.w_o)) return py_x add_updates = [] input_noise = 5.0 noise_X = self.X + input_noise*normalize(gaussian(self.X.shape, 1.0)) noise_py_x = model(noise_X, self.params, self.shared_vars, 0.5, False, add_updates) cost_y2 = -T.sum(self.Y * T.log(noise_py_x)) #clean_py_x = model(self.X, self.params, self.shared_vars, 0.0, 0.5, True, None) #cost_y = T.sum(T.nnet.categorical_crossentropy(clean_py_x, self.Y)) #cost_x = T.sum(T.grad(cost=cost_y2, wrt=self.X)**2) #cost_x2 = T.sum((T.grad(cost=cost_y, wrt=self.X)-T.grad(cost=cost_y2, wrt=self.X))**2) cost = cost_y2 #+ 0.2*cost_x + 0.1*cost_x2 pyx = model(self.X, self.params, self.shared_vars, 0., True, None) map_pyx = T.argmax(pyx, axis=1) error_map_pyx = T.sum(T.neq(map_pyx, T.argmax(self.Y, axis=1))) self.compile(cost, error_map_pyx, add_updates)
codeaudit/Theano-Lights
models/ffn_bn.py
Python
mit
4,888
[ "Gaussian" ]
0b9bf76e94ac08e882a2d6d75c9260a67aecaf161c7d15a3986e70d796ee5bc2
# -*- coding: utf-8 -*- # # helpers.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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. # # NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. """ pynest microcircuit helpers --------------------------- Helper functions for the simulation and evaluation of the microcircuit. Hendrik Rothe, Hannah Bos, Sacha van Albada; May 2016 """ import numpy as np import os import sys if 'DISPLAY' not in os.environ: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Polygon def compute_DC(net_dict, w_ext): """ Computes DC input if no Poisson input is provided to the microcircuit. Parameters ---------- net_dict Parameters of the microcircuit. w_ext Weight of external connections. Returns ------- DC DC input, which compensates lacking Poisson input. """ DC = ( net_dict['bg_rate'] * net_dict['K_ext'] * w_ext * net_dict['neuron_params']['tau_syn_E'] * 0.001 ) return DC def get_weight(PSP_val, net_dict): """ Computes weight to elicit a change in the membrane potential. This function computes the weight which elicits a change in the membrane potential of size PSP_val. To implement this, the weight is calculated to elicit a current that is high enough to implement the desired change in the membrane potential. Parameters ---------- PSP_val Evoked postsynaptic potential. net_dict Dictionary containing parameters of the microcircuit. Returns ------- PSC_e Weight value(s). """ C_m = net_dict['neuron_params']['C_m'] tau_m = net_dict['neuron_params']['tau_m'] tau_syn_ex = net_dict['neuron_params']['tau_syn_ex'] PSC_e_over_PSP_e = (((C_m) ** (-1) * tau_m * tau_syn_ex / ( tau_syn_ex - tau_m) * ((tau_m / tau_syn_ex) ** ( - tau_m / (tau_m - tau_syn_ex)) - (tau_m / tau_syn_ex) ** ( - tau_syn_ex / (tau_m - tau_syn_ex)))) ** (-1)) PSC_e = (PSC_e_over_PSP_e * PSP_val) return PSC_e def get_total_number_of_synapses(net_dict): """ Returns the total number of synapses between all populations. The first index (rows) of the output matrix is the target population and the second (columns) the source population. If a scaling of the synapses is intended this is done in the main simulation script and the variable 'K_scaling' is ignored in this function. Parameters ---------- net_dict Dictionary containing parameters of the microcircuit. N_full Number of neurons in all populations. number_N Total number of populations. conn_probs Connection probabilities of the eight populations. scaling Factor that scales the number of neurons. Returns ------- K Total number of synapses with dimensions [len(populations), len(populations)]. """ N_full = net_dict['N_full'] number_N = len(N_full) conn_probs = net_dict['conn_probs'] scaling = net_dict['N_scaling'] prod = np.outer(N_full, N_full) n_syn_temp = np.log(1. - conn_probs)/np.log((prod - 1.) / prod) N_full_matrix = np.column_stack( (N_full for i in list(range(number_N))) ) # If the network is scaled the indegrees are calculated in the same # fashion as in the original version of the circuit, which is # written in sli. K = (((n_syn_temp * ( N_full_matrix * scaling).astype(int)) / N_full_matrix).astype(int)) return K def synapses_th_matrix(net_dict, stim_dict): """ Computes number of synapses between thalamus and microcircuit. This function ignores the variable, which scales the number of synapses. If this is intended the scaling is performed in the main simulation script. Parameters ---------- net_dict Dictionary containing parameters of the microcircuit. stim_dict Dictionary containing parameters of stimulation settings. N_full Number of neurons in the eight populations. number_N Total number of populations. conn_probs Connection probabilities of the thalamus to the eight populations. scaling Factor that scales the number of neurons. T_full Number of thalamic neurons. Returns ------- K Total number of synapses. """ N_full = net_dict['N_full'] number_N = len(N_full) scaling = net_dict['N_scaling'] conn_probs = stim_dict['conn_probs_th'] T_full = stim_dict['n_thal'] prod = (T_full * N_full).astype(float) n_syn_temp = np.log(1. - conn_probs)/np.log((prod - 1.)/prod) K = (((n_syn_temp * (N_full * scaling).astype(int))/N_full).astype(int)) return K def adj_w_ext_to_K(K_full, K_scaling, w, w_from_PSP, DC, net_dict, stim_dict): """ Adjustment of weights to scaling is performed. The recurrent and external weights are adjusted to the scaling of the indegrees. Extra DC input is added to compensate the scaling and preserve the mean and variance of the input. Parameters ---------- K_full Total number of connections between the eight populations. K_scaling Scaling factor for the connections. w Weight matrix of the connections of the eight populations. w_from_PSP Weight of the external connections. DC DC input to the eight populations. net_dict Dictionary containing parameters of the microcircuit. stim_dict Dictionary containing stimulation parameters. tau_syn_E Time constant of the external postsynaptic excitatory current. full_mean_rates Mean rates of the eight populations in the full scale version. K_ext Number of external connections to the eight populations. bg_rate Rate of the Poissonian spike generator. Returns ------- w_new Adjusted weight matrix. w_ext_new Adjusted external weight. I_ext Extra DC input. """ tau_syn_E = net_dict['neuron_params']['tau_syn_E'] full_mean_rates = net_dict['full_mean_rates'] w_mean = w_from_PSP K_ext = net_dict['K_ext'] bg_rate = net_dict['bg_rate'] w_new = w / np.sqrt(K_scaling) I_ext = np.zeros(len(net_dict['populations'])) x1_all = w * K_full * full_mean_rates x1_sum = np.sum(x1_all, axis=1) if net_dict['poisson_input']: x1_ext = w_mean * K_ext * bg_rate w_ext_new = w_mean / np.sqrt(K_scaling) I_ext = 0.001 * tau_syn_E * ( (1. - np.sqrt(K_scaling)) * x1_sum + ( 1. - np.sqrt(K_scaling)) * x1_ext) + DC else: w_ext_new = w_from_PSP / np.sqrt(K_scaling) I_ext = 0.001 * tau_syn_E * ( (1. - np.sqrt(K_scaling)) * x1_sum) + DC return w_new, w_ext_new, I_ext def read_name(path, name): """ Reads names and ids of spike detector. The names of the spike detectors are gathered and the lowest and highest id of each spike detector is computed. If the simulation was run on several threads or mpi-processes, one name per spike detector per mpi-process/thread is extracted. Parameters ------------ path Path where the spike detector files are stored. name Name of the spike detector. Returns ------- files Name of all spike detectors, which are located in the path. gids Lowest and highest ids of the spike detectors. """ # Import filenames$ files = [] for file in os.listdir(path): if file.endswith('.gdf') and file.startswith(name): temp = file.split('-')[0] + '-' + file.split('-')[1] if temp not in files: files.append(temp) # Import GIDs gidfile = open(path + 'population_GIDs.dat', 'r') gids = [] for l in gidfile: a = l.split() gids.append([int(a[0]), int(a[1])]) files = sorted(files) return files, gids def load_spike_times(path, name, begin, end): """ Loads spike times of each spike detector. Parameters ----------- path Path where the files with the spike times are stored. name Name of the spike detector. begin Lower boundary value to load spike times. end Upper boundary value to load spike times. Returns ------- data Dictionary containing spike times in the interval from 'begin' to 'end'. """ files, gids = read_name(path, name) data = {} for i in list(range(len(files))): all_names = os.listdir(path) temp3 = [ all_names[x] for x in list(range(len(all_names))) if all_names[x].endswith('gdf') and all_names[x].startswith('spike') and (all_names[x].split('-')[0] + '-' + all_names[x].split('-')[1]) in files[i] ] data_temp = [np.loadtxt(os.path.join(path, f)) for f in temp3] data_concatenated = np.concatenate(data_temp) data_raw = data_concatenated[np.argsort(data_concatenated[:, 1])] idx = ((data_raw[:, 1] > begin) * (data_raw[:, 1] < end)) data[i] = data_raw[idx] return data def plot_raster(path, name, begin, end): """ Creates a spike raster plot of the microcircuit. Parameters ----------- path Path where the spike times are stored. name Name of the spike detector. begin Initial value of spike times to plot. end Final value of spike times to plot. Returns ------- None """ files, gids = read_name(path, name) data_all = load_spike_times(path, name, begin, end) highest_gid = gids[-1][-1] gids_numpy = np.asarray(gids) gids_numpy_changed = abs(gids_numpy - highest_gid) + 1 L23_label_pos = (gids_numpy_changed[0][0] + gids_numpy_changed[1][1])/2 L4_label_pos = (gids_numpy_changed[2][0] + gids_numpy_changed[3][1])/2 L5_label_pos = (gids_numpy_changed[4][0] + gids_numpy_changed[5][1])/2 L6_label_pos = (gids_numpy_changed[6][0] + gids_numpy_changed[7][1])/2 ylabels = ['L23', 'L4', 'L5', 'L6'] color_list = [ '#000000', '#888888', '#000000', '#888888', '#000000', '#888888', '#000000', '#888888' ] Fig1 = plt.figure(1, figsize=(8, 6)) for i in list(range(len(files))): times = data_all[i][:, 1] neurons = np.abs(data_all[i][:, 0] - highest_gid) + 1 plt.plot(times, neurons, '.', color=color_list[i]) plt.xlabel('time [ms]', fontsize=18) plt.xticks(fontsize=18) plt.yticks( [L23_label_pos, L4_label_pos, L5_label_pos, L6_label_pos], ylabels, rotation=10, fontsize=18 ) plt.savefig(os.path.join(path, 'raster_plot.png'), dpi=300) plt.show() def fire_rate(path, name, begin, end): """ Computes firing rate and standard deviation of it. The firing rate of each neuron for each population is computed and stored in a numpy file in the directory of the spike detectors. The mean firing rate and its standard deviation is displayed for each population. Parameters ----------- path Path where the spike times are stored. name Name of the spike detector. begin Initial value of spike times to calculate the firing rate. end Final value of spike times to calculate the firing rate. Returns ------- None """ files, gids = read_name(path, name) data_all = load_spike_times(path, name, begin, end) rates_averaged_all = [] rates_std_all = [] for h in list(range(len(files))): n_fil = data_all[h][:, 0] n_fil = n_fil.astype(int) count_of_n = np.bincount(n_fil) count_of_n_fil = count_of_n[gids[h][0]-1:gids[h][1]] rate_each_n = count_of_n_fil * 1000. / (end - begin) rate_averaged = np.mean(rate_each_n) rate_std = np.std(rate_each_n) rates_averaged_all.append(float('%.3f' % rate_averaged)) rates_std_all.append(float('%.3f' % rate_std)) np.save(os.path.join(path, ('rate' + str(h) + '.npy')), rate_each_n) print('Mean rates: %r Hz' % rates_averaged_all) print('Standard deviation of rates: %r Hz' % rates_std_all) def boxplot(net_dict, path): """ Creates a boxblot of the firing rates of the eight populations. To create the boxplot, the firing rates of each population need to be computed with the function 'fire_rate'. Parameters ----------- net_dict Dictionary containing parameters of the microcircuit. path Path were the firing rates are stored. Returns ------- None """ pops = net_dict['N_full'] reversed_order_list = list(range(len(pops) - 1, -1, -1)) list_rates_rev = [] for h in reversed_order_list: list_rates_rev.append( np.load(os.path.join(path, ('rate' + str(h) + '.npy'))) ) pop_names = net_dict['populations'] label_pos = list(range(len(pops), 0, -1)) color_list = ['#888888', '#000000'] medianprops = dict(linestyle='-', linewidth=2.5, color='firebrick') fig, ax1 = plt.subplots(figsize=(10, 6)) bp = plt.boxplot(list_rates_rev, 0, 'rs', 0, medianprops=medianprops) plt.setp(bp['boxes'], color='black') plt.setp(bp['whiskers'], color='black') plt.setp(bp['fliers'], color='red', marker='+') for h in list(range(len(pops))): boxX = [] boxY = [] box = bp['boxes'][h] for j in list(range(5)): boxX.append(box.get_xdata()[j]) boxY.append(box.get_ydata()[j]) boxCoords = list(zip(boxX, boxY)) k = h % 2 boxPolygon = Polygon(boxCoords, facecolor=color_list[k]) ax1.add_patch(boxPolygon) plt.xlabel('firing rate [Hz]', fontsize=18) plt.yticks(label_pos, pop_names, fontsize=18) plt.xticks(fontsize=18) plt.savefig(os.path.join(path, 'box_plot.png'), dpi=300) plt.show()
terhorstd/nest-simulator
pynest/examples/Potjans_2014/helpers.py
Python
gpl-2.0
14,627
[ "NEURON" ]
a9a0dd016a9934a75421a6443f778c218fb54b85ce665c3433fce67edeb0ac79
# -*- coding: utf-8 -*- """ Default Django settings. Override these with settings in the module pointed to by the DJANGO_SETTINGS_MODULE environment variable. """ from __future__ import unicode_literals # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. def gettext_noop(s): return s #################### # CORE # #################### DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing situations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "ETag" header. This saves bandwidth but slows down performance. USE_ETAGS = False # People who get code error notifications. # In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')] ADMINS = [] # List of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = [] # Hosts/domain names that are valid for this site. # "*" matches anything, ".example.com" matches example.com and all subdomains ALLOWED_HOSTS = [] # Local time zone for this installation. All choices can be found here: # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). When USE_TZ is True, this is # interpreted as the default user time zone. TIME_ZONE = 'America/Chicago' # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = False # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. LANGUAGES = [ ('af', gettext_noop('Afrikaans')), ('ar', gettext_noop('Arabic')), ('ast', gettext_noop('Asturian')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('be', gettext_noop('Belarusian')), ('bn', gettext_noop('Bengali')), ('br', gettext_noop('Breton')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('dsb', gettext_noop('Lower Sorbian')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-au', gettext_noop('Australian English')), ('en-gb', gettext_noop('British English')), ('eo', gettext_noop('Esperanto')), ('es', gettext_noop('Spanish')), ('es-ar', gettext_noop('Argentinian Spanish')), ('es-co', gettext_noop('Colombian Spanish')), ('es-mx', gettext_noop('Mexican Spanish')), ('es-ni', gettext_noop('Nicaraguan Spanish')), ('es-ve', gettext_noop('Venezuelan Spanish')), ('et', gettext_noop('Estonian')), ('eu', gettext_noop('Basque')), ('fa', gettext_noop('Persian')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('fy', gettext_noop('Frisian')), ('ga', gettext_noop('Irish')), ('gd', gettext_noop('Scottish Gaelic')), ('gl', gettext_noop('Galician')), ('he', gettext_noop('Hebrew')), ('hi', gettext_noop('Hindi')), ('hr', gettext_noop('Croatian')), ('hsb', gettext_noop('Upper Sorbian')), ('hu', gettext_noop('Hungarian')), ('ia', gettext_noop('Interlingua')), ('id', gettext_noop('Indonesian')), ('io', gettext_noop('Ido')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('ka', gettext_noop('Georgian')), ('kk', gettext_noop('Kazakh')), ('km', gettext_noop('Khmer')), ('kn', gettext_noop('Kannada')), ('ko', gettext_noop('Korean')), ('lb', gettext_noop('Luxembourgish')), ('lt', gettext_noop('Lithuanian')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('ml', gettext_noop('Malayalam')), ('mn', gettext_noop('Mongolian')), ('mr', gettext_noop('Marathi')), ('my', gettext_noop('Burmese')), ('nb', gettext_noop('Norwegian Bokmål')), ('ne', gettext_noop('Nepali')), ('nl', gettext_noop('Dutch')), ('nn', gettext_noop('Norwegian Nynorsk')), ('os', gettext_noop('Ossetic')), ('pa', gettext_noop('Punjabi')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portuguese')), ('pt-br', gettext_noop('Brazilian Portuguese')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sq', gettext_noop('Albanian')), ('sr', gettext_noop('Serbian')), ('sr-latn', gettext_noop('Serbian Latin')), ('sv', gettext_noop('Swedish')), ('sw', gettext_noop('Swahili')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('th', gettext_noop('Thai')), ('tr', gettext_noop('Turkish')), ('tt', gettext_noop('Tatar')), ('udm', gettext_noop('Udmurt')), ('uk', gettext_noop('Ukrainian')), ('ur', gettext_noop('Urdu')), ('vi', gettext_noop('Vietnamese')), ('zh-hans', gettext_noop('Simplified Chinese')), ('zh-hant', gettext_noop('Traditional Chinese')), ] # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ["he", "ar", "fa", "ur"] # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = [] # Settings for language cookie LANGUAGE_COOKIE_NAME = 'django_language' LANGUAGE_COOKIE_AGE = None LANGUAGE_COOKIE_DOMAIN = None LANGUAGE_COOKIE_PATH = '/' # If you set this to True, Django will format dates, numbers and calendars # according to user current locale. USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link # notifications and other various emails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET = 'utf-8' # Email address that error messages come from. SERVER_EMAIL = 'root@localhost' # Database connection info. If left empty, will default to the dummy backend. DATABASES = {} # Classes used to implement DB routing behavior. DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending email. EMAIL_HOST = 'localhost' # Port for sending email. EMAIL_PORT = 25 # Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME = False # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False EMAIL_USE_SSL = False EMAIL_SSL_CERTFILE = None EMAIL_SSL_KEYFILE = None EMAIL_TIMEOUT = None # List of strings representing installed apps. INSTALLED_APPS = [] TEMPLATES = [] # Default email address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = [ # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ] DISALLOWED_USER_AGENTS = [] ABSOLUTE_URL_OVERRIDES = {} # List of compiled regular expression objects representing URLs that need not # be reported by BrokenLinkEmailsMiddleware. Here are a few examples: # import re # IGNORABLE_404_URLS = [ # re.compile(r'^/apple-touch-icon.*\.png$'), # re.compile(r'^/favicon.ico$), # re.compile(r'^/robots.txt$), # re.compile(r'^/phpmyadmin/), # re.compile(r'\.(cgi|php|pl)$'), # ] IGNORABLE_404_URLS = [] # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Example: "/var/www/example.com/static/" STATIC_ROOT = None # URL that handles the static files served from STATIC_ROOT. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be # read before a SuspiciousOperation (RequestDataTooBig) is raised. DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a # SuspiciousOperation (TooManyFieldsSent) is raised. DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see https://docs.python.org/3/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = None # The numeric mode to assign to newly-created directories, when uploading files. # The value should be a mode as you'd pass to os.chmod; # see https://docs.python.org/3/library/os.html#files-and-directories. FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' ] # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ] # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = ',' # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = '' DEFAULT_INDEX_TABLESPACE = '' # Default X-Frame-Options header value X_FRAME_OPTIONS = 'SAMEORIGIN' USE_X_FORWARDED_HOST = False USE_X_FORWARDED_PORT = False # The Python dotted path to the WSGI application that Django's internal server # (runserver) will use. If `None`, the return value of # 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same # behavior as previous versions of Django. Otherwise this should point to an # actual WSGI application object. WSGI_APPLICATION = None # If your Django app is behind a proxy that sets a header to specify secure # connections, AND that proxy ensures that user-submitted headers with the # same name are ignored (so that people can't spoof it), set this value to # a tuple of (header_name, header_value). For any requests that come in with # that header/value, request.is_secure() will return True. # WARNING! Only set this if you fully understand what you're doing. Otherwise, # you may be opening yourself up to a security risk. SECURE_PROXY_SSL_HEADER = None ############## # MIDDLEWARE # ############## # List of middleware to use. Order is important; in the request phase, these # middleware will be applied in the order given, and in the response # phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ] MIDDLEWARE = None ############ # SESSIONS # ############ # Cache to store session data if using the cache session backend. SESSION_CACHE_ALIAS = 'default' # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = 'sessionid' # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like ".example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN = None # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = '/' # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others) SESSION_COOKIE_HTTPONLY = True # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # The module to store session data SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Directory to store session files if using the file session module. If None, # the backend will use a sensible default. SESSION_FILE_PATH = None # class to serialize session data SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' ######### # CACHE # ######### # The cache backends to use. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = 'default' ################## # AUTHENTICATION # ################## AUTH_USER_MODEL = 'auth.User' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile/' LOGOUT_REDIRECT_URL = None # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 # the first hasher in this list is the preferred algorithm. any # password using different algorithms will be converted automatically # upon login PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] AUTH_PASSWORD_VALIDATORS = [] ########### # SIGNING # ########### SIGNING_BACKEND = 'django.core.signing.TimestampSigner' ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Settings for CSRF cookie. CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_PATH = '/' CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CSRF_TRUSTED_ORIGINS = [] ############ # MESSAGES # ############ # Class to use as messages backend MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = 'logging.config.dictConfig' # Custom logging configuration. LOGGING = {} # Default exception reporter filter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter' ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = 'django.test.runner.DiscoverRunner' # Apps that don't need to be serialized at test database creation time # (only apps with migrations are to start with) TEST_NON_SERIALIZED_APPS = [] ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = [] ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = [] # The default file storage backend used during the build process STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] ############## # MIGRATIONS # ############## # Migration module overrides for apps, by app label. MIGRATION_MODULES = {} ################# # SYSTEM CHECKS # ################# # List of all issues generated by system checks that should be silenced. Light # issues like warnings, infos or debugs will not generate a message. Silencing # serious issues like errors and criticals does not result in hiding the # message, but Django will not stop you from e.g. running server. SILENCED_SYSTEM_CHECKS = [] ####################### # SECURITY MIDDLEWARE # ####################### SECURE_BROWSER_XSS_FILTER = False SECURE_CONTENT_TYPE_NOSNIFF = False SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_PRELOAD = False SECURE_HSTS_SECONDS = 0 SECURE_REDIRECT_EXEMPT = [] SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False
jarshwah/django
django/conf/global_settings.py
Python
bsd-3-clause
21,946
[ "VisIt" ]
5e384f207be3d984c1b3a7c7708044c6797f9aad3fc4ce875867d4848ca1a7ab
""" Collection of DIRAC useful operating system related modules by default on Error they return None """ from __future__ import print_function import os import distutils.spawn # pylint: disable=no-name-in-module,import-error import DIRAC from DIRAC.Core.Utilities.Subprocess import shellCall, systemCall from DIRAC.Core.Utilities import List __RCSID__ = "$Id$" DEBUG = 0 def uniquePath(path=None): """ Utility to squeeze the string containing a PATH-like value to leave only unique elements preserving the original order """ if not isinstance(path, basestring): return None try: elements = List.uniqueElements(List.fromChar(path, ":")) return ':'.join(elements) except Exception: return None def getDiskSpace(path='.'): """ Get the free disk space in the partition containing the path. The disk space is reported in MBytes. Returned 0 in case of any error, e.g. path does not exist """ if not os.path.exists(path): return -1 comm = 'df -P -m %s | tail -1' % path resultDF = shellCall(10, comm) if resultDF['OK'] and not resultDF['Value'][0]: output = resultDF['Value'][1] if output.find(' /afs') >= 0: # AFS disk space comm = 'fs lq | tail -1' resultAFS = shellCall(10, comm) if resultAFS['OK'] and not resultAFS['Value'][0]: output = resultAFS['Value'][1] fields = output.split() quota = long(fields[1]) used = long(fields[2]) space = (quota - used) / 1024 return int(space) else: return -1 else: fields = output.split() try: value = int(fields[3]) except Exception as error: print("Exception during disk space evaluation:", str(error)) value = -1 return value else: return -1 def getDirectorySize(path): """ Get the total size of the given directory in MB """ comm = "du -s -m %s" % path result = shellCall(10, comm) if not result['OK'] or result['Value'][0] != 0: return 0 else: output = result['Value'][1] print(output) size = int(output.split()[0]) return size def sourceEnv(timeout, cmdTuple, inputEnv=None): """ Function to source configuration files in a platform dependent way and get back the environment """ # add appropriate extension to first element of the tuple (the command) envAsDict = '&& python -c "import os,sys ; print >> sys.stderr, os.environ"' # 1.- Choose the right version of the configuration file if DIRAC.getPlatformTuple()[0] == 'Windows': cmdTuple[0] += '.bat' else: cmdTuple[0] += '.sh' # 2.- Check that it exists if not os.path.exists(cmdTuple[0]): result = DIRAC.S_ERROR('Missing script: %s' % cmdTuple[0]) result['stdout'] = '' result['stderr'] = 'Missing script: %s' % cmdTuple[0] return result # Source it in a platform dependent way: # On windows the execution makes the environment to be inherit # On Linux or Darwin use bash and source the file. if DIRAC.getPlatformTuple()[0] == 'Windows': # this needs to be tested cmd = ' '.join(cmdTuple) + envAsDict ret = shellCall(timeout, [cmd], env=inputEnv) else: cmdTuple.insert(0, 'source') cmd = ' '.join(cmdTuple) + envAsDict ret = systemCall(timeout, ['/bin/bash', '-c', cmd], env=inputEnv) # 3.- Now get back the result stdout = '' stderr = '' result = DIRAC.S_OK() if ret['OK']: # The Command has not timeout, retrieve stdout and stderr stdout = ret['Value'][1] stderr = ret['Value'][2] if ret['Value'][0] == 0: # execution was OK try: result['outputEnv'] = eval(stderr.split('\n')[-2] + '\n') stderr = '\n'.join(stderr.split('\n')[:-2]) except Exception: stdout = cmd + '\n' + stdout result = DIRAC.S_ERROR('Could not parse Environment dictionary from stderr') else: # execution error stdout = cmd + '\n' + stdout result = DIRAC.S_ERROR('Execution returns %s' % ret['Value'][0]) else: # Timeout stdout = cmd stderr = ret['Message'] result = DIRAC.S_ERROR(stderr) # 4.- Put stdout and stderr in result structure result['stdout'] = stdout result['stderr'] = stderr return result def which(executable): return distutils.spawn.find_executable(executable) # pylint: disable=no-member
fstagni/DIRAC
Core/Utilities/Os.py
Python
gpl-3.0
4,356
[ "DIRAC" ]
6530a34b77e44638605de659a7280d10f2a1206599c255dfa61b9e9e52399be0
# Copyright (c) 2015 James Hensman # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from ..core import GP from . import GPLVM from .. import mappings class BCGPLVM(GPLVM): """ Back constrained Gaussian Process Latent Variable Model :param Y: observed data :type Y: np.ndarray :param input_dim: latent dimensionality :type input_dim: int :param mapping: mapping for back constraint :type mapping: GPy.core.Mapping object """ def __init__(self, Y, input_dim, kernel=None, mapping=None): if mapping is None: mapping = mappings.MLP(input_dim=Y.shape[1], output_dim=input_dim, hidden_dim=10) else: assert mapping.input_dim==Y.shape[1], "mapping input dim does not work for Y dimension" assert mapping.output_dim==input_dim, "mapping output dim does not work for self.input_dim" GPLVM.__init__(self, Y, input_dim, X=mapping.f(Y), kernel=kernel, name="bcgplvm") self.unlink_parameter(self.X) self.mapping = mapping self.link_parameter(self.mapping) self.X = self.mapping.f(self.Y) def parameters_changed(self): self.X = self.mapping.f(self.Y) GP.parameters_changed(self) Xgradient = self.kern.gradients_X(self.grad_dict['dL_dK'], self.X, None) self.mapping.update_gradients(Xgradient, self.Y)
jameshensman/GPy
GPy/models/bcgplvm.py
Python
bsd-3-clause
1,466
[ "Gaussian" ]
231937c08535c858ded18efe1b0cff4b4e8bb6f3897737eb6d95a5fecc9e0eb3
import unittest from StringIO import StringIO from robot.result import ExecutionResult from robot.reporting.outputwriter import OutputWriter from robot.utils import XmlWriter from robot.utils.asserts import assert_equals from robot.utils import ET, ETSource from test_resultbuilder import GOLDEN_XML, GOLDEN_XML_TWICE class StreamXmlWriter(XmlWriter): def _create_output(self, output): return output def close(self): pass class TestableOutputWriter(OutputWriter): def _get_writer(self, output, generator): writer = StreamXmlWriter(output, encoding='UTF-8', write_empty=False) writer.start('robot') return writer class TestResultSerializer(unittest.TestCase): def test_single_result_serialization(self): output = StringIO() writer = TestableOutputWriter(output) ExecutionResult(GOLDEN_XML).visit(writer) self._assert_xml_content(self._xml_lines(output.getvalue()), self._xml_lines(GOLDEN_XML)) def _xml_lines(self, text): with ETSource(text) as source: tree = ET.parse(source) output = StringIO() tree.write(output) return output.getvalue().splitlines() def _assert_xml_content(self, actual, expected): assert_equals(len(actual), len(expected)) for index, (act, exp) in enumerate(zip(actual, expected)[2:]): assert_equals(act, exp.strip(), 'Different values on line %d' % index) def test_combining_results(self): output = StringIO() writer = TestableOutputWriter(output) ExecutionResult(GOLDEN_XML, GOLDEN_XML).visit(writer) self._assert_xml_content(self._xml_lines(output.getvalue()), self._xml_lines(GOLDEN_XML_TWICE)) if __name__ == '__main__': unittest.main()
JackNokia/robotframework
utest/result/test_resultserializer.py
Python
apache-2.0
1,854
[ "VisIt" ]
9aae02805f7099111361fa8847030adc6d573a4b43655e50a170a6777183da83
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # --------------------------------------------------------------------------- # # Copyright (c) 2008-2013 Raoul Snyman # # Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan # # Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, # # Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. # # Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, # # Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, # # Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, # # Frode Woldsund, Martin Zibricky, Patrick Zimmermann # # --------------------------------------------------------------------------- # # 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; version 2 of the License. # # # # 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., 59 # # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### import logging from PyQt4 import QtCore, QtGui from openlp.core.lib import Receiver, translate from openlp.core.lib.ui import critical_error_message_box, \ find_and_set_in_combo_box from openlp.plugins.custom.lib import CustomXMLBuilder, CustomXMLParser from openlp.plugins.custom.lib.db import CustomSlide from editcustomdialog import Ui_CustomEditDialog from editcustomslideform import EditCustomSlideForm log = logging.getLogger(__name__) class EditCustomForm(QtGui.QDialog, Ui_CustomEditDialog): """ Class documentation goes here. """ log.info(u'Custom Editor loaded') def __init__(self, mediaitem, parent, manager): """ Constructor """ super(EditCustomForm, self).__init__(parent) self.manager = manager self.mediaitem = mediaitem self.setupUi(self) # Create other objects and forms. self.editSlideForm = EditCustomSlideForm(self) # Connecting signals and slots self.previewButton.clicked.connect(self.on_preview_button_clicked) self.addButton.clicked.connect(self.on_add_button_clicked) self.editButton.clicked.connect(self.on_edit_button_clicked) self.editAllButton.clicked.connect(self.on_edit_all_button_clicked) self.slideListView.currentRowChanged.connect(self.on_current_row_changed) self.slideListView.doubleClicked.connect(self.on_edit_button_clicked) QtCore.QObject.connect(Receiver.get_receiver(), QtCore.SIGNAL(u'theme_update_list'), self.loadThemes) def loadThemes(self, theme_list): """ Load a list of themes into the themes combo box. ``theme_list`` The list of themes to load. """ self.themeComboBox.clear() self.themeComboBox.addItem(u'') self.themeComboBox.addItems(theme_list) def loadCustom(self, id, preview=False): """ Called when editing or creating a new custom. ``id`` The cutom's id. If zero, then a new custom is created. ``preview`` States whether the custom is edited while being previewed in the preview panel. """ self.slideListView.clear() if id == 0: self.customSlide = CustomSlide() self.titleEdit.setText(u'') self.creditEdit.setText(u'') self.themeComboBox.setCurrentIndex(0) else: self.customSlide = self.manager.get_object(CustomSlide, id) self.titleEdit.setText(self.customSlide.title) self.creditEdit.setText(self.customSlide.credits) customXML = CustomXMLParser(self.customSlide.text) slideList = customXML.get_verses() for slide in slideList: self.slideListView.addItem(slide[1]) theme = self.customSlide.theme_name find_and_set_in_combo_box(self.themeComboBox, theme) self.titleEdit.setFocus() # If not preview hide the preview button. self.previewButton.setVisible(preview) def accept(self): """ Override the QDialog method to check if the custom slide has been saved before closing the dialog. """ log.debug(u'accept') if self.saveCustom(): QtGui.QDialog.accept(self) def saveCustom(self): """ Saves the custom. """ if not self._validate(): return False sxml = CustomXMLBuilder() for count in range(self.slideListView.count()): sxml.add_verse_to_lyrics(u'custom', unicode(count + 1), self.slideListView.item(count).text()) self.customSlide.title = self.titleEdit.text() self.customSlide.text = unicode(sxml.extract_xml(), u'utf-8') self.customSlide.credits = self.creditEdit.text() self.customSlide.theme_name = self.themeComboBox.currentText() success = self.manager.save_object(self.customSlide) self.mediaitem.autoSelectId = self.customSlide.id return success def onUpButtonClicked(self): """ Move a slide up in the list when the "Up" button is clicked. """ selectedRow = self.slideListView.currentRow() if selectedRow != 0: qw = self.slideListView.takeItem(selectedRow) self.slideListView.insertItem(selectedRow - 1, qw) self.slideListView.setCurrentRow(selectedRow - 1) def onDownButtonClicked(self): """ Move a slide down in the list when the "Down" button is clicked. """ selectedRow = self.slideListView.currentRow() # zero base arrays if selectedRow != self.slideListView.count() - 1: qw = self.slideListView.takeItem(selectedRow) self.slideListView.insertItem(selectedRow + 1, qw) self.slideListView.setCurrentRow(selectedRow + 1) def on_add_button_clicked(self): """ Add a new blank slide. """ self.editSlideForm.setText(u'') if self.editSlideForm.exec_(): self.slideListView.addItems(self.editSlideForm.getText()) def on_edit_button_clicked(self): """ Edit the currently selected slide. """ self.editSlideForm.setText(self.slideListView.currentItem().text()) if self.editSlideForm.exec_(): self.updateSlideList(self.editSlideForm.getText()) def on_edit_all_button_clicked(self): """ Edits all slides. """ slide_text = u'' for row in range(self.slideListView.count()): item = self.slideListView.item(row) slide_text += item.text() if row != self.slideListView.count() - 1: slide_text += u'\n[===]\n' self.editSlideForm.setText(slide_text) if self.editSlideForm.exec_(): self.updateSlideList(self.editSlideForm.getText(), True) def on_preview_button_clicked(self): """ Save the custom item and preview it. """ log.debug(u'onPreview') if self.saveCustom(): Receiver.send_message(u'custom_preview') def updateSlideList(self, slides, edit_all=False): """ Updates the slide list after editing slides. ``slides`` A list of all slides which have been edited. ``edit_all`` Indicates if all slides or only one slide has been edited. """ if edit_all: self.slideListView.clear() self.slideListView.addItems(slides) else: old_slides = [] old_row = self.slideListView.currentRow() # Create a list with all (old/unedited) slides. old_slides = [self.slideListView.item(row).text() for row in range(self.slideListView.count())] self.slideListView.clear() old_slides.pop(old_row) # Insert all slides to make the old_slides list complete. for slide in slides: old_slides.insert(old_row, slide) self.slideListView.addItems(old_slides) self.slideListView.repaint() def onDeleteButtonClicked(self): """ Removes the current row from the list. """ self.slideListView.takeItem(self.slideListView.currentRow()) self.on_current_row_changed(self.slideListView.currentRow()) def on_current_row_changed(self, row): """ Called when the *slideListView*'s current row has been changed. This enables or disables buttons which require an slide to act on. ``row`` The row (int). If there is no current row, the value is -1. """ if row == -1: self.deleteButton.setEnabled(False) self.editButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) else: self.deleteButton.setEnabled(True) self.editButton.setEnabled(True) # Decide if the up/down buttons should be enabled or not. self.downButton.setEnabled(self.slideListView.count() - 1 != row) self.upButton.setEnabled(row != 0) def _validate(self): """ Checks whether a custom is valid or not. """ # We must have a title. if not self.titleEdit.displayText(): self.titleEdit.setFocus() critical_error_message_box(message=translate('CustomPlugin.EditCustomForm', 'You need to type in a title.')) return False # We must have at least one slide. if self.slideListView.count() == 0: critical_error_message_box(message=translate('CustomPlugin.EditCustomForm', 'You need to add at least one slide')) return False return True
marmyshev/transitions
openlp/plugins/custom/forms/editcustomform.py
Python
gpl-2.0
10,952
[ "Brian" ]
9e320091fb426e3379666bdd35a0ef90794ed3b92bf3ed07ad21c491ebdffa0e
# Copyright 2014 Andrew Owen Martin # # 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. import math def generate_points(point_count, noise, standard_deviation, random): """Get suitable data for a line estimation problem. Returns a number of points, a determined proportion of which are randomly placed between 0 and 1, and the rest are perturbed by a by a zero mean gaussian from a line. Args: point_count: Total number of points to use. noise: Proportion from 0 to 1 of points to be randomly placed. standard_deviation: The standard deviation of the zero mean gaussian used to peturb good points. random: Random generator Returns: The generated line and the collection of 2 dimensional points between (0,0) and (1,1), some of which lie on it. Raises: None """ noise_points = int(point_count * noise) line_points = point_count - noise_points points = [] line = ( (0,random.random()), (1,random.random())) for i in xrange(line_points): point = random_point_between_two_points(line[0],line[1],random) points.append( perturb_point(point, standard_deviation, random)) for i in xrange(noise_points): points.append( (random.random(),random.random())) return (line, points) def perturb_point(point, standard_deviation, random): """Peturb a point from an amount determined by a zero mean normal Gaussian. Args: point: 2D Point. standard_deviation: The standard deviation of the zero mean gaussian. Returns: A point peturbed by a gaussian. Raises: None """ perturbation = random.gauss(0,standard_deviation) # Gets a uniformly distributed angle in the range 0 and 2*pi # https://docs.python.org/3.1/library/random.html#random.vonmisesvariate angle = random.vonmisesvariate(0,0) return ( point[0] + (perturbation * math.sin(angle)), point[1] + (perturbation * math.cos(angle))) def gnuplot_problem(line, points, file_name): """Write a list of points and a line to a gnuplot file. View the file in gnuplot with: > plot 'plot.txt' using 1:2,'plot.txt' using 3:4 with lines if the file_name was plot.txt. Args: line: Iterable of two 2d points to define a line. points: Iterable of 2d points. filename: File name of gnuplottable file Returns: None Side Effects: Writes a gnuplottable file to disk. Raises: None """ data_lines = [] for num,point in enumerate(points): data_line = "{x} {y}".format( x=point[0], y=point[1]) if num < len(line): data_line = data_line + " " + "{x} {y}".format( x=line[num][0], y=line[num][1]) data_lines.append(data_line) with open(file_name,"w") as file: file.write("\n".join(data_lines)) def random_point_between_two_points(A, B, random): """Get a random point between A and B Using: p = A + t(B-A) where: A = point A B = point B t = proportion of the distance from A to B p = a point between A and Bto place a line Args: A: Point A. B: Point B. random: Random generator Returns: A point randomly between A and B Raises: None. """ t = random.random() p = (a + c for a,c in zip(A,(x*t for x in (b-a for b,a in zip(B,A))))) return tuple(p)
AndrewOwenMartin/sds-recipes
solutions/line_estimation_problem.py
Python
apache-2.0
4,116
[ "Gaussian" ]
db65d4a442384869c816aec0f6a311eb9c31410b6d741751f4933f301b261a86
""" Datatype classes for tracks/track views within galaxy. """ import binary, binascii, logging from galaxy import util from galaxy.web import url_for from galaxy.util.hash_util import hmac_new from urllib import quote_plus log = logging.getLogger(__name__) # GeneTrack is no longer supported but leaving the datatype since # files of this type may still exist class GeneTrack( binary.Binary ): file_ext = "genetrack" def __init__(self, **kwargs): super( GeneTrack, self ).__init__( **kwargs ) # self.add_display_app( 'genetrack', 'View in', '', 'genetrack_link' ) # def get_display_links( self, dataset, type, app, base_url, target_frame='galaxy_main', **kwd ): #Force target_frame to be 'galaxy_main' # return binary.Binary.get_display_links( self, dataset, type, app, base_url, target_frame=target_frame, **kwd ) # def genetrack_link( self, hda, type, app, base_url ): # ret_val = [] # if hda.dataset.has_data(): # # Get the disk file name and data id # file_name = hda.dataset.get_file_name() # data_id = quote_plus( str( hda.id ) ) # galaxy_url = quote_plus( "%s%s" % ( base_url, url_for( controller = 'tool_runner', tool_id='predict2genetrack' ) ) ) # # Make it secure # hashkey = quote_plus( hmac_new( app.config.tool_secret, file_name ) ) # encoded = quote_plus( binascii.hexlify( file_name ) ) # for name, url in util.get_genetrack_sites(): # if name.lower() in app.config.genetrack_display_sites: # # send both parameters filename and hashkey # link = "%s?filename=%s&hashkey=%s&input=%s&GALAXY_URL=%s" % ( url, encoded, hashkey, data_id, galaxy_url ) # ret_val.append( ( name, link ) ) # return ret_val
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/lib/galaxy/datatypes/tracks.py
Python
gpl-3.0
1,861
[ "Galaxy" ]
231dd11f8329c08420a61c54d04837c28f7d7ffc023a64f89b15ed2aeadf56f1
""" Instruction transformations. """ from __future__ import absolute_import from .ast import Def, Var, Apply from .ti import ti_xform, TypeEnv, get_type_env, TypeConstraint from collections import OrderedDict from functools import reduce try: from typing import Union, Iterator, Sequence, Iterable, List, Dict # noqa from typing import Optional, Set # noqa from .ast import Expr, VarAtomMap # noqa from .isa import TargetISA # noqa from .typevar import TypeVar # noqa from .instructions import ConstrList, Instruction # noqa DefApply = Union[Def, Apply] except ImportError: pass def canonicalize_defapply(node): # type: (DefApply) -> Def """ Canonicalize a `Def` or `Apply` node into a `Def`. An `Apply` becomes a `Def` with an empty list of defs. """ if isinstance(node, Apply): return Def((), node) else: return node class Rtl(object): """ Register Transfer Language list. An RTL object contains a list of register assignments in the form of `Def` objects. An RTL list can represent both a source pattern to be matched, or a destination pattern to be inserted. """ def __init__(self, *args): # type: (*DefApply) -> None self.rtl = tuple(map(canonicalize_defapply, args)) def copy(self, m): # type: (VarAtomMap) -> Rtl """ Return a copy of this rtl with all Vars substituted with copies or according to m. Update m as neccessary. """ return Rtl(*[d.copy(m) for d in self.rtl]) def vars(self): # type: () -> Set[Var] """Return the set of all Vars in self that correspond to SSA values""" return reduce(lambda x, y: x.union(y), [d.vars() for d in self.rtl], set([])) def definitions(self): # type: () -> Set[Var] """ Return the set of all Vars defined in self""" return reduce(lambda x, y: x.union(y), [d.definitions() for d in self.rtl], set([])) def free_vars(self): # type: () -> Set[Var] """Return the set of free Vars corresp. to SSA vals used in self""" def flow_f(s, d): # type: (Set[Var], Def) -> Set[Var] """Compute the change in the set of free vars across a Def""" s = s.difference(set(d.defs)) uses = set(d.expr.args[i] for i in d.expr.inst.value_opnums) for v in uses: assert isinstance(v, Var) s.add(v) return s return reduce(flow_f, reversed(self.rtl), set([])) def substitution(self, other, s): # type: (Rtl, VarAtomMap) -> Optional[VarAtomMap] """ If the Rtl self agrees structurally with the Rtl other, return a substitution to transform self to other. Two Rtls agree structurally if they have the same sequence of Defs, that agree structurally. """ if len(self.rtl) != len(other.rtl): return None for i in range(len(self.rtl)): s = self.rtl[i].substitution(other.rtl[i], s) if s is None: return None return s def is_concrete(self): # type: (Rtl) -> bool """Return True iff every Var in the self has a singleton type.""" return all(v.get_typevar().singleton_type() is not None for v in self.vars()) def cleanup_concrete_rtl(self): # type: (Rtl) -> None """ Given that there is only 1 possible concrete typing T for self, assign a singleton TV with type t=T[v] for each Var v \in self. Its an error to call this on an Rtl with more than 1 possible typing. This modifies the Rtl in-place. """ from .ti import ti_rtl, TypeEnv # 1) Infer the types of all vars in res typenv = get_type_env(ti_rtl(self, TypeEnv())) typenv.normalize() typenv = typenv.extract() # 2) Make sure there is only one possible type assignment typings = list(typenv.concrete_typings()) assert len(typings) == 1 typing = typings[0] # 3) Assign the only possible type to each variable. for v in typenv.vars: assert typing[v].singleton_type() is not None v.set_typevar(typing[v]) def __str__(self): # type: () -> str return "\n".join(map(str, self.rtl)) class XForm(object): """ An instruction transformation consists of a source and destination pattern. Patterns are expressed in *register transfer language* as tuples of `ast.Def` or `ast.Expr` nodes. A pattern may optionally have a sequence of TypeConstraints, that additionally limit the set of cases when it applies. A legalization pattern must have a source pattern containing only a single instruction. >>> from base.instructions import iconst, iadd, iadd_imm >>> a = Var('a') >>> c = Var('c') >>> v = Var('v') >>> x = Var('x') >>> XForm( ... Rtl(c << iconst(v), ... a << iadd(x, c)), ... Rtl(a << iadd_imm(x, v))) XForm(inputs=[Var(v), Var(x)], defs=[Var(c, src), Var(a, src, dst)], c << iconst(v) a << iadd(x, c) => a << iadd_imm(x, v) ) """ def __init__(self, src, dst, constraints=None): # type: (Rtl, Rtl, Optional[ConstrList]) -> None self.src = src self.dst = dst # Variables that are inputs to the source pattern. self.inputs = list() # type: List[Var] # Variables defined in either src or dst. self.defs = list() # type: List[Var] # Rewrite variables in src and dst RTL lists to our own copies. # Map name -> private Var. symtab = dict() # type: Dict[str, Var] self._rewrite_rtl(src, symtab, Var.SRCCTX) num_src_inputs = len(self.inputs) self._rewrite_rtl(dst, symtab, Var.DSTCTX) # Needed for testing type inference on XForms self.symtab = symtab # Check for inconsistently used inputs. for i in self.inputs: if not i.is_input(): raise AssertionError( "'{}' used as both input and def".format(i)) # Check for spurious inputs in dst. if len(self.inputs) > num_src_inputs: raise AssertionError( "extra inputs in dst RTL: {}".format( self.inputs[num_src_inputs:])) # Perform type inference and cleanup raw_ti = get_type_env(ti_xform(self, TypeEnv())) raw_ti.normalize() self.ti = raw_ti.extract() def interp_tv(tv): # type: (TypeVar) -> TypeVar """ Convert typevars according to symtab """ if not tv.name.startswith("typeof_"): return tv return symtab[tv.name[len("typeof_"):]].get_typevar() self.constraints = [] # type: List[TypeConstraint] if constraints is not None: if isinstance(constraints, TypeConstraint): constr_list = [constraints] # type: Sequence[TypeConstraint] else: constr_list = constraints for c in constr_list: type_m = {tv: interp_tv(tv) for tv in c.tvs()} inner_c = c.translate(type_m) self.constraints.append(inner_c) self.ti.add_constraint(inner_c) # Sanity: The set of inferred free typevars should be a subset of the # TVs corresponding to Vars appearing in src free_typevars = set(self.ti.free_typevars()) src_vars = set(self.inputs).union( [x for x in self.defs if not x.is_temp()]) src_tvs = set([v.get_typevar() for v in src_vars]) if (not free_typevars.issubset(src_tvs)): raise AssertionError( "Some free vars don't appear in src - {}" .format(free_typevars.difference(src_tvs))) # Update the type vars for each Var to their inferred values for v in self.inputs + self.defs: v.set_typevar(self.ti[v.get_typevar()]) def __repr__(self): # type: () -> str s = "XForm(inputs={}, defs={},\n ".format(self.inputs, self.defs) s += '\n '.join(str(n) for n in self.src.rtl) s += '\n=>\n ' s += '\n '.join(str(n) for n in self.dst.rtl) s += '\n)' return s def _rewrite_rtl(self, rtl, symtab, context): # type: (Rtl, Dict[str, Var], int) -> None for line in rtl.rtl: if isinstance(line, Def): line.defs = tuple( self._rewrite_defs(line, symtab, context)) expr = line.expr else: expr = line self._rewrite_expr(expr, symtab, context) def _rewrite_expr(self, expr, symtab, context): # type: (Apply, Dict[str, Var], int) -> None """ Find all uses of variables in `expr` and replace them with our own local symbols. """ # Accept a whole expression tree. stack = [expr] while len(stack) > 0: expr = stack.pop() expr.args = tuple( self._rewrite_uses(expr, stack, symtab, context)) def _rewrite_defs(self, line, symtab, context): # type: (Def, Dict[str, Var], int) -> Iterable[Var] """ Given a tuple of symbols defined in a Def, rewrite them to local symbols. Yield the new locals. """ for sym in line.defs: name = str(sym) if name in symtab: var = symtab[name] if var.get_def(context): raise AssertionError("'{}' multiply defined".format(name)) else: var = Var(name) symtab[name] = var self.defs.append(var) var.set_def(context, line) yield var def _rewrite_uses(self, expr, stack, symtab, context): # type: (Apply, List[Apply], Dict[str, Var], int) -> Iterable[Expr] """ Given an `Apply` expr, rewrite all uses in its arguments to local variables. Yield a sequence of new arguments. Append any `Apply` arguments to `stack`. """ for arg, operand in zip(expr.args, expr.inst.ins): # Nested instructions are allowed. Visit recursively. if isinstance(arg, Apply): stack.append(arg) yield arg continue if not isinstance(arg, Var): assert not operand.is_value(), "Value arg must be `Var`" yield arg continue # This is supposed to be a symbolic value reference. name = str(arg) if name in symtab: var = symtab[name] # The variable must be used consistently as a def or input. if not var.is_input() and not var.get_def(context): raise AssertionError( "'{}' used as both input and def" .format(name)) else: # First time use of variable. var = Var(name) symtab[name] = var self.inputs.append(var) yield var def verify_legalize(self): # type: () -> None """ Verify that this is a valid legalization XForm. - The source pattern must describe a single instruction. - All values defined in the output pattern must be defined in the destination pattern. """ assert len(self.src.rtl) == 1, "Legalize needs single instruction." for d in self.src.rtl[0].defs: if not d.is_output(): raise AssertionError( '{} not defined in dest pattern'.format(d)) def apply(self, r, suffix=None): # type: (Rtl, str) -> Rtl """ Given a concrete Rtl r s.t. r matches self.src, return the corresponding concrete self.dst. If suffix is provided, any temporary defs are renamed with '.suffix' appended to their old name. """ assert r.is_concrete() s = self.src.substitution(r, {}) # type: VarAtomMap assert s is not None if (suffix is not None): for v in self.dst.vars(): if v.is_temp(): assert v not in s s[v] = Var(v.name + '.' + suffix) dst = self.dst.copy(s) dst.cleanup_concrete_rtl() return dst class XFormGroup(object): """ A group of related transformations. :param isa: A target ISA whose instructions are allowed. :param chain: A next level group to try if this one doesn't match. """ def __init__(self, name, doc, isa=None, chain=None): # type: (str, str, TargetISA, XFormGroup) -> None self.xforms = list() # type: List[XForm] self.custom = OrderedDict() # type: OrderedDict[Instruction, str] self.name = name self.__doc__ = doc self.isa = isa self.chain = chain def __str__(self): # type: () -> str if self.isa: return '{}.{}'.format(self.isa.name, self.name) else: return self.name def rust_name(self): # type: () -> str """ Get the Rust name of this function implementing this transform. """ if self.isa: # This is a function in the same module as the LEGALIZE_ACTION # table referring to it. return self.name else: return '::legalizer::{}'.format(self.name) def legalize(self, src, dst): # type: (Union[Def, Apply], Rtl) -> None """ Add a legalization pattern to this group. :param src: Single `Def` or `Apply` to be legalized. :param dst: `Rtl` list of replacement instructions. """ xform = XForm(Rtl(src), dst) xform.verify_legalize() self.xforms.append(xform) def custom_legalize(self, inst, funcname): # type: (Instruction, str) -> None """ Add a custom legalization action for `inst`. The `funcname` parameter is the fully qualified name of a Rust function which takes the same arguments as the `isa::Legalize` actions. The custom function will be called to legalize `inst` and any return value is ignored. """ assert inst not in self.custom, "Duplicate custom_legalize" self.custom[inst] = funcname
sunfishcode/cretonne
lib/cretonne/meta/cdsl/xform.py
Python
apache-2.0
14,763
[ "VisIt" ]
b9db7dd9a4b32e2cfc34def1d2e3213f1fb250a0f66b3aca2c1f30129437d4b6
## # Copyright 2009-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for building and installing NCL, implemented as an easyblock @author: Stijn De Weirdt (Ghent University) @author: Dries Verdegem (Ghent University) @author: Kenneth Hoste (Ghent University) @author: Pieter De Baets (Ghent University) @author: Jens Timmerman (Ghent University) """ import fileinput import os import re import sys from distutils.version import LooseVersion from easybuild.framework.easyblock import EasyBlock from easybuild.tools.build_log import EasyBuildError from easybuild.tools.modules import get_software_root, get_software_version from easybuild.tools.run import run_cmd class EB_NCL(EasyBlock): """Support for building/installing NCL.""" def configure_step(self): """Configure build: - create Makefile.ini using make and run ymake script to create config file - patch config file with correct settings, and add missing config entries - create config/Site.local file to avoid interactive install - generate Makefile using config/ymkmf script - """ try: os.chdir('config') except OSError, err: raise EasyBuildError("Failed to change to the 'config' dir: %s", err) cmd = "make -f Makefile.ini" run_cmd(cmd, log_all=True, simple=True) cmd = "./ymake -config $PWD" run_cmd(cmd, log_all=True, simple=True) # figure out name of config file cfg_regexp = re.compile('^\s*SYSTEM_INCLUDE\s*=\s*"(.*)"\s*$', re.M) f = open("Makefile", "r") txt = f.read() f.close() cfg_filename = cfg_regexp.search(txt).group(1) # adjust config file as needed ctof_libs = '' ifort = get_software_root('ifort') if ifort: if LooseVersion(get_software_version('ifort')) < LooseVersion('2011.4'): ctof_libs = '-lm -L%s/lib/intel64 -lifcore -lifport' % ifort else: ctof_libs = '-lm -L%s/compiler/lib/intel64 -lifcore -lifport' % ifort elif get_software_root('GCC'): ctof_libs = '-lgfortran -lm' macrodict = { 'CCompiler': os.getenv('CC'), 'FCompiler': os.getenv('F90'), 'CcOptions': '-ansi %s' % os.getenv('CFLAGS') + ' -DH5Rdereference_vers=1 ', 'FcOptions': os.getenv('FFLAGS') + ' -fno-range-check ', 'COptimizeFlag': os.getenv('CFLAGS'), 'FOptimizeFlag': os.getenv('FFLAGS'), 'ExtraSysLibraries': os.getenv('LDFLAGS'), 'CtoFLibraries': ctof_libs } # replace config entries that are already there for line in fileinput.input(cfg_filename, inplace=1, backup='%s.orig' % cfg_filename): for (key, val) in macrodict.items(): regexp = re.compile("(#define %s\s*).*" % key) match = regexp.search(line) if match: line = "#define %s %s\n" % (key, val) macrodict.pop(key) sys.stdout.write(line) # add remaining config entries f = open(cfg_filename, "a") for (key, val) in macrodict.items(): f.write("#define %s %s\n" % (key, val)) f.close() f = open(cfg_filename, "r") self.log.debug("Contents of %s: %s" % (cfg_filename, f.read())) f.close() # configure try: os.chdir(self.cfg['start_dir']) except OSError, err: raise EasyBuildError("Failed to change to the build dir %s: %s", self.cfg['start_dir'], err) # instead of running the Configure script that asks a zillion questions, # let's just generate the config/Site.local file ourselves... # order of deps is important # HDF needs to go after netCDF, because both have a netcdf.h include file # Note: HDF currently not supported - requires netCDF support, which is incompatible with other # software packages deps = ["HDF5", "JasPer", "netCDF", "HDF-EOS", "HDF-EOS5", "g2lib", "g2clib", "Szip", "UDUNITS"] libs = '' includes = '' for dep in deps: root = get_software_root(dep) if not root: raise EasyBuildError("%s not available", dep) libs += ' -L%s/lib ' % root includes += ' -I%s/include ' % root opt_deps = ["netCDF-Fortran", "GDAL"] libs_map = { 'netCDF-Fortran': '-lnetcdff -lnetcdf', 'GDAL': '-lgdal', } for dep in opt_deps: root = get_software_root(dep) if root: libs += ' -L%s/lib %s ' % (root, libs_map[dep]) includes += ' -I%s/include ' % root # Help build system find freetype includes += ' -I/usr/include/freetype2 ' cfgtxt="""#ifdef FirstSite #endif /* FirstSite */ #ifdef SecondSite /* Allow file paths to contain x86_64. Note that this will cause macro recursion errors. */ #ifdef x86_64 #undef x86_64 #define x86_64 x86_64 #endif #define YmakeRoot %(installdir)s #define LibSearch %(libs)s #define IncSearch %(includes)s #define BuildNCL 1 #define HDFlib #define HDFEOSlib -lGctp -lhdfeos #define HDFEOS5lib -lhe5_hdfeos #define BuildGRIB2 1 #define BuildESMF 1 #define UdUnitslib -ludunits2 #define BuildRasterHDF 0 #define BuildHDF4 0 #define BuildTRIANGLE 0 #define BuildHDFEOS 1 #define BuildHDFEOS5 1 #define LexLibrary -lfl #endif /* SecondSite */ """ % { 'installdir': self.installdir, 'libs': libs, 'includes': includes } f = open("config/Site.local", "w") f.write(cfgtxt) f.close() # generate Makefile cmd = "./config/ymkmf" run_cmd(cmd, log_all=True, simple=True) def build_step(self): """Building is done in install_step.""" pass def install_step(self): """Build in install dir using build_step.""" paracmd = "" if self.cfg['parallel']: paracmd = "-j %s" % self.cfg['parallel'] cmd = "make Everything " + paracmd run_cmd(cmd, log_all=True, simple=True) def sanity_check_step(self): """ Custom sanity check for NCL """ custom_paths = { 'files': ['bin/ncl', 'lib/libncl.a', 'lib/libncarg.a'], 'dirs': ['include/ncarg'], } super(EB_NCL, self).sanity_check_step(custom_paths=custom_paths) def make_module_extra(self): """Set NCARG_ROOT environment variable in module.""" txt = super(EB_NCL, self).make_module_extra() txt += self.module_generator.set_environment('NCARG_ROOT', self.installdir) return txt
tinyendian/eb_cray
easyblocks/ncl.py
Python
gpl-2.0
7,879
[ "NetCDF" ]
c3f6dff7f1b19e622d542803fb61cddbcf3850d7a47122dc5ad1115f9a875ed9
# Created by Eugene M. Izhikevich, 2003 Modified by S. Fusi 2007 # Ported to Python by Eilif Muller, 2008. # # Notes: # # Requires matplotlib,ipython,numpy>=1.0.3 # On a debian/ubuntu based system: # $ apt-get install python-matplotlib python-numpy ipython # # Start ipython with threaded plotting support: # $ ipython -pylab # # At the resulting prompt, run the file by: # In [1]: execfile('smallnet.py') # Modules required import numpy import numpy.random as random # Bug fix for numpy version 1.0.4 for numpy.histogram numpy.lib.function_base.any = numpy.any # For inline C optimization from scipy import weave # For measuring performance import time t1 = time.time() # Excitatory and inhibitory neuron counts Ne = 1000 Ni = 4 N = Ne+Ni # Synaptic couplings Je = 250.0/Ne Ji = 0.0 # Synaptic couplings (mV) #S = numpy.zeros((N,N)) #S[:,:Ne] = Je*random.uniform(size=(N,Ne)) #S[:,Ne:] = -Ji*random.uniform(size=(N,Ni)) # Connectivity #S[:,:Ne][random.uniform(size=(N,Ne))-0.9<=0.0]=0.0 #S[:,Ne:][random.uniform(size=(N,Ni))-0.9<=0.0]=0.0 # 10% Connectivity targets = [] weights = [] # excitatory for i in xrange(Ne): targets.append(random.permutation(numpy.arange(N))[:random.poisson(N*0.1)]) weights.append(Je*ones_like(targets[i])) # inhibitory for i in xrange(Ne,N): targets.append(random.permutation(numpy.arange(N))[:random.poisson(N*0.1)]) weights.append(-Ji*ones_like(targets[i])) # Statistics of the background external current #mb = 3.0; sb = 4.0 #mue = mb; sigmae=sb #sigmai = 0.0 # State variable v, initial value of 0 v = numpy.zeros(N) # Refractory period state variable r = numpy.zeros(N) # storage for intermediate calculations I = numpy.zeros(N) Isyn = numpy.zeros(N) # Spike timings in a list spikes = [[] for x in xrange(N)] #print 'mu(nu=5Hz)=%f' % (mb+Ne*Je*.015-leak,) #print 'mu(nu=100Hz)=%f' % (mb+Ne*Je*.1-leak,) # total duration of the simulation (ms) dt = 0.05 duration = 400.0 t = numpy.arange(0.0,duration,dt) vt = numpy.zeros_like(t) # This is inline C code c_code = """ const double mb = 3.0; const double sb = 4.0; double mue = mb; double sigmae = sb; double sigmai = 0.0; //double dt = 0.05; // (ms) double leak = 5.0; // (mV/ms) double sdt = sqrt(dt); double reset = 0.0; //(mV) double refr = 2.5; //(ms) double threshold = 20.0; //(mv) double Je = 250.0/Ne; double Ji = 0.0; int i,j,k; // GSL random number generation setup const gsl_rng_type * T_gsl; gsl_rng * r_gsl; gsl_rng_env_setup(); T_gsl = gsl_rng_default; r_gsl = gsl_rng_alloc (T_gsl); py::list l; for(i=0;i<Nt[0];i++) { // time for a strong external input if (t(i)>150.0) { mue = 6.5; sigmae = 7.5; } // time to restore the initial statistics of the external input if (t(i)>300.0) { mue = mb; sigmae = sb; } // Noise plus synaptic input from last step for (j=0;j<Ne;j++) { I(j)=sdt*sigmae*gsl_ran_gaussian(r_gsl,1.0)+Isyn(j); //I(j) = 0.0; Isyn(j)=0.0; } for (j=Ne;j<N;j++) { I(j)=sdt*sigmai*gsl_ran_gaussian(r_gsl,1.0)+Isyn(j); //I(j)=0.0; Isyn(j)=0.0; } // Euler's method for each neuron for (j=0;j<N;j++) { if (v(j)>=threshold) { l = py::list((PyObject*)(spikes[j])); l.append(t(i)); for (k=0;k<targets[j].size();k++) { Isyn(targets[j][k]) += (const double)weights[j][k]; } v(j) = reset; r(j) = refr; } if(r(j)<0) { I(j) -= dt*(leak-mue); v(j) +=I(j); v(j) = v(j)>=0.0 ? v(j) : 0.0; } else { r(j)-=dt; } } vt(i) = v(0); } // Clean-up the GSL random number generator gsl_rng_free (r_gsl); l = py::list((PyObject*)spikes[0]); l.append(3.0); """ t2 = time.time() print 'Elapsed time is ', str(t2-t1), ' seconds.' t1 = time.time() weave.inline(c_code, ['v','r','t','vt','dt', 'spikes','I','Isyn','Ne','Ni','N','targets','weights'], type_converters=weave.converters.blitz, headers = ["<gsl/gsl_rng.h>", "<gsl/gsl_randist.h>"], libraries = ["gsl","gslcblas"]) t2 = time.time() print 'Elapsed time is ', str(t2-t1), ' seconds.' def myplot(): global firings t1 = time.time() figure() # Membrane potential trace of the zeroeth neuron subplot(3,1,1) vt[vt>=20.0]=65.0 plot(t,vt) ylabel(r'$V-V_{rest}\ \left[\rm{mV}\right]$') # Raster plot of the spikes of the network subplot(3,1,2) myfirings = array(firings) myfirings_100 = myfirings[myfirings[:,0]<min(100,Ne)] plot(myfirings_100[:,1],myfirings_100[:,0],'.') axis([0, duration, 0, min(100,Ne)]) ylabel('Neuron index') # Mean firing rate of the excitatory population as a function of time subplot(3,1,3) # 1 ms resultion of rate histogram dx = 1.0 x = arange(0,duration,dx) myfirings_Ne = myfirings[myfirings[:,0]<Ne] mean_fe,x = numpy.histogram(myfirings_Ne[:,1],x) plot(x,mean_fe/dx/Ne*1000.0,ls='steps') ylabel('Hz') xlabel('time [ms]') t2 = time.time() print 'Finished. Elapsed', str(t2-t1), ' seconds.' #myplot()
meduz/NeuroTools
examples/matlab_vs_python/smallnet_inlineC.py
Python
gpl-2.0
5,107
[ "NEURON" ]
6e294de388db34053c9b2f1cf2788df9c159c18267a1e047b381986fdce11c14
"""Gaussian Mixture Model.""" # Author: Wei Xue <xuewei4d@gmail.com> # Modified by Thierry Guillemot <thierry.guillemot.work@gmail.com> import numpy as np from scipy import linalg from .base import BaseMixture, _check_shape from ..externals.six.moves import zip from ..utils import check_array from ..utils.validation import check_is_fitted ############################################################################### # Gaussian mixture shape checkers used by the GaussianMixture class def _check_weights(weights, n_components): """Check the user provided 'weights'. Parameters ---------- weights : array-like, shape (n_components,) The proportions of components of each mixture. n_components : int Number of components. Returns ------- weights : array, shape (n_components,) """ weights = check_array(weights, dtype=[np.float64, np.float32], ensure_2d=False) _check_shape(weights, (n_components,), 'weights') # check range if (any(np.less(weights, 0)) or any(np.greater(weights, 1))): raise ValueError("The parameter 'weights' should be in the range " "[0, 1], but got max value %.5f, min value %.5f" % (np.min(weights), np.max(weights))) # check normalization if not np.allclose(np.abs(1 - np.sum(weights)), 0.0): raise ValueError("The parameter 'weights' should be normalized, " "but got sum(weights) = %.5f" % np.sum(weights)) return weights def _check_means(means, n_components, n_features): """Validate the provided 'means'. Parameters ---------- means : array-like, shape (n_components, n_features) The centers of the current components. n_components : int Number of components. n_features : int Number of features. Returns ------- means : array, (n_components, n_features) """ means = check_array(means, dtype=[np.float64, np.float32], ensure_2d=False) _check_shape(means, (n_components, n_features), 'means') return means def _check_covariance_matrix(covariance, covariance_type): """Check a covariance matrix is symmetric and positive-definite.""" if (not np.allclose(covariance, covariance.T) or np.any(np.less_equal(linalg.eigvalsh(covariance), .0))): raise ValueError("'%s covariance' should be symmetric, " "positive-definite" % covariance_type) def _check_covariance_positivity(covariance, covariance_type): """Check a covariance vector is positive-definite.""" if np.any(np.less_equal(covariance, 0.0)): raise ValueError("'%s covariance' should be " "positive" % covariance_type) def _check_covariances_full(covariances, covariance_type): """Check the covariance matrices are symmetric and positive-definite.""" for k, cov in enumerate(covariances): _check_covariance_matrix(cov, covariance_type) def _check_covariances(covariances, covariance_type, n_components, n_features): """Validate user provided covariances. Parameters ---------- covariances : array-like, 'full' : shape of (n_components, n_features, n_features) 'tied' : shape of (n_features, n_features) 'diag' : shape of (n_components, n_features) 'spherical' : shape of (n_components,) covariance_type : string n_components : int Number of components. n_features : int Number of features. Returns ------- covariances : array """ covariances = check_array(covariances, dtype=[np.float64, np.float32], ensure_2d=False, allow_nd=covariance_type is 'full') covariances_shape = {'full': (n_components, n_features, n_features), 'tied': (n_features, n_features), 'diag': (n_components, n_features), 'spherical': (n_components,)} _check_shape(covariances, covariances_shape[covariance_type], '%s covariance' % covariance_type) check_functions = {'full': _check_covariances_full, 'tied': _check_covariance_matrix, 'diag': _check_covariance_positivity, 'spherical': _check_covariance_positivity} check_functions[covariance_type](covariances, covariance_type) return covariances ############################################################################### # Gaussian mixture parameters estimators (used by the M-Step) def _estimate_gaussian_covariance_full(resp, X, nk, means, reg_covar): """Estimate the full covariance matrices. Parameters ---------- resp : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_components, n_features, n_features) """ n_features = X.shape[1] n_components = means.shape[0] covariances = np.empty((n_components, n_features, n_features)) for k in range(n_components): diff = X - means[k] covariances[k] = np.dot(resp[:, k] * diff.T, diff) / nk[k] covariances[k].flat[::n_features + 1] += reg_covar return covariances def _estimate_gaussian_covariance_tied(resp, X, nk, means, reg_covar): """Estimate the tied covariance matrix. Parameters ---------- resp : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_features, n_features) """ avg_X2 = np.dot(X.T, X) avg_means2 = np.dot(nk * means.T, means) covariances = avg_X2 - avg_means2 covariances /= X.shape[0] covariances.flat[::len(covariances) + 1] += reg_covar return covariances def _estimate_gaussian_covariance_diag(resp, X, nk, means, reg_covar): """Estimate the diagonal covariance matrices. Parameters ---------- responsibilities : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_components, n_features) """ avg_X2 = np.dot(resp.T, X * X) / nk[:, np.newaxis] avg_means2 = means ** 2 avg_X_means = means * np.dot(resp.T, X) / nk[:, np.newaxis] return avg_X2 - 2 * avg_X_means + avg_means2 + reg_covar def _estimate_gaussian_covariance_spherical(resp, X, nk, means, reg_covar): """Estimate the spherical covariance matrices. Parameters ---------- responsibilities : array-like, shape (n_samples, n_components) X : array-like, shape (n_samples, n_features) nk : array-like, shape (n_components,) means : array-like, shape (n_components, n_features) reg_covar : float Returns ------- covariances : array, shape (n_components,) """ covariances = _estimate_gaussian_covariance_diag(resp, X, nk, means, reg_covar) return covariances.mean(axis=1) def _estimate_gaussian_parameters(X, resp, reg_covar, covariance_type): """Estimate the Gaussian distribution parameters. Parameters ---------- X : array-like, shape (n_samples, n_features) The input data array. resp : array-like, shape (n_samples, n_features) The responsibilities for each data sample in X. reg_covar : float The regularization added to each covariance matrices. covariance_type : {'full', 'tied', 'diag', 'spherical'} The type of covariance matrices. Returns ------- nk : array, shape (n_components,) The numbers of data samples in the current components. means : array, shape (n_components, n_features) The centers of the current components. covariances : array The sample covariances of the current components. The shape depends of the covariance_type. """ compute_covariance = { "full": _estimate_gaussian_covariance_full, "tied": _estimate_gaussian_covariance_tied, "diag": _estimate_gaussian_covariance_diag, "spherical": _estimate_gaussian_covariance_spherical} nk = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps means = np.dot(resp.T, X) / nk[:, np.newaxis] covariances = compute_covariance[covariance_type]( resp, X, nk, means, reg_covar) return nk, means, covariances ############################################################################### # Gaussian mixture probability estimators def _estimate_log_gaussian_prob_full(X, means, covariances): """Estimate the log Gaussian probability for 'full' covariance. Parameters ---------- X : array-like, shape (n_samples, n_features) means : array-like, shape (n_components, n_features) covariances : array-like, shape (n_components, n_features, n_features) Returns ------- log_prob : array, shape (n_samples, n_components) """ n_samples, n_features = X.shape n_components = means.shape[0] log_prob = np.empty((n_samples, n_components)) for k, (mu, cov) in enumerate(zip(means, covariances)): try: cov_chol = linalg.cholesky(cov, lower=True) except linalg.LinAlgError: raise ValueError("The algorithm has diverged because of too " "few samples per components. " "Try to decrease the number of components, or " "increase reg_covar.") cv_log_det = 2. * np.sum(np.log(np.diagonal(cov_chol))) cv_sol = linalg.solve_triangular(cov_chol, (X - mu).T, lower=True).T log_prob[:, k] = - .5 * (n_features * np.log(2. * np.pi) + cv_log_det + np.sum(np.square(cv_sol), axis=1)) return log_prob def _estimate_log_gaussian_prob_tied(X, means, covariances): """Estimate the log Gaussian probability for 'tied' covariance. Parameters ---------- X : array-like, shape (n_samples, n_features) means : array-like, shape (n_components, n_features) covariances : array-like, shape (n_features, n_features) Returns ------- log_prob : array-like, shape (n_samples, n_components) """ n_samples, n_features = X.shape n_components = means.shape[0] log_prob = np.empty((n_samples, n_components)) try: cov_chol = linalg.cholesky(covariances, lower=True) except linalg.LinAlgError: raise ValueError("The algorithm has diverged because of too " "few samples per components. " "Try to decrease the number of components, or " "increase reg_covar.") cv_log_det = 2. * np.sum(np.log(np.diagonal(cov_chol))) for k, mu in enumerate(means): cv_sol = linalg.solve_triangular(cov_chol, (X - mu).T, lower=True).T log_prob[:, k] = np.sum(np.square(cv_sol), axis=1) log_prob = - .5 * (n_features * np.log(2. * np.pi) + cv_log_det + log_prob) return log_prob def _estimate_log_gaussian_prob_diag(X, means, covariances): """Estimate the log Gaussian probability for 'diag' covariance. Parameters ---------- X : array-like, shape (n_samples, n_features) means : array-like, shape (n_components, n_features) covariances : array-like, shape (n_components, n_features) Returns ------- log_prob : array-like, shape (n_samples, n_components) """ if np.any(np.less_equal(covariances, 0.0)): raise ValueError("The algorithm has diverged because of too " "few samples per components. " "Try to decrease the number of components, or " "increase reg_covar.") n_samples, n_features = X.shape log_prob = - .5 * (n_features * np.log(2. * np.pi) + np.sum(np.log(covariances), 1) + np.sum((means ** 2 / covariances), 1) - 2. * np.dot(X, (means / covariances).T) + np.dot(X ** 2, (1. / covariances).T)) return log_prob def _estimate_log_gaussian_prob_spherical(X, means, covariances): """Estimate the log Gaussian probability for 'spherical' covariance. Parameters ---------- X : array-like, shape (n_samples, n_features) means : array-like, shape (n_components, n_features) covariances : array-like, shape (n_components, ) Returns ------- log_prob : array-like, shape (n_samples, n_components) """ if np.any(np.less_equal(covariances, 0.0)): raise ValueError("The algorithm has diverged because of too " "few samples per components. " "Try to decrease the number of components, or " "increase reg_covar.") n_samples, n_features = X.shape log_prob = - .5 * (n_features * np.log(2 * np.pi) + n_features * np.log(covariances) + np.sum(means ** 2, 1) / covariances - 2 * np.dot(X, means.T / covariances) + np.outer(np.sum(X ** 2, axis=1), 1. / covariances)) return log_prob class GaussianMixture(BaseMixture): """Gaussian Mixture. Representation of a Gaussian mixture model probability distribution. This class allows to estimate the parameters of a Gaussian mixture distribution. Parameters ---------- n_components : int, defaults to 1. The number of mixture components. covariance_type : {'full', 'tied', 'diag', 'spherical'}, defaults to 'full'. String describing the type of covariance parameters to use. Must be one of:: 'full' (each component has its own general covariance matrix). 'tied' (all components share the same general covariance matrix), 'diag' (each component has its own diagonal covariance matrix), 'spherical' (each component has its own single variance), tol : float, defaults to 1e-3. The convergence threshold. EM iterations will stop when the log_likelihood average gain is below this threshold. reg_covar : float, defaults to 0. Non-negative regularization added to the diagonal of covariance. Allows to assure that the covariance matrices are all positive. max_iter : int, defaults to 100. The number of EM iterations to perform. n_init : int, defaults to 1. The number of initializations to perform. The best results is kept. init_params : {'kmeans', 'random'}, defaults to 'kmeans'. The method used to initialize the weights, the means and the covariances. Must be one of:: 'kmeans' : responsibilities are initialized using kmeans. 'random' : responsibilities are initialized randomly. weights_init : array-like, shape (n_components, ), optional The user-provided initial weights, defaults to None. If it None, weights are initialized using the `init_params` method. means_init: array-like, shape (n_components, n_features), optional The user-provided initial means, defaults to None, If it None, means are initialized using the `init_params` method. covariances_init: array-like, optional. The user-provided initial covariances, defaults to None. If it None, covariances are initialized using the 'init_params' method. The shape depends on 'covariance_type':: (n_components,) if 'spherical', (n_features, n_features) if 'tied', (n_components, n_features) if 'diag', (n_components, n_features, n_features) if 'full' random_state: RandomState or an int seed, defaults to None. A random number generator instance. warm_start : bool, default to False. If 'warm_start' is True, the solution of the last fitting is used as initialization for the next call of fit(). This can speed up convergence when fit is called several time on similar problems. verbose : int, default to 0. Enable verbose output. If 1 then it prints the current initialization and each iteration step. If greater than 1 then it prints also the log probability and the time needed for each step. Attributes ---------- weights_ : array, shape (n_components,) The weights of each mixture components. `weights_` will not exist before a call to fit. means_ : array, shape (n_components, n_features) The mean of each mixture component. `means_` will not exist before a call to fit. covariances_ : array The covariance of each mixture component. The shape depends on `covariance_type`:: (n_components,) if 'spherical', (n_features, n_features) if 'tied', (n_components, n_features) if 'diag', (n_components, n_features, n_features) if 'full' `covariances_` will not exist before a call to fit. converged_ : bool True when convergence was reached in fit(), False otherwise. `converged_` will not exist before a call to fit. n_iter_ : int Number of step used by the best fit of EM to reach the convergence. `n_iter_` will not exist before a call to fit. """ def __init__(self, n_components=1, covariance_type='full', tol=1e-3, reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans', weights_init=None, means_init=None, covariances_init=None, random_state=None, warm_start=False, verbose=0, verbose_interval=10): super(GaussianMixture, self).__init__( n_components=n_components, tol=tol, reg_covar=reg_covar, max_iter=max_iter, n_init=n_init, init_params=init_params, random_state=random_state, warm_start=warm_start, verbose=verbose, verbose_interval=verbose_interval) self.covariance_type = covariance_type self.weights_init = weights_init self.means_init = means_init self.covariances_init = covariances_init def _check_parameters(self, X): """Check the Gaussian mixture parameters are well defined.""" if self.covariance_type not in ['spherical', 'tied', 'diag', 'full']: raise ValueError("Invalid value for 'covariance_type': %s " "'covariance_type' should be in " "['spherical', 'tied', 'diag', 'full']" % self.covariance_type) if self.weights_init is not None: self.weights_init = _check_weights(self.weights_init, self.n_components) if self.means_init is not None: self.means_init = _check_means(self.means_init, self.n_components, X.shape[1]) if self.covariances_init is not None: self.covariances_init = _check_covariances(self.covariances_init, self.covariance_type, self.n_components, X.shape[1]) def _initialize(self, X, resp): """Initialization of the Gaussian mixture parameters. Parameters ---------- X : array-like, shape (n_samples, n_features) resp : array-like, shape (n_samples, n_components) """ weights, means, covariances = _estimate_gaussian_parameters( X, resp, self.reg_covar, self.covariance_type) weights /= X.shape[0] self.weights_ = (weights if self.weights_init is None else self.weights_init) self.means_ = means if self.means_init is None else self.means_init self.covariances_ = (covariances if self.covariances_init is None else self.covariances_init) def _e_step(self, X): log_prob_norm, _, log_resp = self._estimate_log_prob_resp(X) return np.mean(log_prob_norm), np.exp(log_resp) def _m_step(self, X, resp): self.weights_, self.means_, self.covariances_ = ( _estimate_gaussian_parameters(X, resp, self.reg_covar, self.covariance_type)) self.weights_ /= X.shape[0] def _estimate_log_prob(self, X): estimate_log_prob_functions = { "full": _estimate_log_gaussian_prob_full, "tied": _estimate_log_gaussian_prob_tied, "diag": _estimate_log_gaussian_prob_diag, "spherical": _estimate_log_gaussian_prob_spherical } return estimate_log_prob_functions[self.covariance_type]( X, self.means_, self.covariances_) def _estimate_log_weights(self): return np.log(self.weights_) def _check_is_fitted(self): check_is_fitted(self, ['weights_', 'means_', 'covariances_']) def _get_parameters(self): return self.weights_, self.means_, self.covariances_ def _set_parameters(self, params): self.weights_, self.means_, self.covariances_ = params def _n_parameters(self): """Return the number of free parameters in the model.""" ndim = self.means_.shape[1] if self.covariance_type == 'full': cov_params = self.n_components * ndim * (ndim + 1) / 2. elif self.covariance_type == 'diag': cov_params = self.n_components * ndim elif self.covariance_type == 'tied': cov_params = ndim * (ndim + 1) / 2. elif self.covariance_type == 'spherical': cov_params = self.n_components mean_params = ndim * self.n_components return int(cov_params + mean_params + self.n_components - 1) def bic(self, X): """Bayesian information criterion for the current model on the input X. Parameters ---------- X : array of shape (n_samples, n_dimensions) Returns ------- bic: float The greater the better. """ return (-2 * self.score(X) * X.shape[0] + self._n_parameters() * np.log(X.shape[0])) def aic(self, X): """Akaike information criterion for the current model on the input X. Parameters ---------- X : array of shape(n_samples, n_dimensions) Returns ------- aic: float The greater the better. """ return -2 * self.score(X) * X.shape[0] + 2 * self._n_parameters()
olologin/scikit-learn
sklearn/mixture/gaussian_mixture.py
Python
bsd-3-clause
23,400
[ "Gaussian" ]
cee42dd83cbc40a117be283360ba1c98596619940ff523203067184fe727ced5
'''cgat_logfiles2tsv.py - create summary from logfiles =================================================== Purpose ------- This script takes a list of logfiles and collates summary information about execution times. This can be useful for post-mortem benchmark analysis. This script uses the ``# job finished`` tag that is added by scripts using the module :mod:`CGAT.Experiment`. Usage ----- To collect logfile information from all files matching the pattern ``bwa.dir/mC-juvenile-stressed-R[12]*.log``, type:: python cgat_logfiles2tsv.py --glob="bwa.dir/mC-juvenile-stressed-R[12]*.log" to receive output such as this:: file chunks wall user sys cuser csys bwa.dir/mC-juvenile-stressed-R2.bwa.bam.log 2 2552.00 1563.91 13.73 0.00 0.04 bwa.dir/mC-juvenile-stressed-R2.bwa.bw.log 1 2068.00 170.66 4.50 237.51 1194.92 bwa.dir/mC-juvenile-stressed-R1.bwa.bam.log 2 1378.00 762.52 9.90 0.00 0.04 bwa.dir/mC-juvenile-stressed-R1.bwa.contextstats.log 1 948.00 150.21 2.13 726.00 7.92 bwa.dir/mC-juvenile-stressed-R2.bwa.contextstats.log 1 935.00 137.00 2.26 775.07 8.35 bwa.dir/mC-juvenile-stressed-R1.bwa.bw.log 1 2150.00 159.64 4.12 214.59 1566.41 total 8 10031.00 2943.94 36.64 1953.17 2777.68 The output lists for each file how often it was executed (``chunks``) and the total execution time in terms of wall clock time, user time, system time, child process user time and child process system time. The last line contains the sum total. Type:: python cgat_logfiles2tsv.py --help for command line help. Command line options -------------------- ''' import sys import re import gzip import glob import CGAT.Experiment as E import CGAT.Logfile as Logfile def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser( version="%prog version: $Id$", usage=globals()["__doc__"]) parser.add_option( "-g", "--glob", dest="glob_pattern", type="string", help="glob pattern to use for collecting files [%default].") parser.add_option( "-f", "--file-pattern", dest="file_pattern", type="string", help="only check files matching this pattern [%default].") parser.add_option("-m", "--mode", dest="mode", type="choice", choices=("file", "node"), help="analysis mode [%default].") parser.add_option( "-r", "--recursive", action="store_true", help="recursively look for logfiles from current directory " "[%default].") parser.set_defaults( truncate_sites_list=0, glob_pattern="*.log", mode="file", recursive=False, ) (options, args) = E.Start(parser) if args: filenames = args elif options.glob_pattern: filenames = glob.glob(options.glob_pattern) if len(filenames) == 0: raise ValueError("no files to analyse") if options.mode == "file": totals = Logfile.LogFileData() options.stdout.write("file\t%s\n" % totals.getHeader()) for filename in filenames: if filename == "-": infile = sys.stdin elif filename[-3:] == ".gz": infile = gzip.open(filename, "r") else: infile = open(filename, "r") subtotals = Logfile.LogFileData() for line in infile: subtotals.add(line) infile.close() options.stdout.write("%s\t%s\n" % (filename, str(subtotals))) totals += subtotals options.stdout.write("%s\t%s\n" % ("total", str(totals))) elif options.mode == "node": chunks_per_node = {} rx_node = re.compile("# job started at .* \d+ on (\S+)") for filename in filenames: if filename == "-": infile = sys.stdin elif filename[-3:] == ".gz": infile = gzip.open(filename, "r") else: infile = open(filename, "r") data = Logfile.LogFileDataLines() for line in infile: if rx_node.match(line): node_id = rx_node.match(line).groups()[0] data = Logfile.LogFileDataLines() if node_id not in chunks_per_node: chunks_per_node[node_id] = [] chunks_per_node[node_id].append(data) continue data.add(line) options.stdout.write("node\t%s\n" % data.getHeader()) total = Logfile.LogFileDataLines() for node, data in sorted(chunks_per_node.items()): subtotal = Logfile.LogFileDataLines() for d in data: # options.stdout.write( "%s\t%s\n" % (node, str(d) ) ) subtotal += d options.stdout.write("%s\t%s\n" % (node, str(subtotal))) total += subtotal options.stdout.write("%s\t%s\n" % ("total", str(total))) E.Stop() if __name__ == "__main__": sys.exit(main(sys.argv))
AntonioJBT/CGATPipeline_core
scripts/cgat_logfiles2tsv.py
Python
mit
5,268
[ "BWA" ]
e1cc312e2fdba2ff5bc9252ce9a93d29ac39aa2d2647ee2cce8621860516cd37
from flask import Flask from flask.ext.httpauth import HTTPBasicAuth app = Flask(__name__) auth = HTTPBasicAuth() host_cert_file = "/opt/dirac/etc/grid-security/hostcert.pem" host_key_file = "/opt/dirac/etc/grid-security/hostkey.pem" port = 5010 users = { "john": "hello", "susan": "bye" } @auth.get_password def get_pw(username): if username in users: return users[username] return None @app.route('/DIRAC/') def hello_world(): return 'Hello World!' @app.route('/DIRAC/galaxy', methods=['GET', 'POST']) @auth.login_required def galaxy_token(): print auth print dir(auth) return 'galaxy token, %s' % auth.username() if __name__ == '__main__': #app.run('0.0.0.0', debug=True, port=5000, ssl_context='adhoc') #app.run('0.0.0.0', debug=True, port=5000, ssl_context=(host_cert_file, host_key_file)) app.run('0.0.0.0', port=port, ssl_context=(host_cert_file, host_key_file))
SuperDIRAC/TESTDIRAC
WebServerSystem/tmpdir/xalfonso/ora-server.py
Python
gpl-3.0
935
[ "DIRAC", "Galaxy" ]
40b8cf30949ca990fff5eeb5d04b06e1d1be8ea60090de4f30a5e238fa5964e7
"""Simple molecular dynamics. A block of 27 cubic unit cells of Cu is set up, a single atom is given a significant momentum, and constant energy molecular dynamics is performed. """ from numpy import * from asap3 import Atoms, EMT, units from ase.lattice.cubic import FaceCenteredCubic from asap3.md.verlet import VelocityVerlet # Create the atoms atoms = FaceCenteredCubic(size=(3,3,3), symbol="Cu", pbc=False) # Give the first atom a non-zero momentum atoms[0].momentum = array([0, -11.3, 0]) print("Kinetic energies of all atoms:") p = atoms.get_momenta() kinenergies = 0.5 * (p * p).sum(1) / atoms.get_masses() print(kinenergies) # Associate the EMT potential with the atoms atoms.set_calculator(EMT()) # Now do molecular dynamics, printing kinetic, potential and total # energy every ten timesteps. dyn = VelocityVerlet(atoms, 5.0*units.fs) print("") print("Energy per atom:") print(" %15s %15s %15s" % ("Pot. energy", "Kin. energy", "Total energy")) for i in range(25): dyn.run(10) epot = atoms.get_potential_energy()/len(atoms) ekin = atoms.get_kinetic_energy()/len(atoms) print("%15.5f %15.5f %15.5f" % (epot, ekin, epot+ekin))
miroi/open-collection
theoretical_chemistry/software_runs/ase/runs/simple_md_asap3/SimpleMD.py
Python
mit
1,162
[ "ASE" ]
d7965bb917f44c587eb70f1506c6bbedea843f71b11475d7aea525939c0c130a
from ..c import nodes as C import ast op_map = { C.Op.Add: lambda x, y: x + y, C.Op.Div: lambda x, y: x / y, C.Op.Mul: lambda x, y: x * y, C.Op.Lt: lambda x, y: x < y, C.Op.Sub: lambda x, y: x - y, } class ConstantFold(ast.NodeTransformer): """ TODO: Support all folding situations """ def fold_add(self, node): if isinstance(node.left, C.Constant) and node.left.value == 0: return node.right elif isinstance(node.right, C.Constant) and node.right.value == 0: return node.left return node def fold_sub(self, node): if isinstance(node.left, C.Constant) and node.left.value == 0: return C.Sub(node.right) elif isinstance(node.right, C.Constant) and node.right.value == 0: return node.left return node def fold_mul(self, node): if isinstance(node.left, C.Constant) and node.left.value == 1: return node.right elif isinstance(node.right, C.Constant) and node.right.value == 1: return node.left elif isinstance(node.left, C.Constant) and node.left.value == 0: return node.left elif isinstance(node.right, C.Constant) and node.right.value == 0: return node.right return node def visit_BinaryOp(self, node): node.left = self.visit(node.left) node.right = self.visit(node.right) if isinstance(node.left, C.Constant) and \ isinstance(node.right, C.Constant): return C.Constant(op_map[node.op.__class__]( node.left.value, node.right.value)) elif isinstance(node.op, C.Op.Add): return self.fold_add(node) elif isinstance(node.op, C.Op.Sub): return self.fold_sub(node) elif isinstance(node.op, C.Op.Mul): return self.fold_mul(node) return node
alphaFred/Sejits4Fpgas
sejits4fpgas/src/vhdl_ctree/transforms/constant_fold.py
Python
gpl-3.0
1,899
[ "VisIt" ]
eebdcc8cb7e1a586e2c8e2b4fb80ab5b43f1fa0afabe47a0c18efb93b54b1f19
# Copyright (C) 2010-2018 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 unittest as ut import numpy as np import espressomd class AnalyzeITensor(ut.TestCase): """Test the inertia tensor analysis""" box_l = 50.0 system = espressomd.System(box_l=[box_l, box_l, box_l]) np.random.seed(seed=123) @classmethod def setUpClass(cls): cls.system.cell_system.skin = 0.4 cls.system.time_step = 0.01 cls.system.thermostat.turn_off() for i in range(10): cls.system.part.add( id=i, pos=np.random.random(3) * cls.box_l, type=0) for i in range(20, 30, 1): cls.system.part.add( id=i, pos=np.random.random(3) * cls.box_l, type=1) if espressomd.has_features("MASS"): cls.system.part[:].mass = 0.5 + np.random.random(20) def i_tensor(self, ids): pslice = self.system.part[ids] I = np.zeros((3, 3)) # Center of mass com = np.zeros(3) for p in pslice: com += p.mass * p.pos com /= np.sum(pslice.mass) # Eqn from # https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor for p in pslice: I += p.mass * \ (np.dot(p.pos - com, p.pos - com) * np.identity(3) - np.outer(p.pos - com, p.pos - com)) return I def test(self): # Particles of type 0 I0 = self.i_tensor(range(0, 10, 1)) np.testing.assert_allclose( I0, self.system.analysis.moment_of_inertia_matrix(p_type=0), atol=1E-9) # type=1 I1 = self.i_tensor(range(20, 30, 1)) self.assertTrue( np.allclose(I1, self.system.analysis.moment_of_inertia_matrix(p_type=1), atol=1E-9)) if __name__ == "__main__": ut.main()
mkuron/espresso
testsuite/python/analyze_itensor.py
Python
gpl-3.0
2,464
[ "ESPResSo" ]
7e7d3cb5f577bed1400c902eb77abcc96b6eadbc12959f4ee053f30790554592
import sys, shutil sys.path.insert(1, "../../../") import h2o import random def cars_checkpoint(ip,port): cars = h2o.upload_file(h2o.locate("smalldata/junit/cars_20mpg.csv")) s = cars.runif() train = cars[s > .2] valid = cars[s <= .2] print "\n*** Description (chunk distribution, etc) of training frame:" train.describe() print "\n*** Description (chunk distribution, etc) of validation frame:" valid.describe() # choose the type model-building exercise (multinomial classification or regression). 0:regression, 1:binomial, # 2:multinomial problem = random.sample(range(3),1)[0] # pick the predictors and response column, along with the correct distribution predictors = ["displacement","power","weight","acceleration","year"] if problem == 1 : response_col = "economy_20mpg" distribution = "bernoulli" train[response_col] = train[response_col].asfactor() valid[response_col] = valid[response_col].asfactor() elif problem == 2 : response_col = "cylinders" distribution = "multinomial" train[response_col] = train[response_col].asfactor() valid[response_col] = valid[response_col].asfactor() else : response_col = "economy" distribution = "gaussian" print "\n*** Distribution: {0}".format(distribution) print "\n*** Response column: {0}".format(response_col) # build first model ntrees1 = 5 max_depth1 = random.sample(range(2,6),1)[0] min_rows1 = random.sample(range(10,16),1)[0] print "\n*** Building model 1 with the following parameters:" print "*** ntrees model 1: {0}".format(ntrees1) print "*** max_depth model 1: {0}".format(max_depth1) print "*** min_rows model 1: {0}".format(min_rows1) model1 = h2o.gbm(x=train[predictors], y=train[response_col], ntrees=ntrees1, max_depth=max_depth1, min_rows=min_rows1, score_each_iteration=True, distribution=distribution, validation_x=valid[predictors], validation_y=valid[response_col]) # save the model, then load the model model_path = h2o.save_model(model1, name="delete_model", force=True) restored_model = h2o.load_model(model_path) shutil.rmtree("delete_model") # continue building the model ntrees2 = ntrees1 + 5 max_depth2 = max_depth1 min_rows2 = min_rows1 print "\n*** Continuing to build model 1 (now called model 2) with the following parameters:" print "*** ntrees model 2: {0}".format(ntrees2) print "*** max_depth model 2: {0}".format(max_depth2) print "*** min_rows model 2: {0}".format(min_rows2) model2 = h2o.gbm(x=train[predictors], y=train[response_col], ntrees=ntrees2, max_depth=max_depth2, min_rows=min_rows2, distribution=distribution, score_each_iteration=True, validation_x=valid[predictors], validation_y=valid[response_col], checkpoint=restored_model._id) # continue building the model, but with different number of trees ntrees3 = ntrees2 + 50 max_depth3 = max_depth1 min_rows3 = min_rows1 print "\n*** Continuing to build model 1 (now called model 3) with the following parameters:" print "*** ntrees model 3: {0}".format(ntrees3) print "*** max_depth model 3: {0}".format(max_depth3) print "*** min_rows model 3: {0}".format(min_rows3) model3 = h2o.gbm(x=train[predictors], y=train[response_col], ntrees=ntrees3, max_depth=max_depth3, min_rows=min_rows3, distribution=distribution, score_each_iteration=True, validation_x=valid[predictors], validation_y=valid[response_col], checkpoint=restored_model._id) # build the equivalent of model 2 in one shot print "\n*** Building the equivalent of model 2 (called model 4) in one shot:" model4 = h2o.gbm(x=train[predictors], y=train[response_col], ntrees=ntrees2, max_depth=max_depth2, min_rows=min_rows2, distribution=distribution, score_each_iteration=True, validation_x=valid[predictors], validation_y=valid[response_col]) print "\n*** Model Summary for model 2:" print model2.summary() print "\n*** Model Summary for model 3:" print model3.summary() print "\n*** Model Summary for model 4:" print model4.summary() print "\n*** Score History for model 2:" print model2.score_history() print "\n*** Score History for model 3:" print model3.score_history() print "\n*** Score History for model 4:" print model4.score_history() # checks if problem == 0: assert isinstance(model2,type(model4)) assert model2.mse(valid=True)==model4.mse(valid=True), "Expected Model 2 MSE: {0} to be the same as Model 4 MSE: {1}".format(model2.mse(valid=True), model4.mse(valid=True)) #assert model3.mse(valid=True)!=model4.mse(valid=True), "Expected Model 3 MSE: {0} to be different from Model 4 MSE: {1}".format(model3.mse(valid=True), model4.mse(valid=True)) elif problem == 1: assert isinstance(model2,type(model4)) assert model2.auc(valid=True)==model4.auc(valid=True), "Expected Model 2 AUC: {0} to be the same as Model 4 AUC: {1}".format(model2.auc(valid=True), model4.auc(valid=True)) #assert model3.auc(valid=True)!=model4.auc(valid=True), "Expected Model 3 AUC: {0} to be different from Model 4 AUC: {1}".format(model3.auc(valid=True), model4.auc(valid=True)) assert model2.logloss(valid=True)==model4.logloss(valid=True), "Expected Model 2 Log Loss: {0} to be the same as Model 4 Log Loss: {1}".format(model2.logloss(valid=True), model4.logloss(valid=True)) #assert model3.logloss(valid=True)!=model4.logloss(valid=True), "Expected Model 3 Log Loss: {0} to be different from Model 4 Log Loss: {1}".format(model2.logloss(valid=True), model4.logloss(valid=True)) assert model2.giniCoef(valid=True)==model4.giniCoef(valid=True), "Expected Model 2 Gini Coef {0} to be the same as Model 4 Gini Coef: {1}".format(model2.giniCoef(valid=True), model4.giniCoef(valid=True)) #assert model3.giniCoef(valid=True)!=model4.giniCoef(valid=True), "Expected Model 3 Gini Coef: {0} to be different from Model 4 Gini Coef: {1}".format(model2.giniCoef(valid=True), model4.giniCoef(valid=True)) else: assert isinstance(model2,type(model4)) assert model2.mse(valid=True)==model4.mse(valid=True), "Expected Model 2 MSE: {0} to be the same as Model 4 MSE: {1}".format(model2.mse(valid=True), model4.mse(valid=True)) #assert model3.mse(valid=True)!=model4.mse(valid=True), "Expected Model 3 MSE: {0} to be different from Model 4 MSE: {1}".format(model3.mse(valid=True), model4.mse(valid=True)) assert model2.r2(valid=True)==model4.r2(valid=True), "Expected Model 2 R2: {0} to be the same as Model 4 R2: {1}".format(model2.r2(valid=True), model4.r2(valid=True)) #assert model3.r2(valid=True)!=model4.r2(valid=True), "Expected Model 3 R2: {0} to be different from Model 4 R2: {1}".format(model3.r2(valid=True), model4.r2(valid=True)) if __name__ == "__main__": h2o.run_test(sys.argv, cars_checkpoint)
weaver-viii/h2o-3
h2o-py/tests/testdir_algos/gbm/pyunit_NOPASS_cars_checkpointGBM.py
Python
apache-2.0
7,714
[ "Gaussian" ]
3a71b484ff7c5dad57b6ea3f84a59076b101855eacb7426a7f189a8534baa741
#!/usr/bin/env python """ """ import os import vtk def main(): colors = vtk.vtkNamedColors() fileNames = get_program_parameters() # Set up the stocks renderers = list() topRenderer = vtk.vtkRenderer() bottomRenderer = vtk.vtkRenderer() renderers.append(topRenderer) renderers.append(bottomRenderer) zPosition = 0.0 for fn in fileNames: zPosition = AddStock(renderers, fn, os.path.basename((os.path.splitext(fn)[0])), zPosition) # Setup the render window and interactor. renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderers[0]) renderWindow.AddRenderer(renderers[1]) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderers[0].SetViewport(0.0, 0.4, 1.0, 1.0) renderers[1].SetViewport(0.0, 0.0, 1.0, 0.4) renderers[0].GetActiveCamera().SetViewAngle(5.0) renderers[0].ResetCamera() renderers[0].GetActiveCamera().Zoom(1.4) renderers[0].ResetCameraClippingRange() renderers[0].SetBackground(colors.GetColor3d("SteelBlue")) renderers[1].GetActiveCamera().SetViewUp(0, 0, -1) renderers[1].GetActiveCamera().SetPosition(0, 1, 0) renderers[1].GetActiveCamera().SetViewAngle(5.0) renderers[1].ResetCamera() renderers[1].GetActiveCamera().Zoom(2.2) renderers[1].ResetCameraClippingRange() renderers[1].SetBackground(colors.GetColor3d("LightSteelBlue")) renderWindow.SetSize(500, 800) renderWindow.Render() renderWindowInteractor.Start() def get_program_parameters(): import argparse description = 'Two views from the stock visualization script.' epilogue = ''' The top shows closing price over time; the bottom shows volume over time. ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('filenames', nargs='+', help='List of one or more filenames corresponding to stocks.') args = parser.parse_args() return args.filenames def AddStock(renderers, filename, name, zPosition): print("Adding", name) # Read the data PolyDataRead = vtk.vtkPolyDataReader() PolyDataRead.SetFileName(filename) PolyDataRead.Update() # Create the labels. TextSrc = vtk.vtkVectorText() TextSrc.SetText(name) numberOfPoints = PolyDataRead.GetOutput().GetNumberOfPoints() nameIndex = int((numberOfPoints - 1) * 0.8) nameLocation = PolyDataRead.GetOutput().GetPoint(nameIndex) x = nameLocation[0] * 0.15 y = nameLocation[1] + 5.0 z = zPosition RibbonFilter = vtk.vtkRibbonFilter() RibbonFilter.SetInputConnection(PolyDataRead.GetOutputPort()) RibbonFilter.VaryWidthOn() RibbonFilter.SetWidthFactor(5) RibbonFilter.SetDefaultNormal(0, 1, 0) RibbonFilter.UseDefaultNormalOn() Extrude = vtk.vtkLinearExtrusionFilter() Extrude.SetInputConnection(RibbonFilter.GetOutputPort()) Extrude.SetVector(0, 1, 0) Extrude.SetExtrusionType(1) Extrude.SetScaleFactor(0.7) Transform = vtk.vtkTransform() Transform.Translate(0, 0, zPosition) Transform.Scale(0.15, 1, 1) TransformFilter = vtk.vtkTransformPolyDataFilter() TransformFilter.SetInputConnection(Extrude.GetOutputPort()) TransformFilter.SetTransform(Transform) for r in range(0, len(renderers)): LabelMapper = vtk.vtkPolyDataMapper() LabelMapper.SetInputConnection(TextSrc.GetOutputPort()) LabelActor = vtk.vtkFollower() LabelActor.SetMapper(LabelMapper) LabelActor.SetPosition(x, y, z) LabelActor.SetScale(2, 2, 2) LabelActor.SetOrigin(TextSrc.GetOutput().GetCenter()) # Increment zPosition. zPosition += 8.0 StockMapper = vtk.vtkPolyDataMapper() StockMapper.SetInputConnection(TransformFilter.GetOutputPort()) StockMapper.SetScalarRange(0, 8000) StockActor = vtk.vtkActor() StockActor.SetMapper(StockMapper) renderers[r].AddActor(StockActor) renderers[r].AddActor(LabelActor) LabelActor.SetCamera(renderers[r].GetActiveCamera()) return zPosition if __name__ == '__main__': main()
lorensen/VTKExamples
src/Python/VisualizationAlgorithms/Stocks.py
Python
apache-2.0
4,298
[ "VTK" ]
1f3e76177283befb61bb38331cddd286a2d2a7ca6eabfc583a3082c2d4b8b99f
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils import html #Local Imports import models as cont import utils.admin as utils class ConnectionInline(admin.TabularInline): model = cont.Connection extra = 0 class NoteInline(admin.TabularInline): model = cont.Note extra = 1 def mark_quit(modeladmin, request, queryset): ''' mark all contacts in queryset as quit and save ''' for c in queryset: c.set_status('quit',comment='Status set from bulk quit action') mark_quit.short_description = 'Mark contact as quit' def revert_status(modeladmin, request, queryset): ''' set the status for each contact in queryset to their previous status ''' for c in queryset: old_status = c.statuschange_set.last().old c.set_status(old_status,comment='Status reverted from bulk action') revert_status.short_description = 'Revert to last status' @admin.register(cont.Contact) class ContactAdmin(admin.ModelAdmin): list_display = ('study_id','nickname','status','description','facility', 'phone_number','due_date','language','send_day','is_validated','created') list_display_links = ('study_id','nickname') list_filter = ('facility','study_group', ('created',admin.DateFieldListFilter), 'hiv_messaging','status','is_validated','language','send_day') ordering = ('study_id',) search_fields = ('study_id','nickname','connection__identity','anc_num') readonly_fields = ('last_msg_client','last_msg_system','created','modified') inlines = (ConnectionInline,NoteInline) actions = (mark_quit,revert_status,) def ParticipantMixinFactory(field='participant'): class ParticipantAdminMixinBase(object): participant_field = field def participant_name(self,obj): participant = getattr(obj,self.participant_field) if participant is not None: return html.format_html("<a href='../contact/{0.pk}'>({0.study_id}) {0.nickname}</a>".format(participant) ) participant_name.short_description = 'Nickname' participant_name.admin_order_field = '{}__study_id'.format(participant_field) def facility(self,obj): participant = getattr(obj,self.participant_field) if participant is not None: return participant.facility.capitalize() facility.admin_order_field = '{}__facility'.format(participant_field) def study_id(self,obj): return getattr(obj,self.participant_field).study_id study_id.short_description = 'Study ID' study_id.admin_order_field = '{}__study_id'.format(participant_field) def phone_number(self,obj): connection = getattr(obj,self.participant_field).connection() if connection is not None: return html.format_html("<a href='../connection/{0.pk}'>{0.identity}</a>".format(connection) ) phone_number.short_description = 'Number' phone_number.admin_order_field = '{}__connection__identity'.format(participant_field) return ParticipantAdminMixinBase ParticipantAdminMixin = ParticipantMixinFactory() ContactAdminMixin = ParticipantMixinFactory('contact') @admin.register(cont.Message) class MessageAdmin(admin.ModelAdmin,ContactAdminMixin): list_display = ('text','participant_name','identity','is_system', 'is_outgoing', 'is_reply', 'external_status', 'translation_status','created') list_filter = ('is_system','is_outgoing', 'external_status', ('contact',utils.NullFieldListFilter), ('created', admin.DateFieldListFilter) ,'connection__contact__facility', 'translation_status','is_related','external_success') date_hierarchy = 'created' search_fields = ('contact__study_id','contact__nickname','connection__identity') readonly_fields = ('created','modified') def identity(self,obj): return html.format_html("<a href='./?q={0.identity}'>{0.identity}</a>".format( obj.connection ) ) identity.short_description = 'Number' identity.admin_order_field = 'connection__identity' @admin.register(cont.PhoneCall) class PhoneCallAdmin(admin.ModelAdmin,ContactAdminMixin): list_display = ('comment','participant_name','phone_number','outcome','is_outgoing','created') date_hierarchy = 'created' list_filter = ('outcome','is_outgoing') readonly_fields = ('created','modified') search_fields = ('contact__study_id','contact__nickname') @admin.register(cont.Note) class NoteAdmin(admin.ModelAdmin,ParticipantAdminMixin): list_display = ('participant_name','comment','created') date_hierarchy = 'created' @admin.register(cont.Connection) class ConnectionAdmin(admin.ModelAdmin,ContactAdminMixin): list_display = ('identity','participant_name','facility','is_primary') search_fields = ('contact__study_id','contact__nickname','identity') @admin.register(cont.Visit) class VisitAdmin(admin.ModelAdmin,ParticipantAdminMixin): list_display = ('study_id','participant_name','visit_type','scheduled', 'notification_last_seen','notify_count', 'arrived','status') date_hierarchy = 'scheduled' list_filter = ('status','visit_type','arrived','scheduled') search_fields = ('participant__study_id','participant__nickname') @admin.register(cont.ScheduledPhoneCall) class ScheduledPhoneCall(admin.ModelAdmin,ParticipantAdminMixin): list_display = ('study_id','participant_name','call_type','scheduled', 'notification_last_seen','notify_count', 'arrived','status') date_hierarchy = 'scheduled' list_filter = ('status','call_type','arrived','scheduled') search_fields = ('participant__study_id','participant__nickname') @admin.register(cont.Practitioner) class PractitionerAdmin(admin.ModelAdmin): list_display = ('facility','username','password_changed') @admin.register(cont.StatusChange) class StatusChangeAdmin(admin.ModelAdmin,ContactAdminMixin): list_display = ('comment','participant_name','old','new','type','created') search_fields = ('contact__study_id','contact__nickname') @admin.register(cont.EventLog) class EventLogAdmin(admin.ModelAdmin): list_display = ('user','event','created') class PractitionerInline(admin.TabularInline): model = cont.Practitioner class UserAdmin(UserAdmin): inlines = (PractitionerInline,) #Re-register UserAdmin admin.site.unregister(User) admin.site.register(User,UserAdmin)
tperrier/mwachx
contacts/admin.py
Python
apache-2.0
6,505
[ "VisIt" ]
72117b9d803b18d5b7b8db9a0841af1942c4c8ed60652ccc1f5f1d15096209e4
# neubot/utils_path.py # # Copyright (c) 2012-2013 # Nexa Center for Internet & Society, Politecnico di Torino (DAUIN) # and Simone Basso <bassosimone@gmail.com> # # This file is part of Neubot <http://www.neubot.org/>. # # Neubot 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. # # Neubot 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 Neubot. If not, see <http://www.gnu.org/licenses/>. # ''' Path management utils ''' # # Python3-ready: yes # import collections import logging import os import sys if __name__ == "__main__": sys.path.insert(0, ".") from neubot import six def depth_visit(prefix, components, visit): ''' Visit the subtree prefix/components[0]/components[1]... ''' # # Append() guarantees that the result is always below prefix, # so the result of this function is below prefix as well. # # It is not an error to pass a component that contains one or # more path separators, except that subcomponents are not visited # in that case. # # The boolean second argument to visit is to distinguish between # leaf and ordinary nodes. # # This function is more strict than needed and generates an # error for input like '/var/www', ['a/b/c', '../d'], but we # don't care because that case doesn't happen in Neubot. # components = collections.deque(components) while components: prefix = append(prefix, components.popleft(), False) if prefix == None: raise RuntimeError("utils_path: depth_visit(): append() failed") visit(prefix, not components) return prefix STRING_CLASS = six.u("").__class__ def decode(string, encoding): """ Decode STRING from ENCODING to UNICODE """ logging.debug("utils_path: decode('%s', '%s')", string, encoding) try: string = string.decode(encoding) except (KeyboardInterrupt, SystemExit): raise except: logging.warning("utils_path: decode() error", exc_info=1) else: return string def encode(string, encoding): """ Encode STRING to ENCODING from UNICODE """ logging.debug("utils_path: encode('%s', '%s')", string, encoding) try: string = string.encode(encoding) except (KeyboardInterrupt, SystemExit): raise except: logging.warning("utils_path: encode() error", exc_info=1) else: return string def possibly_decode(string, encoding): """ If needed, decode STRING from ENCODING to UNICODE """ if string.__class__.__name__ == STRING_CLASS.__name__: return string return decode(string, encoding) def append(rootdir, path, unquote_path): """ Append path to rootdir """ logging.debug("utils_path: rootdir \"%s\"", rootdir) logging.debug("utils_path: path \"%s\"", path) # # ROOTDIR # rootdir = possibly_decode(rootdir, "utf-8") logging.debug("utils_path: unicode(rootdir): %s", rootdir) if not rootdir: return rootdir = os.path.normpath(rootdir) logging.debug("utils_path: normpath(rootdir): %s", rootdir) rootdir = os.path.realpath(rootdir) logging.debug("utils_path: realpath(rootdir): %s", rootdir) # # PATH # # 1) Neubot only and always uses ASCII paths; # # 2) after we unquote, the unicode string can contain some # non-ASCII characters; # # 3) therefore we encode and decode again to make sure # that we have an ASCII only path. # path = possibly_decode(path, "ascii") logging.debug("utils_path: ascii(path): %s", path) if not path: return if unquote_path: path = six.urlparse.unquote(path) logging.debug("utils_path: unquote(path): %s", path) # # Note: we encode() and decode() IN ANY CASE, because the original # path string can also be unicode, which means that the above # possibly_decode() invocation just returns the unicode string. # # BTW we MUST perform this step after we unquote(), because unquote() # may introduce non-ASCII chars into the string. # path = encode(path, "ascii") if not path: return path = decode(path, "ascii") if not path: return logging.debug("utils_path: make_sure_really_ascii(path): %s", path) # # JOINED # joined = join(rootdir, path) logging.debug("utils_path: joined = join(rootdir, path): %s", joined) joined = os.path.normpath(joined) logging.debug("utils_path: normpath(joined): %s", joined) joined = os.path.realpath(joined) logging.debug("utils_path: realpath(joined): %s", joined) if not joined.startswith(rootdir): logging.warning("utils_path: '%s' IS NOT below '%s'", joined, rootdir) return return joined def normalize(string): ''' Normalize a pathname ''' return os.path.normpath(string) def join(left, right): ''' Join two paths ''' return os.sep.join([left, right]) def main(args): """ Main function """ logging.basicConfig(level=logging.DEBUG, format="%(message)s") if len(args) < 3: sys.exit("usage: python neubot/utils_path.py prefix path [...]") if len(args) == 3: append(args[1], args[2], True) else: depth_visit(args[1], args[2:], lambda *args: None) if __name__ == "__main__": main(sys.argv)
neubot/neubot
neubot/utils_path.py
Python
gpl-3.0
5,763
[ "VisIt" ]
83acd1d0b7f28d9fabacf24bad6491b5daa4ee56b72d3463353dba58e3287c58
"""Tornado handlers for the notebooks web service. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import json from tornado import web from IPython.html.utils import url_path_join, url_escape from IPython.utils.jsonutil import date_default from IPython.html.base.handlers import (IPythonHandler, json_errors, notebook_path_regex, path_regex, notebook_name_regex) #----------------------------------------------------------------------------- # Notebook web service handlers #----------------------------------------------------------------------------- class NotebookHandler(IPythonHandler): SUPPORTED_METHODS = (u'GET', u'PUT', u'PATCH', u'POST', u'DELETE') def notebook_location(self, name, path=''): """Return the full URL location of a notebook based. Parameters ---------- name : unicode The base name of the notebook, such as "foo.ipynb". path : unicode The URL path of the notebook. """ return url_escape(url_path_join( self.base_url, 'api', 'notebooks', path, name )) def _finish_model(self, model, location=True): """Finish a JSON request with a model, setting relevant headers, etc.""" if location: location = self.notebook_location(model['name'], model['path']) self.set_header('Location', location) self.set_header('Last-Modified', model['last_modified']) self.finish(json.dumps(model, default=date_default)) @web.authenticated @json_errors def get(self, path='', name=None): """Return a Notebook or list of notebooks. * GET with path and no notebook name lists notebooks in a directory * GET with path and notebook name returns notebook JSON """ nbm = self.notebook_manager # Check to see if a notebook name was given if name is None: # TODO: Remove this after we create the contents web service and directories are # no longer listed by the notebook web service. This should only handle notebooks # and not directories. dirs = nbm.list_dirs(path) notebooks = [] index = [] for nb in nbm.list_notebooks(path): if nb['name'].lower() == 'index.ipynb': index.append(nb) else: notebooks.append(nb) notebooks = index + dirs + notebooks self.finish(json.dumps(notebooks, default=date_default)) return # get and return notebook representation model = nbm.get_notebook(name, path) self._finish_model(model, location=False) @web.authenticated @json_errors def patch(self, path='', name=None): """PATCH renames a notebook without re-uploading content.""" nbm = self.notebook_manager if name is None: raise web.HTTPError(400, u'Notebook name missing') model = self.get_json_body() if model is None: raise web.HTTPError(400, u'JSON body missing') model = nbm.update_notebook(model, name, path) self._finish_model(model) def _copy_notebook(self, copy_from, path, copy_to=None): """Copy a notebook in path, optionally specifying the new name. Only support copying within the same directory. """ self.log.info(u"Copying notebook from %s/%s to %s/%s", path, copy_from, path, copy_to or '', ) model = self.notebook_manager.copy_notebook(copy_from, copy_to, path) self.set_status(201) self._finish_model(model) def _upload_notebook(self, model, path, name=None): """Upload a notebook If name specified, create it in path/name. """ self.log.info(u"Uploading notebook to %s/%s", path, name or '') if name: model['name'] = name model = self.notebook_manager.create_notebook(model, path) self.set_status(201) self._finish_model(model) def _create_empty_notebook(self, path, name=None): """Create an empty notebook in path If name specified, create it in path/name. """ self.log.info(u"Creating new notebook in %s/%s", path, name or '') model = {} if name: model['name'] = name model = self.notebook_manager.create_notebook(model, path=path) self.set_status(201) self._finish_model(model) def _save_notebook(self, model, path, name): """Save an existing notebook.""" self.log.info(u"Saving notebook at %s/%s", path, name) model = self.notebook_manager.save_notebook(model, name, path) if model['path'] != path.strip('/') or model['name'] != name: # a rename happened, set Location header location = True else: location = False self._finish_model(model, location) @web.authenticated @json_errors def post(self, path='', name=None): """Create a new notebook in the specified path. POST creates new notebooks. The server always decides on the notebook name. POST /api/notebooks/path New untitled notebook in path. If content specified, upload a notebook, otherwise start empty. POST /api/notebooks/path?copy=OtherNotebook.ipynb New copy of OtherNotebook in path """ if name is not None: raise web.HTTPError(400, "Only POST to directories. Use PUT for full names.") model = self.get_json_body() if model is not None: copy_from = model.get('copy_from') if copy_from: if model.get('content'): raise web.HTTPError(400, "Can't upload and copy at the same time.") self._copy_notebook(copy_from, path) else: self._upload_notebook(model, path) else: self._create_empty_notebook(path) @web.authenticated @json_errors def put(self, path='', name=None): """Saves the notebook in the location specified by name and path. PUT is very similar to POST, but the requester specifies the name, whereas with POST, the server picks the name. PUT /api/notebooks/path/Name.ipynb Save notebook at ``path/Name.ipynb``. Notebook structure is specified in `content` key of JSON request body. If content is not specified, create a new empty notebook. PUT /api/notebooks/path/Name.ipynb?copy=OtherNotebook.ipynb Copy OtherNotebook to Name """ if name is None: raise web.HTTPError(400, "Only PUT to full names. Use POST for directories.") model = self.get_json_body() if model: copy_from = model.get('copy_from') if copy_from: if model.get('content'): raise web.HTTPError(400, "Can't upload and copy at the same time.") self._copy_notebook(copy_from, path, name) elif self.notebook_manager.notebook_exists(name, path): self._save_notebook(model, path, name) else: self._upload_notebook(model, path, name) else: self._create_empty_notebook(path, name) @web.authenticated @json_errors def delete(self, path='', name=None): """delete the notebook in the given notebook path""" nbm = self.notebook_manager nbm.delete_notebook(name, path) self.set_status(204) self.finish() class NotebookCheckpointsHandler(IPythonHandler): SUPPORTED_METHODS = ('GET', 'POST') @web.authenticated @json_errors def get(self, path='', name=None): """get lists checkpoints for a notebook""" nbm = self.notebook_manager checkpoints = nbm.list_checkpoints(name, path) data = json.dumps(checkpoints, default=date_default) self.finish(data) @web.authenticated @json_errors def post(self, path='', name=None): """post creates a new checkpoint""" nbm = self.notebook_manager checkpoint = nbm.create_checkpoint(name, path) data = json.dumps(checkpoint, default=date_default) location = url_path_join(self.base_url, 'api/notebooks', path, name, 'checkpoints', checkpoint['id']) self.set_header('Location', url_escape(location)) self.set_status(201) self.finish(data) class ModifyNotebookCheckpointsHandler(IPythonHandler): SUPPORTED_METHODS = ('POST', 'DELETE') @web.authenticated @json_errors def post(self, path, name, checkpoint_id): """post restores a notebook from a checkpoint""" nbm = self.notebook_manager nbm.restore_checkpoint(checkpoint_id, name, path) self.set_status(204) self.finish() @web.authenticated @json_errors def delete(self, path, name, checkpoint_id): """delete clears a checkpoint for a given notebook""" nbm = self.notebook_manager nbm.delete_checkpoint(checkpoint_id, name, path) self.set_status(204) self.finish() #----------------------------------------------------------------------------- # URL to handler mappings #----------------------------------------------------------------------------- _checkpoint_id_regex = r"(?P<checkpoint_id>[\w-]+)" default_handlers = [ (r"/api/notebooks%s/checkpoints" % notebook_path_regex, NotebookCheckpointsHandler), (r"/api/notebooks%s/checkpoints/%s" % (notebook_path_regex, _checkpoint_id_regex), ModifyNotebookCheckpointsHandler), (r"/api/notebooks%s" % notebook_path_regex, NotebookHandler), (r"/api/notebooks%s" % path_regex, NotebookHandler), ]
WillisXChen/django-oscar
oscar/lib/python2.7/site-packages/IPython/html/services/notebooks/handlers.py
Python
bsd-3-clause
10,572
[ "Brian" ]
8007df24ff185547d752b193025f26f403fc89a51a69bff8a3ee28750b981d22
#!/usr/bin/env python2 """ Parse SAM file and output only pairs with at least one read aligned. Compatible with bowtie/bwa output - one entry per read. SAM file has to be sorted by read name. USAGE: samtools view -St yeast_chromosomes.fa.fai 409.sam -f3 | sam2aligned.py > 409.aligned.sam """ from datetime import datetime import os, sys def int2bin( n, count=12 ): """returns the binary of integer n, using count number of digits @ http://www.daniweb.com/software-development/python/code/216539 """ return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) def sam2unique( handle = sys.stdin ): """ """ i = k = aligned = 0 pName = lines = '' refs=0 for l in handle: #write header info if l.startswith('@'): sys.stdout.write( l ) continue #name,flag,contig,pos,mapq,cigar,paired,pairStart,isize,seq,qual name,flag,ref = l.split('\t')[:3] if name != pName: i+=1 if lines and refs: sys.stdout.write( lines ) aligned += 1 refs = 0 lines = l if ref != "*": refs += 1 pName = name else: #reads if ref != "*": refs += 1 lines += l if lines and refs: aligned += 1 sys.stdout.write( lines ) sys.stderr.write( 'Processed pairs:\t%s\nAligned pairs:\t%s [%.2f%s]\n' % ( i,aligned,aligned*100.0/i,'%' ) ) #,bothUnique,bothUnique*100.0/pairs,'%' if __name__=='__main__': T0=datetime.now() sam2unique() sys.stderr.write( "Elapsed time: %s\n" % ( datetime.now()-T0 ) )
lpryszcz/bin
sam2aligned.py
Python
gpl-3.0
1,558
[ "BWA", "Bowtie" ]
851c601f68e4f0a86df6719937efa1427484a1e220ca4084e34be187933e27c4
'''Main file''' if __name__ == '__main__': from tablecontroller import * class MainMenu(Menu): # default parameters def __init__(self, relational_table_controller): assert isinstance(relational_table_controller, VisualRelationalTableController), \ "MainMenu should use RelationalController!: {0}".format(relational_table_controller) self.__controller = relational_table_controller self.view_master = self.__controller.update_view_master _names_array = ["View table Author", "View table Books", "Add...", "Edit...", "Delete...", "Search...", "Get Authors with books of >100 pages", "Save/Load"] _fn_array = [self.__controller.update_view_master, self.__controller.update_view_slave, self.nested_menu_loop(["Authors", "Books"], [self.__controller.add_row_master, self.__controller.add_row_slave], name='Choose table'), self.nested_menu_loop(["Authors", "Books"], [self.__controller.edit_master, self.__controller.edit_slave], name='Choose table'), self.nested_menu_loop(["Authors", "Books"], [self.__controller.delete_master, self.__controller.delete_slave], name='Choose table'), self.nested_menu_loop(["Authors", "Books"], [self.__controller.search_master, self.__controller.search_slave], name='Choose table'), self.__controller.print_task_result, self.nested_menu_loop(["Save pickle", "Load pickle"], [self.__controller.dump, self.__controller.load])] super(MainMenu, self).__init__(_names_array, _fn_array, name="Simple database", return_name="Exit", return_index="x") authors = TableController(DatabaseTableModel(('Author', 'YearOfBirth'))) books = TableController(DatabaseTableModel(('Book', 'NumOfPages', 'Author'))) try: authors.load() except: # load by code authors_data_starting_point = \ (("Douglas Adams", "1952"), ("Ray Bradbury", "1920"), ("Taras Shevchenko", "1814")) for row in authors_data_starting_point: authors.add_row(row) # save authors.dump() try: books.load() except: # load by code books_data_starting_point = \ (("Kobzar (1st ed.)", "100", "Taras Shevchenko"), ("Hitchhiker's Guide to Galaxy", "120", "Douglas Adams"), ("Fahrenheit 451", "159", "Ray Bradbury")) for row in books_data_starting_point: books.add_row(row) # save books.dump() books.set_item(1, "Author", "Morty") relation = VisualRelationalTableController(authors, books, ("Author", "Author")) main_menu = MainMenu(relation) main_menu.loop()
sanchaez/python_labs
Lab1/main.py
Python
mit
3,496
[ "Galaxy" ]
0caf7e4ce655154b94fb52c9810253d674acf67271422150f48fd19cf2ed6ed2
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2007 Donald N. Allingham # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2008 Jerome Rapinat # Copyright (C) 2008 Benny Malengier # # 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. # #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # GRAMPS modules # #------------------------------------------------------------------------- from .._hasnotebase import HasNoteBase #------------------------------------------------------------------------- # "People having notes" #------------------------------------------------------------------------- class HasNote(HasNoteBase): """People having notes""" name = _('People having <count> notes') description = _("Matches people having a certain number of notes")
pmghalvorsen/gramps_branch
gramps/gen/filters/rules/person/_hasnote.py
Python
gpl-2.0
1,754
[ "Brian" ]
5774b0400826f8660956f023f8615e463fdea85f5bec57705b71fc6053a2f58f
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # import sys from pyspark import since, keyword_only from pyspark.ml.param.shared import * from pyspark.ml.tree import _DecisionTreeModel, _DecisionTreeParams, \ _TreeEnsembleModel, _TreeEnsembleParams, _RandomForestParams, _GBTParams, \ _HasVarianceImpurity, _TreeRegressorParams from pyspark.ml.util import * from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, \ JavaPredictor, JavaPredictionModel, _JavaPredictorParams, JavaWrapper from pyspark.ml.common import inherit_doc from pyspark.sql import DataFrame __all__ = ['AFTSurvivalRegression', 'AFTSurvivalRegressionModel', 'DecisionTreeRegressor', 'DecisionTreeRegressionModel', 'GBTRegressor', 'GBTRegressionModel', 'GeneralizedLinearRegression', 'GeneralizedLinearRegressionModel', 'GeneralizedLinearRegressionSummary', 'GeneralizedLinearRegressionTrainingSummary', 'IsotonicRegression', 'IsotonicRegressionModel', 'LinearRegression', 'LinearRegressionModel', 'LinearRegressionSummary', 'LinearRegressionTrainingSummary', 'RandomForestRegressor', 'RandomForestRegressionModel', 'FMRegressor', 'FMRegressionModel'] class _LinearRegressionParams(_JavaPredictorParams, HasRegParam, HasElasticNetParam, HasMaxIter, HasTol, HasFitIntercept, HasStandardization, HasWeightCol, HasSolver, HasAggregationDepth, HasLoss): """ Params for :py:class:`LinearRegression` and :py:class:`LinearRegressionModel`. .. versionadded:: 3.0.0 """ solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " + "options: auto, normal, l-bfgs.", typeConverter=TypeConverters.toString) loss = Param(Params._dummy(), "loss", "The loss function to be optimized. Supported " + "options: squaredError, huber.", typeConverter=TypeConverters.toString) epsilon = Param(Params._dummy(), "epsilon", "The shape parameter to control the amount of " + "robustness. Must be > 1.0. Only valid when loss is huber", typeConverter=TypeConverters.toFloat) @since("2.3.0") def getEpsilon(self): """ Gets the value of epsilon or its default value. """ return self.getOrDefault(self.epsilon) @inherit_doc class LinearRegression(JavaPredictor, _LinearRegressionParams, JavaMLWritable, JavaMLReadable): """ Linear regression. The learning objective is to minimize the specified loss function, with regularization. This supports two kinds of loss: * squaredError (a.k.a squared loss) * huber (a hybrid of squared error for relatively small errors and absolute error for \ relatively large ones, and we estimate the scale parameter from training data) This supports multiple types of regularization: * none (a.k.a. ordinary least squares) * L2 (ridge regression) * L1 (Lasso) * L2 + L1 (elastic net) Note: Fitting with huber loss only supports none and L2 regularization. >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, 2.0, Vectors.dense(1.0)), ... (0.0, 2.0, Vectors.sparse(1, [], []))], ["label", "weight", "features"]) >>> lr = LinearRegression(regParam=0.0, solver="normal", weightCol="weight") >>> lr.setMaxIter(5) LinearRegression... >>> lr.getMaxIter() 5 >>> lr.setRegParam(0.1) LinearRegression... >>> lr.getRegParam() 0.1 >>> lr.setRegParam(0.0) LinearRegression... >>> model = lr.fit(df) >>> model.setFeaturesCol("features") LinearRegressionModel... >>> model.setPredictionCol("newPrediction") LinearRegressionModel... >>> model.getMaxIter() 5 >>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"]) >>> abs(model.predict(test0.head().features) - (-1.0)) < 0.001 True >>> abs(model.transform(test0).head().newPrediction - (-1.0)) < 0.001 True >>> abs(model.coefficients[0] - 1.0) < 0.001 True >>> abs(model.intercept - 0.0) < 0.001 True >>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"]) >>> abs(model.transform(test1).head().newPrediction - 1.0) < 0.001 True >>> lr.setParams("vector") Traceback (most recent call last): ... TypeError: Method setParams forces keyword arguments. >>> lr_path = temp_path + "/lr" >>> lr.save(lr_path) >>> lr2 = LinearRegression.load(lr_path) >>> lr2.getMaxIter() 5 >>> model_path = temp_path + "/lr_model" >>> model.save(model_path) >>> model2 = LinearRegressionModel.load(model_path) >>> model.coefficients[0] == model2.coefficients[0] True >>> model.intercept == model2.intercept True >>> model.numFeatures 1 >>> model.write().format("pmml").save(model_path + "_2") .. versionadded:: 1.4.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto", weightCol=None, aggregationDepth=2, loss="squaredError", epsilon=1.35): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \ standardization=True, solver="auto", weightCol=None, aggregationDepth=2, \ loss="squaredError", epsilon=1.35) """ super(LinearRegression, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.LinearRegression", self.uid) self._setDefault(maxIter=100, regParam=0.0, tol=1e-6, loss="squaredError", epsilon=1.35) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("1.4.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto", weightCol=None, aggregationDepth=2, loss="squaredError", epsilon=1.35): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \ standardization=True, solver="auto", weightCol=None, aggregationDepth=2, \ loss="squaredError", epsilon=1.35) Sets params for linear regression. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return LinearRegressionModel(java_model) @since("2.3.0") def setEpsilon(self, value): """ Sets the value of :py:attr:`epsilon`. """ return self._set(epsilon=value) def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) def setRegParam(self, value): """ Sets the value of :py:attr:`regParam`. """ return self._set(regParam=value) def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) def setElasticNetParam(self, value): """ Sets the value of :py:attr:`elasticNetParam`. """ return self._set(elasticNetParam=value) def setFitIntercept(self, value): """ Sets the value of :py:attr:`fitIntercept`. """ return self._set(fitIntercept=value) def setStandardization(self, value): """ Sets the value of :py:attr:`standardization`. """ return self._set(standardization=value) def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) def setSolver(self, value): """ Sets the value of :py:attr:`solver`. """ return self._set(solver=value) def setAggregationDepth(self, value): """ Sets the value of :py:attr:`aggregationDepth`. """ return self._set(aggregationDepth=value) def setLoss(self, value): """ Sets the value of :py:attr:`loss`. """ return self._set(lossType=value) class LinearRegressionModel(JavaPredictionModel, _LinearRegressionParams, GeneralJavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by :class:`LinearRegression`. .. versionadded:: 1.4.0 """ @property @since("2.0.0") def coefficients(self): """ Model coefficients. """ return self._call_java("coefficients") @property @since("1.4.0") def intercept(self): """ Model intercept. """ return self._call_java("intercept") @property @since("2.3.0") def scale(self): r""" The value by which :math:`\|y - X'w\|` is scaled down when loss is "huber", otherwise 1.0. """ return self._call_java("scale") @property @since("2.0.0") def summary(self): """ Gets summary (e.g. residuals, mse, r-squared ) of model on training set. An exception is thrown if `trainingSummary is None`. """ if self.hasSummary: return LinearRegressionTrainingSummary(super(LinearRegressionModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("2.0.0") def evaluate(self, dataset): """ Evaluates the model on a test dataset. :param dataset: Test dataset to evaluate model on, where dataset is an instance of :py:class:`pyspark.sql.DataFrame` """ if not isinstance(dataset, DataFrame): raise ValueError("dataset must be a DataFrame but got %s." % type(dataset)) java_lr_summary = self._call_java("evaluate", dataset) return LinearRegressionSummary(java_lr_summary) class LinearRegressionSummary(JavaWrapper): """ Linear regression results evaluated on a dataset. .. versionadded:: 2.0.0 """ @property @since("2.0.0") def predictions(self): """ Dataframe outputted by the model's `transform` method. """ return self._call_java("predictions") @property @since("2.0.0") def predictionCol(self): """ Field in "predictions" which gives the predicted value of the label at each instance. """ return self._call_java("predictionCol") @property @since("2.0.0") def labelCol(self): """ Field in "predictions" which gives the true label of each instance. """ return self._call_java("labelCol") @property @since("2.0.0") def featuresCol(self): """ Field in "predictions" which gives the features of each instance as a vector. """ return self._call_java("featuresCol") @property @since("2.0.0") def explainedVariance(self): r""" Returns the explained variance regression score. explainedVariance = :math:`1 - \frac{variance(y - \hat{y})}{variance(y)}` .. seealso:: `Wikipedia explain variation <http://en.wikipedia.org/wiki/Explained_variation>`_ .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("explainedVariance") @property @since("2.0.0") def meanAbsoluteError(self): """ Returns the mean absolute error, which is a risk function corresponding to the expected value of the absolute error loss or l1-norm loss. .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("meanAbsoluteError") @property @since("2.0.0") def meanSquaredError(self): """ Returns the mean squared error, which is a risk function corresponding to the expected value of the squared error loss or quadratic loss. .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("meanSquaredError") @property @since("2.0.0") def rootMeanSquaredError(self): """ Returns the root mean squared error, which is defined as the square root of the mean squared error. .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("rootMeanSquaredError") @property @since("2.0.0") def r2(self): """ Returns R^2, the coefficient of determination. .. seealso:: `Wikipedia coefficient of determination <http://en.wikipedia.org/wiki/Coefficient_of_determination>`_ .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("r2") @property @since("2.4.0") def r2adj(self): """ Returns Adjusted R^2, the adjusted coefficient of determination. .. seealso:: `Wikipedia coefficient of determination, Adjusted R^2 <https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2>`_ .. note:: This ignores instance weights (setting all to 1.0) from `LinearRegression.weightCol`. This will change in later Spark versions. """ return self._call_java("r2adj") @property @since("2.0.0") def residuals(self): """ Residuals (label - predicted value) """ return self._call_java("residuals") @property @since("2.0.0") def numInstances(self): """ Number of instances in DataFrame predictions """ return self._call_java("numInstances") @property @since("2.2.0") def degreesOfFreedom(self): """ Degrees of freedom. """ return self._call_java("degreesOfFreedom") @property @since("2.0.0") def devianceResiduals(self): """ The weighted residuals, the usual residuals rescaled by the square root of the instance weights. """ return self._call_java("devianceResiduals") @property @since("2.0.0") def coefficientStandardErrors(self): """ Standard error of estimated coefficients and intercept. This value is only available when using the "normal" solver. If :py:attr:`LinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. .. seealso:: :py:attr:`LinearRegression.solver` """ return self._call_java("coefficientStandardErrors") @property @since("2.0.0") def tValues(self): """ T-statistic of estimated coefficients and intercept. This value is only available when using the "normal" solver. If :py:attr:`LinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. .. seealso:: :py:attr:`LinearRegression.solver` """ return self._call_java("tValues") @property @since("2.0.0") def pValues(self): """ Two-sided p-value of estimated coefficients and intercept. This value is only available when using the "normal" solver. If :py:attr:`LinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. .. seealso:: :py:attr:`LinearRegression.solver` """ return self._call_java("pValues") @inherit_doc class LinearRegressionTrainingSummary(LinearRegressionSummary): """ Linear regression training results. Currently, the training summary ignores the training weights except for the objective trace. .. versionadded:: 2.0.0 """ @property @since("2.0.0") def objectiveHistory(self): """ Objective function (scaled loss + regularization) at each iteration. This value is only available when using the "l-bfgs" solver. .. seealso:: :py:attr:`LinearRegression.solver` """ return self._call_java("objectiveHistory") @property @since("2.0.0") def totalIterations(self): """ Number of training iterations until termination. This value is only available when using the "l-bfgs" solver. .. seealso:: :py:attr:`LinearRegression.solver` """ return self._call_java("totalIterations") class _IsotonicRegressionParams(HasFeaturesCol, HasLabelCol, HasPredictionCol, HasWeightCol): """ Params for :py:class:`IsotonicRegression` and :py:class:`IsotonicRegressionModel`. .. versionadded:: 3.0.0 """ isotonic = Param( Params._dummy(), "isotonic", "whether the output sequence should be isotonic/increasing (true) or" + "antitonic/decreasing (false).", typeConverter=TypeConverters.toBoolean) featureIndex = Param( Params._dummy(), "featureIndex", "The index of the feature if featuresCol is a vector column, no effect otherwise.", typeConverter=TypeConverters.toInt) def getIsotonic(self): """ Gets the value of isotonic or its default value. """ return self.getOrDefault(self.isotonic) def getFeatureIndex(self): """ Gets the value of featureIndex or its default value. """ return self.getOrDefault(self.featureIndex) @inherit_doc class IsotonicRegression(JavaEstimator, _IsotonicRegressionParams, HasWeightCol, JavaMLWritable, JavaMLReadable): """ Currently implemented using parallelized pool adjacent violators algorithm. Only univariate (single feature) algorithm supported. >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(1.0)), ... (0.0, Vectors.sparse(1, [], []))], ["label", "features"]) >>> ir = IsotonicRegression() >>> model = ir.fit(df) >>> model.setFeaturesCol("features") IsotonicRegressionModel... >>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"]) >>> model.transform(test0).head().prediction 0.0 >>> model.boundaries DenseVector([0.0, 1.0]) >>> ir_path = temp_path + "/ir" >>> ir.save(ir_path) >>> ir2 = IsotonicRegression.load(ir_path) >>> ir2.getIsotonic() True >>> model_path = temp_path + "/ir_model" >>> model.save(model_path) >>> model2 = IsotonicRegressionModel.load(model_path) >>> model.boundaries == model2.boundaries True >>> model.predictions == model2.predictions True .. versionadded:: 1.6.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", weightCol=None, isotonic=True, featureIndex=0): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ weightCol=None, isotonic=True, featureIndex=0): """ super(IsotonicRegression, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.IsotonicRegression", self.uid) self._setDefault(isotonic=True, featureIndex=0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", weightCol=None, isotonic=True, featureIndex=0): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ weightCol=None, isotonic=True, featureIndex=0): Set the params for IsotonicRegression. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return IsotonicRegressionModel(java_model) def setIsotonic(self, value): """ Sets the value of :py:attr:`isotonic`. """ return self._set(isotonic=value) def setFeatureIndex(self, value): """ Sets the value of :py:attr:`featureIndex`. """ return self._set(featureIndex=value) @since("1.6.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("1.6.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("1.6.0") def setLabelCol(self, value): """ Sets the value of :py:attr:`labelCol`. """ return self._set(labelCol=value) @since("1.6.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) class IsotonicRegressionModel(JavaModel, _IsotonicRegressionParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`IsotonicRegression`. .. versionadded:: 1.6.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) def setFeatureIndex(self, value): """ Sets the value of :py:attr:`featureIndex`. """ return self._set(featureIndex=value) @property @since("1.6.0") def boundaries(self): """ Boundaries in increasing order for which predictions are known. """ return self._call_java("boundaries") @property @since("1.6.0") def predictions(self): """ Predictions associated with the boundaries at the same index, monotone because of isotonic regression. """ return self._call_java("predictions") class _DecisionTreeRegressorParams(_DecisionTreeParams, _TreeRegressorParams, HasVarianceCol): """ Params for :py:class:`DecisionTreeRegressor` and :py:class:`DecisionTreeRegressionModel`. .. versionadded:: 3.0.0 """ pass @inherit_doc class DecisionTreeRegressor(JavaPredictor, _DecisionTreeRegressorParams, JavaMLWritable, JavaMLReadable): """ `Decision tree <http://en.wikipedia.org/wiki/Decision_tree_learning>`_ learning algorithm for regression. It supports both continuous and categorical features. >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(1.0)), ... (0.0, Vectors.sparse(1, [], []))], ["label", "features"]) >>> dt = DecisionTreeRegressor(maxDepth=2) >>> dt.setVarianceCol("variance") DecisionTreeRegressor... >>> model = dt.fit(df) >>> model.getVarianceCol() 'variance' >>> model.setLeafCol("leafId") DecisionTreeRegressionModel... >>> model.depth 1 >>> model.numNodes 3 >>> model.featureImportances SparseVector(1, {0: 1.0}) >>> model.numFeatures 1 >>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"]) >>> model.predict(test0.head().features) 0.0 >>> result = model.transform(test0).head() >>> result.prediction 0.0 >>> model.predictLeaf(test0.head().features) 0.0 >>> result.leafId 0.0 >>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"]) >>> model.transform(test1).head().prediction 1.0 >>> dtr_path = temp_path + "/dtr" >>> dt.save(dtr_path) >>> dt2 = DecisionTreeRegressor.load(dtr_path) >>> dt2.getMaxDepth() 2 >>> model_path = temp_path + "/dtr_model" >>> model.save(model_path) >>> model2 = DecisionTreeRegressionModel.load(model_path) >>> model.numNodes == model2.numNodes True >>> model.depth == model2.depth True >>> model.transform(test1).head().variance 0.0 >>> df3 = spark.createDataFrame([ ... (1.0, 0.2, Vectors.dense(1.0)), ... (1.0, 0.8, Vectors.dense(1.0)), ... (0.0, 1.0, Vectors.sparse(1, [], []))], ["label", "weight", "features"]) >>> dt3 = DecisionTreeRegressor(maxDepth=2, weightCol="weight", varianceCol="variance") >>> model3 = dt3.fit(df3) >>> print(model3.toDebugString) DecisionTreeRegressionModel...depth=1, numNodes=3... .. versionadded:: 1.4.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", seed=None, varianceCol=None, weightCol=None, leafCol="", minWeightFractionPerNode=0.0): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \ impurity="variance", seed=None, varianceCol=None, weightCol=None, \ leafCol="", minWeightFractionPerNode=0.0) """ super(DecisionTreeRegressor, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.DecisionTreeRegressor", self.uid) self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", leafCol="", minWeightFractionPerNode=0.0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("1.4.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", seed=None, varianceCol=None, weightCol=None, leafCol="", minWeightFractionPerNode=0.0): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \ impurity="variance", seed=None, varianceCol=None, weightCol=None, \ leafCol="", minWeightFractionPerNode=0.0) Sets params for the DecisionTreeRegressor. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return DecisionTreeRegressionModel(java_model) @since("1.4.0") def setMaxDepth(self, value): """ Sets the value of :py:attr:`maxDepth`. """ return self._set(maxDepth=value) @since("1.4.0") def setMaxBins(self, value): """ Sets the value of :py:attr:`maxBins`. """ return self._set(maxBins=value) @since("1.4.0") def setMinInstancesPerNode(self, value): """ Sets the value of :py:attr:`minInstancesPerNode`. """ return self._set(minInstancesPerNode=value) @since("3.0.0") def setMinWeightFractionPerNode(self, value): """ Sets the value of :py:attr:`minWeightFractionPerNode`. """ return self._set(minWeightFractionPerNode=value) @since("1.4.0") def setMinInfoGain(self, value): """ Sets the value of :py:attr:`minInfoGain`. """ return self._set(minInfoGain=value) @since("1.4.0") def setMaxMemoryInMB(self, value): """ Sets the value of :py:attr:`maxMemoryInMB`. """ return self._set(maxMemoryInMB=value) @since("1.4.0") def setCacheNodeIds(self, value): """ Sets the value of :py:attr:`cacheNodeIds`. """ return self._set(cacheNodeIds=value) @since("1.4.0") def setImpurity(self, value): """ Sets the value of :py:attr:`impurity`. """ return self._set(impurity=value) @since("1.4.0") def setCheckpointInterval(self, value): """ Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value) @since("1.4.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("2.0.0") def setVarianceCol(self, value): """ Sets the value of :py:attr:`varianceCol`. """ return self._set(varianceCol=value) @inherit_doc class DecisionTreeRegressionModel(_DecisionTreeModel, _DecisionTreeRegressorParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`DecisionTreeRegressor`. .. versionadded:: 1.4.0 """ @since("3.0.0") def setVarianceCol(self, value): """ Sets the value of :py:attr:`varianceCol`. """ return self._set(varianceCol=value) @property @since("2.0.0") def featureImportances(self): """ Estimate of the importance of each feature. This generalizes the idea of "Gini" importance to other losses, following the explanation of Gini importance from "Random Forests" documentation by Leo Breiman and Adele Cutler, and following the implementation from scikit-learn. This feature importance is calculated as follows: - importance(feature j) = sum (over nodes which split on feature j) of the gain, where gain is scaled by the number of instances passing through node - Normalize importances for tree to sum to 1. .. note:: Feature importance for single decision trees can have high variance due to correlated predictor variables. Consider using a :py:class:`RandomForestRegressor` to determine feature importance instead. """ return self._call_java("featureImportances") class _RandomForestRegressorParams(_RandomForestParams, _TreeRegressorParams): """ Params for :py:class:`RandomForestRegressor` and :py:class:`RandomForestRegressionModel`. .. versionadded:: 3.0.0 """ pass @inherit_doc class RandomForestRegressor(JavaPredictor, _RandomForestRegressorParams, JavaMLWritable, JavaMLReadable): """ `Random Forest <http://en.wikipedia.org/wiki/Random_forest>`_ learning algorithm for regression. It supports both continuous and categorical features. >>> from numpy import allclose >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(1.0)), ... (0.0, Vectors.sparse(1, [], []))], ["label", "features"]) >>> rf = RandomForestRegressor(numTrees=2, maxDepth=2) >>> rf.setSeed(42) RandomForestRegressor... >>> model = rf.fit(df) >>> model.getSeed() 42 >>> model.setLeafCol("leafId") RandomForestRegressionModel... >>> model.featureImportances SparseVector(1, {0: 1.0}) >>> allclose(model.treeWeights, [1.0, 1.0]) True >>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"]) >>> model.predict(test0.head().features) 0.0 >>> model.predictLeaf(test0.head().features) DenseVector([0.0, 0.0]) >>> result = model.transform(test0).head() >>> result.prediction 0.0 >>> result.leafId DenseVector([0.0, 0.0]) >>> model.numFeatures 1 >>> model.trees [DecisionTreeRegressionModel...depth=..., DecisionTreeRegressionModel...] >>> model.getNumTrees 2 >>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"]) >>> model.transform(test1).head().prediction 0.5 >>> rfr_path = temp_path + "/rfr" >>> rf.save(rfr_path) >>> rf2 = RandomForestRegressor.load(rfr_path) >>> rf2.getNumTrees() 2 >>> model_path = temp_path + "/rfr_model" >>> model.save(model_path) >>> model2 = RandomForestRegressionModel.load(model_path) >>> model.featureImportances == model2.featureImportances True .. versionadded:: 1.4.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", subsamplingRate=1.0, seed=None, numTrees=20, featureSubsetStrategy="auto", leafCol="", minWeightFractionPerNode=0.0): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \ impurity="variance", subsamplingRate=1.0, seed=None, numTrees=20, \ featureSubsetStrategy="auto", leafCol=", minWeightFractionPerNode=0.0") """ super(RandomForestRegressor, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.RandomForestRegressor", self.uid) self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", subsamplingRate=1.0, numTrees=20, featureSubsetStrategy="auto", leafCol="", minWeightFractionPerNode=0.0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("1.4.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="variance", subsamplingRate=1.0, seed=None, numTrees=20, featureSubsetStrategy="auto", leafCol="", minWeightFractionPerNode=0.0): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \ impurity="variance", subsamplingRate=1.0, seed=None, numTrees=20, \ featureSubsetStrategy="auto", leafCol="", minWeightFractionPerNode=0.0) Sets params for linear regression. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return RandomForestRegressionModel(java_model) def setMaxDepth(self, value): """ Sets the value of :py:attr:`maxDepth`. """ return self._set(maxDepth=value) def setMaxBins(self, value): """ Sets the value of :py:attr:`maxBins`. """ return self._set(maxBins=value) def setMinInstancesPerNode(self, value): """ Sets the value of :py:attr:`minInstancesPerNode`. """ return self._set(minInstancesPerNode=value) def setMinInfoGain(self, value): """ Sets the value of :py:attr:`minInfoGain`. """ return self._set(minInfoGain=value) def setMaxMemoryInMB(self, value): """ Sets the value of :py:attr:`maxMemoryInMB`. """ return self._set(maxMemoryInMB=value) def setCacheNodeIds(self, value): """ Sets the value of :py:attr:`cacheNodeIds`. """ return self._set(cacheNodeIds=value) @since("1.4.0") def setImpurity(self, value): """ Sets the value of :py:attr:`impurity`. """ return self._set(impurity=value) @since("1.4.0") def setNumTrees(self, value): """ Sets the value of :py:attr:`numTrees`. """ return self._set(numTrees=value) @since("1.4.0") def setSubsamplingRate(self, value): """ Sets the value of :py:attr:`subsamplingRate`. """ return self._set(subsamplingRate=value) @since("2.4.0") def setFeatureSubsetStrategy(self, value): """ Sets the value of :py:attr:`featureSubsetStrategy`. """ return self._set(featureSubsetStrategy=value) def setCheckpointInterval(self, value): """ Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value) def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) class RandomForestRegressionModel(_TreeEnsembleModel, _RandomForestRegressorParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`RandomForestRegressor`. .. versionadded:: 1.4.0 """ @property @since("2.0.0") def trees(self): """Trees in this ensemble. Warning: These have null parent Estimators.""" return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))] @property @since("2.0.0") def featureImportances(self): """ Estimate of the importance of each feature. Each feature's importance is the average of its importance across all trees in the ensemble The importance vector is normalized to sum to 1. This method is suggested by Hastie et al. (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.) and follows the implementation from scikit-learn. .. seealso:: :py:attr:`DecisionTreeRegressionModel.featureImportances` """ return self._call_java("featureImportances") class _GBTRegressorParams(_GBTParams, _TreeRegressorParams): """ Params for :py:class:`GBTRegressor` and :py:class:`GBTRegressorModel`. .. versionadded:: 3.0.0 """ supportedLossTypes = ["squared", "absolute"] lossType = Param(Params._dummy(), "lossType", "Loss function which GBT tries to minimize (case-insensitive). " + "Supported options: " + ", ".join(supportedLossTypes), typeConverter=TypeConverters.toString) @since("1.4.0") def getLossType(self): """ Gets the value of lossType or its default value. """ return self.getOrDefault(self.lossType) @inherit_doc class GBTRegressor(JavaPredictor, _GBTRegressorParams, JavaMLWritable, JavaMLReadable): """ `Gradient-Boosted Trees (GBTs) <http://en.wikipedia.org/wiki/Gradient_boosting>`_ learning algorithm for regression. It supports both continuous and categorical features. >>> from numpy import allclose >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(1.0)), ... (0.0, Vectors.sparse(1, [], []))], ["label", "features"]) >>> gbt = GBTRegressor(maxDepth=2, seed=42, leafCol="leafId") >>> gbt.setMaxIter(5) GBTRegressor... >>> gbt.setMinWeightFractionPerNode(0.049) GBTRegressor... >>> gbt.getMaxIter() 5 >>> print(gbt.getImpurity()) variance >>> print(gbt.getFeatureSubsetStrategy()) all >>> model = gbt.fit(df) >>> model.featureImportances SparseVector(1, {0: 1.0}) >>> model.numFeatures 1 >>> allclose(model.treeWeights, [1.0, 0.1, 0.1, 0.1, 0.1]) True >>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"]) >>> model.predict(test0.head().features) 0.0 >>> model.predictLeaf(test0.head().features) DenseVector([0.0, 0.0, 0.0, 0.0, 0.0]) >>> result = model.transform(test0).head() >>> result.prediction 0.0 >>> result.leafId DenseVector([0.0, 0.0, 0.0, 0.0, 0.0]) >>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"]) >>> model.transform(test1).head().prediction 1.0 >>> gbtr_path = temp_path + "gbtr" >>> gbt.save(gbtr_path) >>> gbt2 = GBTRegressor.load(gbtr_path) >>> gbt2.getMaxDepth() 2 >>> model_path = temp_path + "gbtr_model" >>> model.save(model_path) >>> model2 = GBTRegressionModel.load(model_path) >>> model.featureImportances == model2.featureImportances True >>> model.treeWeights == model2.treeWeights True >>> model.trees [DecisionTreeRegressionModel...depth=..., DecisionTreeRegressionModel...] >>> validation = spark.createDataFrame([(0.0, Vectors.dense(-1.0))], ... ["label", "features"]) >>> model.evaluateEachIteration(validation, "squared") [0.0, 0.0, 0.0, 0.0, 0.0] >>> gbt = gbt.setValidationIndicatorCol("validationIndicator") >>> gbt.getValidationIndicatorCol() 'validationIndicator' >>> gbt.getValidationTol() 0.01 .. versionadded:: 1.4.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0, checkpointInterval=10, lossType="squared", maxIter=20, stepSize=0.1, seed=None, impurity="variance", featureSubsetStrategy="all", validationTol=0.01, validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, weightCol=None): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0, \ checkpointInterval=10, lossType="squared", maxIter=20, stepSize=0.1, seed=None, \ impurity="variance", featureSubsetStrategy="all", validationTol=0.01, \ validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, weightCol=None) """ super(GBTRegressor, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.regression.GBTRegressor", self.uid) self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0, checkpointInterval=10, lossType="squared", maxIter=20, stepSize=0.1, impurity="variance", featureSubsetStrategy="all", validationTol=0.01, leafCol="", minWeightFractionPerNode=0.0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("1.4.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0, checkpointInterval=10, lossType="squared", maxIter=20, stepSize=0.1, seed=None, impuriy="variance", featureSubsetStrategy="all", validationTol=0.01, validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, weightCol=None): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \ maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0, \ checkpointInterval=10, lossType="squared", maxIter=20, stepSize=0.1, seed=None, \ impurity="variance", featureSubsetStrategy="all", validationTol=0.01, \ validationIndicatorCol=None, leafCol="", minWeightFractionPerNode=0.0, \ weightCol=None) Sets params for Gradient Boosted Tree Regression. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return GBTRegressionModel(java_model) @since("1.4.0") def setMaxDepth(self, value): """ Sets the value of :py:attr:`maxDepth`. """ return self._set(maxDepth=value) @since("1.4.0") def setMaxBins(self, value): """ Sets the value of :py:attr:`maxBins`. """ return self._set(maxBins=value) @since("1.4.0") def setMinInstancesPerNode(self, value): """ Sets the value of :py:attr:`minInstancesPerNode`. """ return self._set(minInstancesPerNode=value) @since("1.4.0") def setMinInfoGain(self, value): """ Sets the value of :py:attr:`minInfoGain`. """ return self._set(minInfoGain=value) @since("1.4.0") def setMaxMemoryInMB(self, value): """ Sets the value of :py:attr:`maxMemoryInMB`. """ return self._set(maxMemoryInMB=value) @since("1.4.0") def setCacheNodeIds(self, value): """ Sets the value of :py:attr:`cacheNodeIds`. """ return self._set(cacheNodeIds=value) @since("1.4.0") def setImpurity(self, value): """ Sets the value of :py:attr:`impurity`. """ return self._set(impurity=value) @since("1.4.0") def setLossType(self, value): """ Sets the value of :py:attr:`lossType`. """ return self._set(lossType=value) @since("1.4.0") def setSubsamplingRate(self, value): """ Sets the value of :py:attr:`subsamplingRate`. """ return self._set(subsamplingRate=value) @since("2.4.0") def setFeatureSubsetStrategy(self, value): """ Sets the value of :py:attr:`featureSubsetStrategy`. """ return self._set(featureSubsetStrategy=value) @since("3.0.0") def setValidationIndicatorCol(self, value): """ Sets the value of :py:attr:`validationIndicatorCol`. """ return self._set(validationIndicatorCol=value) @since("1.4.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("1.4.0") def setCheckpointInterval(self, value): """ Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value) @since("1.4.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("1.4.0") def setStepSize(self, value): """ Sets the value of :py:attr:`stepSize`. """ return self._set(stepSize=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("3.0.0") def setMinWeightFractionPerNode(self, value): """ Sets the value of :py:attr:`minWeightFractionPerNode`. """ return self._set(minWeightFractionPerNode=value) class GBTRegressionModel(_TreeEnsembleModel, _GBTRegressorParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`GBTRegressor`. .. versionadded:: 1.4.0 """ @property @since("2.0.0") def featureImportances(self): """ Estimate of the importance of each feature. Each feature's importance is the average of its importance across all trees in the ensemble The importance vector is normalized to sum to 1. This method is suggested by Hastie et al. (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.) and follows the implementation from scikit-learn. .. seealso:: :py:attr:`DecisionTreeRegressionModel.featureImportances` """ return self._call_java("featureImportances") @property @since("2.0.0") def trees(self): """Trees in this ensemble. Warning: These have null parent Estimators.""" return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))] @since("2.4.0") def evaluateEachIteration(self, dataset, loss): """ Method to compute error or loss for every iteration of gradient boosting. :param dataset: Test dataset to evaluate model on, where dataset is an instance of :py:class:`pyspark.sql.DataFrame` :param loss: The loss function used to compute error. Supported options: squared, absolute """ return self._call_java("evaluateEachIteration", dataset, loss) class _AFTSurvivalRegressionParams(HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter, HasTol, HasFitIntercept, HasAggregationDepth): """ Params for :py:class:`AFTSurvivalRegression` and :py:class:`AFTSurvivalRegressionModel`. .. versionadded:: 3.0.0 """ censorCol = Param( Params._dummy(), "censorCol", "censor column name. The value of this column could be 0 or 1. " + "If the value is 1, it means the event has occurred i.e. " + "uncensored; otherwise censored.", typeConverter=TypeConverters.toString) quantileProbabilities = Param( Params._dummy(), "quantileProbabilities", "quantile probabilities array. Values of the quantile probabilities array " + "should be in the range (0, 1) and the array should be non-empty.", typeConverter=TypeConverters.toListFloat) quantilesCol = Param( Params._dummy(), "quantilesCol", "quantiles column name. This column will output quantiles of " + "corresponding quantileProbabilities if it is set.", typeConverter=TypeConverters.toString) @since("1.6.0") def getCensorCol(self): """ Gets the value of censorCol or its default value. """ return self.getOrDefault(self.censorCol) @since("1.6.0") def getQuantileProbabilities(self): """ Gets the value of quantileProbabilities or its default value. """ return self.getOrDefault(self.quantileProbabilities) @since("1.6.0") def getQuantilesCol(self): """ Gets the value of quantilesCol or its default value. """ return self.getOrDefault(self.quantilesCol) @inherit_doc class AFTSurvivalRegression(JavaEstimator, _AFTSurvivalRegressionParams, JavaMLWritable, JavaMLReadable): """ Accelerated Failure Time (AFT) Model Survival Regression Fit a parametric AFT survival regression model based on the Weibull distribution of the survival time. .. seealso:: `AFT Model <https://en.wikipedia.org/wiki/Accelerated_failure_time_model>`_ >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(1.0), 1.0), ... (1e-40, Vectors.sparse(1, [], []), 0.0)], ["label", "features", "censor"]) >>> aftsr = AFTSurvivalRegression() >>> aftsr.setMaxIter(10) AFTSurvivalRegression... >>> aftsr.getMaxIter() 10 >>> aftsr.clear(aftsr.maxIter) >>> model = aftsr.fit(df) >>> model.setFeaturesCol("features") AFTSurvivalRegressionModel... >>> model.predict(Vectors.dense(6.3)) 1.0 >>> model.predictQuantiles(Vectors.dense(6.3)) DenseVector([0.0101, 0.0513, 0.1054, 0.2877, 0.6931, 1.3863, 2.3026, 2.9957, 4.6052]) >>> model.transform(df).show() +-------+---------+------+----------+ | label| features|censor|prediction| +-------+---------+------+----------+ | 1.0| [1.0]| 1.0| 1.0| |1.0E-40|(1,[],[])| 0.0| 1.0| +-------+---------+------+----------+ ... >>> aftsr_path = temp_path + "/aftsr" >>> aftsr.save(aftsr_path) >>> aftsr2 = AFTSurvivalRegression.load(aftsr_path) >>> aftsr2.getMaxIter() 100 >>> model_path = temp_path + "/aftsr_model" >>> model.save(model_path) >>> model2 = AFTSurvivalRegressionModel.load(model_path) >>> model.coefficients == model2.coefficients True >>> model.intercept == model2.intercept True >>> model.scale == model2.scale True .. versionadded:: 1.6.0 """ @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", fitIntercept=True, maxIter=100, tol=1E-6, censorCol="censor", quantileProbabilities=list([0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99]), quantilesCol=None, aggregationDepth=2): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ fitIntercept=True, maxIter=100, tol=1E-6, censorCol="censor", \ quantileProbabilities=[0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99], \ quantilesCol=None, aggregationDepth=2) """ super(AFTSurvivalRegression, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.AFTSurvivalRegression", self.uid) self._setDefault(censorCol="censor", quantileProbabilities=[0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99], maxIter=100, tol=1E-6) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("1.6.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", fitIntercept=True, maxIter=100, tol=1E-6, censorCol="censor", quantileProbabilities=list([0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99]), quantilesCol=None, aggregationDepth=2): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ fitIntercept=True, maxIter=100, tol=1E-6, censorCol="censor", \ quantileProbabilities=[0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99], \ quantilesCol=None, aggregationDepth=2): """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return AFTSurvivalRegressionModel(java_model) @since("1.6.0") def setCensorCol(self, value): """ Sets the value of :py:attr:`censorCol`. """ return self._set(censorCol=value) @since("1.6.0") def setQuantileProbabilities(self, value): """ Sets the value of :py:attr:`quantileProbabilities`. """ return self._set(quantileProbabilities=value) @since("1.6.0") def setQuantilesCol(self, value): """ Sets the value of :py:attr:`quantilesCol`. """ return self._set(quantilesCol=value) @since("1.6.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("1.6.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("1.6.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("1.6.0") def setLabelCol(self, value): """ Sets the value of :py:attr:`labelCol`. """ return self._set(labelCol=value) @since("1.6.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("1.6.0") def setFitIntercept(self, value): """ Sets the value of :py:attr:`fitIntercept`. """ return self._set(fitIntercept=value) @since("2.1.0") def setAggregationDepth(self, value): """ Sets the value of :py:attr:`aggregationDepth`. """ return self._set(aggregationDepth=value) class AFTSurvivalRegressionModel(JavaModel, _AFTSurvivalRegressionParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`AFTSurvivalRegression`. .. versionadded:: 1.6.0 """ @since("3.0.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("3.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("3.0.0") def setQuantileProbabilities(self, value): """ Sets the value of :py:attr:`quantileProbabilities`. """ return self._set(quantileProbabilities=value) @since("3.0.0") def setQuantilesCol(self, value): """ Sets the value of :py:attr:`quantilesCol`. """ return self._set(quantilesCol=value) @property @since("2.0.0") def coefficients(self): """ Model coefficients. """ return self._call_java("coefficients") @property @since("1.6.0") def intercept(self): """ Model intercept. """ return self._call_java("intercept") @property @since("1.6.0") def scale(self): """ Model scale parameter. """ return self._call_java("scale") @since("2.0.0") def predictQuantiles(self, features): """ Predicted Quantiles """ return self._call_java("predictQuantiles", features) @since("2.0.0") def predict(self, features): """ Predicted value """ return self._call_java("predict", features) class _GeneralizedLinearRegressionParams(_JavaPredictorParams, HasFitIntercept, HasMaxIter, HasTol, HasRegParam, HasWeightCol, HasSolver, HasAggregationDepth): """ Params for :py:class:`GeneralizedLinearRegression` and :py:class:`GeneralizedLinearRegressionModel`. .. versionadded:: 3.0.0 """ family = Param(Params._dummy(), "family", "The name of family which is a description of " + "the error distribution to be used in the model. Supported options: " + "gaussian (default), binomial, poisson, gamma and tweedie.", typeConverter=TypeConverters.toString) link = Param(Params._dummy(), "link", "The name of link function which provides the " + "relationship between the linear predictor and the mean of the distribution " + "function. Supported options: identity, log, inverse, logit, probit, cloglog " + "and sqrt.", typeConverter=TypeConverters.toString) linkPredictionCol = Param(Params._dummy(), "linkPredictionCol", "link prediction (linear " + "predictor) column name", typeConverter=TypeConverters.toString) variancePower = Param(Params._dummy(), "variancePower", "The power in the variance function " + "of the Tweedie distribution which characterizes the relationship " + "between the variance and mean of the distribution. Only applicable " + "for the Tweedie family. Supported values: 0 and [1, Inf).", typeConverter=TypeConverters.toFloat) linkPower = Param(Params._dummy(), "linkPower", "The index in the power link function. " + "Only applicable to the Tweedie family.", typeConverter=TypeConverters.toFloat) solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " + "options: irls.", typeConverter=TypeConverters.toString) offsetCol = Param(Params._dummy(), "offsetCol", "The offset column name. If this is not set " + "or empty, we treat all instance offsets as 0.0", typeConverter=TypeConverters.toString) @since("2.0.0") def getFamily(self): """ Gets the value of family or its default value. """ return self.getOrDefault(self.family) @since("2.0.0") def getLinkPredictionCol(self): """ Gets the value of linkPredictionCol or its default value. """ return self.getOrDefault(self.linkPredictionCol) @since("2.0.0") def getLink(self): """ Gets the value of link or its default value. """ return self.getOrDefault(self.link) @since("2.2.0") def getVariancePower(self): """ Gets the value of variancePower or its default value. """ return self.getOrDefault(self.variancePower) @since("2.2.0") def getLinkPower(self): """ Gets the value of linkPower or its default value. """ return self.getOrDefault(self.linkPower) @since("2.3.0") def getOffsetCol(self): """ Gets the value of offsetCol or its default value. """ return self.getOrDefault(self.offsetCol) @inherit_doc class GeneralizedLinearRegression(JavaPredictor, _GeneralizedLinearRegressionParams, JavaMLWritable, JavaMLReadable): """ Generalized Linear Regression. Fit a Generalized Linear Model specified by giving a symbolic description of the linear predictor (link function) and a description of the error distribution (family). It supports "gaussian", "binomial", "poisson", "gamma" and "tweedie" as family. Valid link functions for each family is listed below. The first link function of each family is the default one. * "gaussian" -> "identity", "log", "inverse" * "binomial" -> "logit", "probit", "cloglog" * "poisson" -> "log", "identity", "sqrt" * "gamma" -> "inverse", "identity", "log" * "tweedie" -> power link function specified through "linkPower". \ The default link power in the tweedie family is 1 - variancePower. .. seealso:: `GLM <https://en.wikipedia.org/wiki/Generalized_linear_model>`_ >>> from pyspark.ml.linalg import Vectors >>> df = spark.createDataFrame([ ... (1.0, Vectors.dense(0.0, 0.0)), ... (1.0, Vectors.dense(1.0, 2.0)), ... (2.0, Vectors.dense(0.0, 0.0)), ... (2.0, Vectors.dense(1.0, 1.0)),], ["label", "features"]) >>> glr = GeneralizedLinearRegression(family="gaussian", link="identity", linkPredictionCol="p") >>> glr.setRegParam(0.1) GeneralizedLinearRegression... >>> glr.getRegParam() 0.1 >>> glr.clear(glr.regParam) >>> glr.setMaxIter(10) GeneralizedLinearRegression... >>> glr.getMaxIter() 10 >>> glr.clear(glr.maxIter) >>> model = glr.fit(df) >>> model.setFeaturesCol("features") GeneralizedLinearRegressionModel... >>> model.getMaxIter() 25 >>> model.getAggregationDepth() 2 >>> transformed = model.transform(df) >>> abs(transformed.head().prediction - 1.5) < 0.001 True >>> abs(transformed.head().p - 1.5) < 0.001 True >>> model.coefficients DenseVector([1.5..., -1.0...]) >>> model.numFeatures 2 >>> abs(model.intercept - 1.5) < 0.001 True >>> glr_path = temp_path + "/glr" >>> glr.save(glr_path) >>> glr2 = GeneralizedLinearRegression.load(glr_path) >>> glr.getFamily() == glr2.getFamily() True >>> model_path = temp_path + "/glr_model" >>> model.save(model_path) >>> model2 = GeneralizedLinearRegressionModel.load(model_path) >>> model.intercept == model2.intercept True >>> model.coefficients[0] == model2.coefficients[0] True .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, labelCol="label", featuresCol="features", predictionCol="prediction", family="gaussian", link=None, fitIntercept=True, maxIter=25, tol=1e-6, regParam=0.0, weightCol=None, solver="irls", linkPredictionCol=None, variancePower=0.0, linkPower=None, offsetCol=None, aggregationDepth=2): """ __init__(self, labelCol="label", featuresCol="features", predictionCol="prediction", \ family="gaussian", link=None, fitIntercept=True, maxIter=25, tol=1e-6, \ regParam=0.0, weightCol=None, solver="irls", linkPredictionCol=None, \ variancePower=0.0, linkPower=None, offsetCol=None, aggregationDepth=2) """ super(GeneralizedLinearRegression, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.GeneralizedLinearRegression", self.uid) self._setDefault(family="gaussian", maxIter=25, tol=1e-6, regParam=0.0, solver="irls", variancePower=0.0, aggregationDepth=2) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("2.0.0") def setParams(self, labelCol="label", featuresCol="features", predictionCol="prediction", family="gaussian", link=None, fitIntercept=True, maxIter=25, tol=1e-6, regParam=0.0, weightCol=None, solver="irls", linkPredictionCol=None, variancePower=0.0, linkPower=None, offsetCol=None, aggregationDepth=2): """ setParams(self, labelCol="label", featuresCol="features", predictionCol="prediction", \ family="gaussian", link=None, fitIntercept=True, maxIter=25, tol=1e-6, \ regParam=0.0, weightCol=None, solver="irls", linkPredictionCol=None, \ variancePower=0.0, linkPower=None, offsetCol=None, aggregationDepth=2) Sets params for generalized linear regression. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return GeneralizedLinearRegressionModel(java_model) @since("2.0.0") def setFamily(self, value): """ Sets the value of :py:attr:`family`. """ return self._set(family=value) @since("2.0.0") def setLinkPredictionCol(self, value): """ Sets the value of :py:attr:`linkPredictionCol`. """ return self._set(linkPredictionCol=value) @since("2.0.0") def setLink(self, value): """ Sets the value of :py:attr:`link`. """ return self._set(link=value) @since("2.2.0") def setVariancePower(self, value): """ Sets the value of :py:attr:`variancePower`. """ return self._set(variancePower=value) @since("2.2.0") def setLinkPower(self, value): """ Sets the value of :py:attr:`linkPower`. """ return self._set(linkPower=value) @since("2.3.0") def setOffsetCol(self, value): """ Sets the value of :py:attr:`offsetCol`. """ return self._set(offsetCol=value) @since("2.0.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.0.0") def setRegParam(self, value): """ Sets the value of :py:attr:`regParam`. """ return self._set(regParam=value) @since("2.0.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("2.2.0") def setFitIntercept(self, value): """ Sets the value of :py:attr:`fitIntercept`. """ return self._set(fitIntercept=value) @since("2.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("2.0.0") def setSolver(self, value): """ Sets the value of :py:attr:`solver`. """ return self._set(solver=value) @since("3.0.0") def setAggregationDepth(self, value): """ Sets the value of :py:attr:`aggregationDepth`. """ return self._set(aggregationDepth=value) class GeneralizedLinearRegressionModel(JavaPredictionModel, _GeneralizedLinearRegressionParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by :class:`GeneralizedLinearRegression`. .. versionadded:: 2.0.0 """ @since("3.0.0") def setLinkPredictionCol(self, value): """ Sets the value of :py:attr:`linkPredictionCol`. """ return self._set(linkPredictionCol=value) @property @since("2.0.0") def coefficients(self): """ Model coefficients. """ return self._call_java("coefficients") @property @since("2.0.0") def intercept(self): """ Model intercept. """ return self._call_java("intercept") @property @since("2.0.0") def summary(self): """ Gets summary (e.g. residuals, deviance, pValues) of model on training set. An exception is thrown if `trainingSummary is None`. """ if self.hasSummary: return GeneralizedLinearRegressionTrainingSummary( super(GeneralizedLinearRegressionModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("2.0.0") def evaluate(self, dataset): """ Evaluates the model on a test dataset. :param dataset: Test dataset to evaluate model on, where dataset is an instance of :py:class:`pyspark.sql.DataFrame` """ if not isinstance(dataset, DataFrame): raise ValueError("dataset must be a DataFrame but got %s." % type(dataset)) java_glr_summary = self._call_java("evaluate", dataset) return GeneralizedLinearRegressionSummary(java_glr_summary) class GeneralizedLinearRegressionSummary(JavaWrapper): """ Generalized linear regression results evaluated on a dataset. .. versionadded:: 2.0.0 """ @property @since("2.0.0") def predictions(self): """ Predictions output by the model's `transform` method. """ return self._call_java("predictions") @property @since("2.0.0") def predictionCol(self): """ Field in :py:attr:`predictions` which gives the predicted value of each instance. This is set to a new column name if the original model's `predictionCol` is not set. """ return self._call_java("predictionCol") @property @since("2.2.0") def numInstances(self): """ Number of instances in DataFrame predictions. """ return self._call_java("numInstances") @property @since("2.0.0") def rank(self): """ The numeric rank of the fitted linear model. """ return self._call_java("rank") @property @since("2.0.0") def degreesOfFreedom(self): """ Degrees of freedom. """ return self._call_java("degreesOfFreedom") @property @since("2.0.0") def residualDegreeOfFreedom(self): """ The residual degrees of freedom. """ return self._call_java("residualDegreeOfFreedom") @property @since("2.0.0") def residualDegreeOfFreedomNull(self): """ The residual degrees of freedom for the null model. """ return self._call_java("residualDegreeOfFreedomNull") @since("2.0.0") def residuals(self, residualsType="deviance"): """ Get the residuals of the fitted model by type. :param residualsType: The type of residuals which should be returned. Supported options: deviance (default), pearson, working, and response. """ return self._call_java("residuals", residualsType) @property @since("2.0.0") def nullDeviance(self): """ The deviance for the null model. """ return self._call_java("nullDeviance") @property @since("2.0.0") def deviance(self): """ The deviance for the fitted model. """ return self._call_java("deviance") @property @since("2.0.0") def dispersion(self): """ The dispersion of the fitted model. It is taken as 1.0 for the "binomial" and "poisson" families, and otherwise estimated by the residual Pearson's Chi-Squared statistic (which is defined as sum of the squares of the Pearson residuals) divided by the residual degrees of freedom. """ return self._call_java("dispersion") @property @since("2.0.0") def aic(self): """ Akaike's "An Information Criterion"(AIC) for the fitted model. """ return self._call_java("aic") @inherit_doc class GeneralizedLinearRegressionTrainingSummary(GeneralizedLinearRegressionSummary): """ Generalized linear regression training results. .. versionadded:: 2.0.0 """ @property @since("2.0.0") def numIterations(self): """ Number of training iterations. """ return self._call_java("numIterations") @property @since("2.0.0") def solver(self): """ The numeric solver used for training. """ return self._call_java("solver") @property @since("2.0.0") def coefficientStandardErrors(self): """ Standard error of estimated coefficients and intercept. If :py:attr:`GeneralizedLinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. """ return self._call_java("coefficientStandardErrors") @property @since("2.0.0") def tValues(self): """ T-statistic of estimated coefficients and intercept. If :py:attr:`GeneralizedLinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. """ return self._call_java("tValues") @property @since("2.0.0") def pValues(self): """ Two-sided p-value of estimated coefficients and intercept. If :py:attr:`GeneralizedLinearRegression.fitIntercept` is set to True, then the last element returned corresponds to the intercept. """ return self._call_java("pValues") def __repr__(self): return self._call_java("toString") class _FactorizationMachinesParams(_JavaPredictorParams, HasMaxIter, HasStepSize, HasTol, HasSolver, HasSeed, HasFitIntercept, HasRegParam): """ Params for :py:class:`FMRegressor`, :py:class:`FMRegressionModel`, :py:class:`FMClassifier` and :py:class:`FMClassifierModel`. .. versionadded:: 3.0.0 """ factorSize = Param(Params._dummy(), "factorSize", "Dimensionality of the factor vectors, " + "which are used to get pairwise interactions between variables", typeConverter=TypeConverters.toInt) fitLinear = Param(Params._dummy(), "fitLinear", "whether to fit linear term (aka 1-way term)", typeConverter=TypeConverters.toBoolean) miniBatchFraction = Param(Params._dummy(), "miniBatchFraction", "fraction of the input data " + "set that should be used for one iteration of gradient descent", typeConverter=TypeConverters.toFloat) initStd = Param(Params._dummy(), "initStd", "standard deviation of initial coefficients", typeConverter=TypeConverters.toFloat) solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " + "options: gd, adamW. (Default adamW)", typeConverter=TypeConverters.toString) @since("3.0.0") def getFactorSize(self): """ Gets the value of factorSize or its default value. """ return self.getOrDefault(self.factorSize) @since("3.0.0") def getFitLinear(self): """ Gets the value of fitLinear or its default value. """ return self.getOrDefault(self.fitLinear) @since("3.0.0") def getMiniBatchFraction(self): """ Gets the value of miniBatchFraction or its default value. """ return self.getOrDefault(self.miniBatchFraction) @since("3.0.0") def getInitStd(self): """ Gets the value of initStd or its default value. """ return self.getOrDefault(self.initStd) @inherit_doc class FMRegressor(JavaPredictor, _FactorizationMachinesParams, JavaMLWritable, JavaMLReadable): """ Factorization Machines learning algorithm for regression. solver Supports: * gd (normal mini-batch gradient descent) * adamW (default) >>> from pyspark.ml.linalg import Vectors >>> from pyspark.ml.regression import FMRegressor >>> df = spark.createDataFrame([ ... (2.0, Vectors.dense(2.0)), ... (1.0, Vectors.dense(1.0)), ... (0.0, Vectors.sparse(1, [], []))], ["label", "features"]) >>> >>> fm = FMRegressor(factorSize=2) >>> fm.setSeed(16) FMRegressor... >>> model = fm.fit(df) >>> model.getMaxIter() 100 >>> test0 = spark.createDataFrame([ ... (Vectors.dense(-2.0),), ... (Vectors.dense(0.5),), ... (Vectors.dense(1.0),), ... (Vectors.dense(4.0),)], ["features"]) >>> model.transform(test0).show(10, False) +--------+-------------------+ |features|prediction | +--------+-------------------+ |[-2.0] |-1.9989237712341565| |[0.5] |0.4956682219523814 | |[1.0] |0.994586620589689 | |[4.0] |3.9880970124135344 | +--------+-------------------+ ... >>> model.intercept -0.0032501766849261557 >>> model.linear DenseVector([0.9978]) >>> model.factors DenseMatrix(1, 2, [0.0173, 0.0021], 1) .. versionadded:: 3.0.0 """ factorSize = Param(Params._dummy(), "factorSize", "Dimensionality of the factor vectors, " + "which are used to get pairwise interactions between variables", typeConverter=TypeConverters.toInt) fitLinear = Param(Params._dummy(), "fitLinear", "whether to fit linear term (aka 1-way term)", typeConverter=TypeConverters.toBoolean) miniBatchFraction = Param(Params._dummy(), "miniBatchFraction", "fraction of the input data " + "set that should be used for one iteration of gradient descent", typeConverter=TypeConverters.toFloat) initStd = Param(Params._dummy(), "initStd", "standard deviation of initial coefficients", typeConverter=TypeConverters.toFloat) solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " + "options: gd, adamW. (Default adamW)", typeConverter=TypeConverters.toString) @keyword_only def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, tol=1e-6, solver="adamW", seed=None): """ __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, \ miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, \ tol=1e-6, solver="adamW", seed=None) """ super(FMRegressor, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.regression.FMRegressor", self.uid) self._setDefault(factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, tol=1e-6, solver="adamW") kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("3.0.0") def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, tol=1e-6, solver="adamW", seed=None): """ setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \ factorSize=8, fitIntercept=True, fitLinear=True, regParam=0.0, \ miniBatchFraction=1.0, initStd=0.01, maxIter=100, stepSize=1.0, \ tol=1e-6, solver="adamW", seed=None) Sets Params for FMRegressor. """ kwargs = self._input_kwargs return self._set(**kwargs) def _create_model(self, java_model): return FMRegressionModel(java_model) @since("3.0.0") def setFactorSize(self, value): """ Sets the value of :py:attr:`factorSize`. """ return self._set(factorSize=value) @since("3.0.0") def setFitLinear(self, value): """ Sets the value of :py:attr:`fitLinear`. """ return self._set(fitLinear=value) @since("3.0.0") def setMiniBatchFraction(self, value): """ Sets the value of :py:attr:`miniBatchFraction`. """ return self._set(miniBatchFraction=value) @since("3.0.0") def setInitStd(self, value): """ Sets the value of :py:attr:`initStd`. """ return self._set(initStd=value) @since("3.0.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("3.0.0") def setStepSize(self, value): """ Sets the value of :py:attr:`stepSize`. """ return self._set(stepSize=value) @since("3.0.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("3.0.0") def setSolver(self, value): """ Sets the value of :py:attr:`solver`. """ return self._set(solver=value) @since("3.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("3.0.0") def setFitIntercept(self, value): """ Sets the value of :py:attr:`fitIntercept`. """ return self._set(fitIntercept=value) @since("3.0.0") def setRegParam(self, value): """ Sets the value of :py:attr:`regParam`. """ return self._set(regParam=value) class FMRegressionModel(JavaPredictionModel, _FactorizationMachinesParams, JavaMLWritable, JavaMLReadable): """ Model fitted by :class:`FMRegressor`. .. versionadded:: 3.0.0 """ @property @since("3.0.0") def intercept(self): """ Model intercept. """ return self._call_java("intercept") @property @since("3.0.0") def linear(self): """ Model linear term. """ return self._call_java("linear") @property @since("3.0.0") def factors(self): """ Model factor term. """ return self._call_java("factors") if __name__ == "__main__": import doctest import pyspark.ml.regression from pyspark.sql import SparkSession globs = pyspark.ml.regression.__dict__.copy() # The small batch size here ensures that we see multiple batches, # even in these small test examples: spark = SparkSession.builder\ .master("local[2]")\ .appName("ml.regression tests")\ .getOrCreate() sc = spark.sparkContext globs['sc'] = sc globs['spark'] = spark import tempfile temp_path = tempfile.mkdtemp() globs['temp_path'] = temp_path try: (failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS) spark.stop() finally: from shutil import rmtree try: rmtree(temp_path) except OSError: pass if failure_count: sys.exit(-1)
jkbradley/spark
python/pyspark/ml/regression.py
Python
apache-2.0
87,709
[ "Gaussian" ]
8633c960479b9d70cbbb9989e6b8a45b0f03fcb5f3f9fddb0a2dc7c377e98247
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Test for the piezo tensor class """ __author__ = "Handong Ling" __version__ = "0.1" __maintainer__ = "Handong Ling" __email__ = "handongling@berkeley.edu" __status__ = "Development" __date__ = "4/23/19" import os import unittest import numpy as np import pymatgen from pymatgen.analysis.piezo import PiezoTensor from pymatgen.analysis.piezo_sensitivity import * from pymatgen.symmetry import site_symmetries as ss from pymatgen.symmetry.analyzer import SpacegroupAnalyzer as sga from pymatgen.util.testing import PymatgenTest try: from phonopy import Phonopy except ImportError: Phonopy = None test_dir = os.path.join(PymatgenTest.TEST_FILES_DIR, "piezo_sensitivity") class PiezoSensitivityTest(PymatgenTest): def setUp(self): self.piezo_struc = self.get_structure("Pb2TiZrO6") self.IST = np.load(os.path.join(test_dir, "pztist.npy"), allow_pickle=True) self.BEC = np.load(os.path.join(test_dir, "pztborn.npy"), allow_pickle=True) self.FCM = np.load(os.path.join(test_dir, "pztfcm.npy"), allow_pickle=True) self.pointops = np.load(os.path.join(test_dir, "pointops.npy"), allow_pickle=True) self.sharedops = np.load(os.path.join(test_dir, "sharedops.npy"), allow_pickle=True) self.BEC_operations = np.load(os.path.join(test_dir, "becops.npy"), allow_pickle=True) self.IST_operations = np.load(os.path.join(test_dir, "istops.npy"), allow_pickle=True) self.FCM_operations = np.load(os.path.join(test_dir, "fcmops.npy"), allow_pickle=True) self.piezo = np.array( [ [ [5.32649351e-03, -1.33404642e-14, -6.86958142e02], [-1.33404642e-14, 4.95526253e-03, -5.60353712e-13], [-6.86958142e02, -5.60353712e-13, 1.33209787e-02], ], [ [4.86622567e-03, 3.14840965e-13, -7.41608150e-13], [3.14840965e-13, 5.23745666e-03, -6.68536818e02], [-7.41608150e-13, -6.68536818e02, 1.35025755e-02], ], [ [-1.01086427e02, 3.20177004e-14, -3.68487214e-14], [3.20177004e-14, -1.01086427e02, 1.22012318e-14], [-3.68487214e-14, 1.22012318e-14, -5.32241086e02], ], ] ) def test_BornEffectiveChargeTensor(self): bec = BornEffectiveCharge(self.piezo_struc, self.BEC, self.pointops) self.assertArrayAlmostEqual(self.BEC, bec.bec) def test_InternalStrainTensor(self): ist = InternalStrainTensor(self.piezo_struc, self.IST, self.pointops) self.assertArrayAlmostEqual(ist.ist, self.IST) def test_ForceConstantMatrix(self): fcmt = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) self.assertArrayAlmostEqual(fcmt.fcm, self.FCM) def test_get_BEC_operations(self): bec = BornEffectiveCharge(self.piezo_struc, self.BEC, self.pointops) bec.get_BEC_operations() self.assertTrue(np.all(self.BEC_operations == bec.BEC_operations)) def test_get_rand_BEC(self): bec = BornEffectiveCharge(self.piezo_struc, self.BEC, self.pointops) bec.get_BEC_operations() rand_BEC = bec.get_rand_BEC() for i in range(len(self.BEC_operations)): for j in range(len(self.BEC_operations[i][2])): self.assertTrue( np.allclose( rand_BEC[self.BEC_operations[i][0]], self.BEC_operations[i][2][j].transform_tensor(rand_BEC[self.BEC_operations[i][1]]), atol=1e-03, ) ) def test_get_rand_IST(self): ist = InternalStrainTensor(self.piezo_struc, self.IST, self.pointops) ist.get_IST_operations() rand_IST = ist.get_rand_IST() for i in range(len(self.IST_operations)): for j in range(len(self.IST_operations[i])): self.assertTrue( np.allclose( rand_IST[i], self.IST_operations[i][j][1].transform_tensor(rand_IST[self.IST_operations[i][j][0]]), atol=1e-03, ) ) def test_get_FCM_operations(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() self.assertTrue(np.all(fcm.FCM_operations == self.FCM_operations)) def test_get_unstable_FCM(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() rand_FCM = fcm.get_unstable_FCM() rand_FCM = np.reshape(rand_FCM, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), rand_FCM[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) def test_get_FCM_symmetry(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() fcm = fcm.get_symmetrized_FCM(np.random.rand(30, 30)) fcm = np.reshape(fcm, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( fcm[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), fcm[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) def test_get_asum_FCM(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() rand_FCM = fcm.get_unstable_FCM() rand_FCM = fcm.get_asum_FCM(rand_FCM) rand_FCM = np.reshape(rand_FCM, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), rand_FCM[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) for i in range(len(rand_FCM)): asum1 = np.zeros([3, 3]) asum2 = np.zeros([3, 3]) for j in range(len(rand_FCM[i])): asum1 += rand_FCM[i][j] asum2 += rand_FCM[j][i] self.assertTrue(np.allclose(asum1, np.zeros([3, 3]), atol=1e-05)) self.assertTrue(np.allclose(asum2, np.zeros([3, 3]), atol=1e-05)) def test_get_stable_FCM(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() rand_FCM = fcm.get_unstable_FCM() rand_FCM1 = fcm.get_stable_FCM(rand_FCM) eigs, vecs = np.linalg.eig(rand_FCM1) eigsort = np.argsort(np.abs(eigs)) for i in range(3, len(eigs)): self.assertTrue(eigs[eigsort[i]] < 1e-06) rand_FCM1 = np.reshape(rand_FCM1, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM1[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), rand_FCM1[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) for i in range(len(rand_FCM1)): asum1 = np.zeros([3, 3]) asum2 = np.zeros([3, 3]) for j in range(len(rand_FCM1[i])): asum1 += rand_FCM1[i][j] asum2 += rand_FCM1[j][i] self.assertTrue(np.allclose(asum1, np.zeros([3, 3]), atol=1e-05)) self.assertTrue(np.allclose(asum2, np.zeros([3, 3]), atol=1e-05)) @unittest.skipIf(Phonopy is None, "Phonopy not present") def test_rand_FCM(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) fcm.get_FCM_operations() rand_FCM = fcm.get_rand_FCM() structure = pymatgen.io.phonopy.get_phonopy_structure(self.piezo_struc) pnstruc = Phonopy(structure, np.eye(3), np.eye(3)) pnstruc.set_force_constants(rand_FCM) dyn = pnstruc.get_dynamical_matrix_at_q([0, 0, 0]) dyn = np.reshape(dyn, (10, 3, 10, 3)).swapaxes(1, 2) dyn = np.real(dyn) numsites = len(self.piezo_struc) masses = [] for j in range(numsites): masses.append(self.piezo_struc.sites[j].specie.atomic_mass) dynmass = np.zeros([numsites, numsites, 3, 3]) for m in range(numsites): for n in range(numsites): dynmass[m][n] = dyn[m][n] / np.sqrt(masses[m]) / np.sqrt(masses[n]) dynmass = np.reshape(np.swapaxes(dynmass, 1, 2), (10 * 3, 10 * 3)) eigs, vecs = np.linalg.eig(dynmass) eigsort = np.argsort(np.abs(eigs)) for i in range(3, len(eigs)): self.assertTrue(eigs[eigsort[i]] < 1e-06) # rand_FCM1 = np.reshape(rand_FCM1, (10,3,10,3)).swapaxes(1,2) dynmass = np.reshape(dynmass, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( dynmass[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), dynmass[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) for i in range(len(dynmass)): asum1 = np.zeros([3, 3]) asum2 = np.zeros([3, 3]) for j in range(len(dynmass[i])): asum1 += dynmass[i][j] asum2 += dynmass[j][i] self.assertTrue(np.allclose(asum1, np.zeros([3, 3]), atol=1e-05)) self.assertTrue(np.allclose(asum2, np.zeros([3, 3]), atol=1e-05)) def test_get_piezo(self): piezo = get_piezo(self.BEC, self.IST, self.FCM) self.assertTrue(np.allclose(piezo, self.piezo, atol=1e-05)) @unittest.skipIf(Phonopy is None, "Phonopy not present") def test_rand_piezo(self): rand_BEC, rand_IST, rand_FCM, piezo = rand_piezo( self.piezo_struc, self.pointops, self.sharedops, self.BEC, self.IST, self.FCM, ) for i in range(len(self.BEC_operations)): for j in range(len(self.BEC_operations[i][2])): self.assertTrue( np.allclose( rand_BEC[self.BEC_operations[i][0]], self.BEC_operations[i][2][j].transform_tensor(rand_BEC[self.BEC_operations[i][1]]), atol=1e-03, ) ) for i in range(len(self.IST_operations)): for j in range(len(self.IST_operations[i])): self.assertTrue( np.allclose( rand_IST[i], self.IST_operations[i][j][1].transform_tensor(rand_IST[self.IST_operations[i][j][0]]), atol=1e-03, ) ) structure = pymatgen.io.phonopy.get_phonopy_structure(self.piezo_struc) pnstruc = Phonopy(structure, np.eye(3), np.eye(3)) pnstruc.set_force_constants(rand_FCM) dyn = pnstruc.get_dynamical_matrix_at_q([0, 0, 0]) dyn = np.reshape(dyn, (10, 3, 10, 3)).swapaxes(1, 2) dyn = np.real(dyn) numsites = len(self.piezo_struc) masses = [] for j in range(numsites): masses.append(self.piezo_struc.sites[j].specie.atomic_mass) dynmass = np.zeros([numsites, numsites, 3, 3]) for m in range(numsites): for n in range(numsites): dynmass[m][n] = dyn[m][n] / np.sqrt(masses[m]) / np.sqrt(masses[n]) dynmass = np.reshape(np.swapaxes(dynmass, 1, 2), (10 * 3, 10 * 3)) eigs, vecs = np.linalg.eig(dynmass) eigsort = np.argsort(np.abs(eigs)) for i in range(3, len(eigs)): self.assertTrue(eigs[eigsort[i]] < 1e-06) # rand_FCM1 = np.reshape(rand_FCM1, (10,3,10,3)).swapaxes(1,2) dynmass = np.reshape(dynmass, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): self.assertTrue( np.allclose( self.FCM_operations[i][4][j].transform_tensor( dynmass[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), dynmass[self.FCM_operations[i][0]][self.FCM_operations[i][1]], atol=1e-04, ) ) for i in range(len(dynmass)): asum1 = np.zeros([3, 3]) asum2 = np.zeros([3, 3]) for j in range(len(dynmass[i])): asum1 += dynmass[i][j] asum2 += dynmass[j][i] self.assertTrue(np.allclose(asum1, np.zeros([3, 3]), atol=1e-05)) self.assertTrue(np.allclose(asum2, np.zeros([3, 3]), atol=1e-05)) if __name__ == "__main__": unittest.main()
vorwerkc/pymatgen
pymatgen/analysis/tests/test_piezo_sensitivity.py
Python
mit
14,582
[ "phonopy", "pymatgen" ]
c68bba87de6509fb19d20580d16ba11803b580185facb267256ad30918ef76e4
from math import pi, cos, sin, sqrt, acos from ase.atoms import Atoms from ase.parallel import paropen def read_sdf(fileobj): if isinstance(fileobj, str): fileobj = open(fileobj) lines = fileobj.readlines() # first three lines header del lines[:3] # L1 = lines.pop(0).split() natoms = int(L1[0]) positions = [] symbols = [] for line in lines[:natoms]: x, y, z, symbol = line.split()[:4] symbols.append(symbol) positions.append([float(x), float(y), float(z)]) return Atoms(symbols=symbols, positions=positions)
grhawk/ASE
tools/ase/io/sdf.py
Python
gpl-2.0
591
[ "ASE" ]
94167bc84a1c746d6711fbc48138464740fd2186a50e95c065f429a3feb88eaf
""" Course Outline page in Studio. """ from bok_choy.page_object import PageObject from bok_choy.promise import EmptyPromise from .course_page import CoursePage from .unit import UnitPage class CourseOutlineContainer(object): """ A mixin to a CourseOutline page object that adds the ability to load a child page object by title. CHILD_CLASS must be a :class:`CourseOutlineChild` subclass. """ CHILD_CLASS = None def child(self, title, child_class=None): """ :type self: object """ if not child_class: child_class = self.CHILD_CLASS return child_class( self.browser, self.q(css=child_class.BODY_SELECTOR).filter( lambda el: title in [inner.text for inner in el.find_elements_by_css_selector(child_class.NAME_SELECTOR)] ).attrs('data-locator')[0] ) class CourseOutlineChild(PageObject): """ A mixin to a CourseOutline page object that will be used as a child of :class:`CourseOutlineContainer`. """ NAME_SELECTOR = None BODY_SELECTOR = None def __init__(self, browser, locator): super(CourseOutlineChild, self).__init__(browser) self.locator = locator def is_browser_on_page(self): return self.q(css='{}[data-locator="{}"]'.format(self.BODY_SELECTOR, self.locator)).present @property def name(self): """ Return the display name of this object. """ titles = self.q(css=self._bounded_selector(self.NAME_SELECTOR)).text if titles: return titles[0] else: return None def __repr__(self): return "{}(<browser>, {!r})".format(self.__class__.__name__, self.locator) def _bounded_selector(self, selector): """ Return `selector`, but limited to this particular `CourseOutlineChild` context """ return '{}[data-locator="{}"] {}'.format( self.BODY_SELECTOR, self.locator, selector ) class CourseOutlineUnit(CourseOutlineChild): """ PageObject that wraps a unit link on the Studio Course Overview page. """ url = None BODY_SELECTOR = '.courseware-unit' NAME_SELECTOR = '.unit-name' def go_to(self): """ Open the unit page linked to by this unit link, and return an initialized :class:`.UnitPage` for that unit. """ return UnitPage(self.browser, self.locator).visit() class CourseOutlineSubsection(CourseOutlineChild, CourseOutlineContainer): """ :class`.PageObject` that wraps a subsection block on the Studio Course Overview page. """ url = None BODY_SELECTOR = '.courseware-subsection' NAME_SELECTOR = '.subsection-name-value' CHILD_CLASS = CourseOutlineUnit def unit(self, title): """ Return the :class:`.CourseOutlineUnit with the title `title`. """ return self.child(title) def toggle_expand(self): """ Toggle the expansion of this subsection. """ self.browser.execute_script("jQuery.fx.off = true;") def subsection_expanded(): return all( self.q(css=self._bounded_selector('.new-unit-item')) .map(lambda el: el.is_displayed()) .results ) currently_expanded = subsection_expanded() self.q(css=self._bounded_selector('.expand-collapse')).first.click() EmptyPromise( lambda: subsection_expanded() != currently_expanded, "Check that the subsection {} has been toggled".format(self.locator) ).fulfill() return self class CourseOutlineSection(CourseOutlineChild, CourseOutlineContainer): """ :class`.PageObject` that wraps a section block on the Studio Course Overview page. """ url = None BODY_SELECTOR = '.courseware-section' NAME_SELECTOR = '.section-name-span' CHILD_CLASS = CourseOutlineSubsection def subsection(self, title): """ Return the :class:`.CourseOutlineSubsection` with the title `title`. """ return self.child(title) class CourseOutlinePage(CoursePage, CourseOutlineContainer): """ Course Outline page in Studio. """ url_path = "course" CHILD_CLASS = CourseOutlineSection def is_browser_on_page(self): return self.q(css='body.view-outline').present def section(self, title): """ Return the :class:`.CourseOutlineSection` with the title `title`. """ return self.child(title) def click_section_name(self, parent_css=''): """ Find and click on first section name in course outline """ self.q(css='{} .section-name'.format(parent_css)).first.click() def get_section_name(self, parent_css='', page_refresh=False): """ Get the list of names of all sections present """ if page_refresh: self.browser.refresh() return self.q(css='{} .section-name'.format(parent_css)).text def section_name_edit_form_present(self, parent_css=''): """ Check that section name edit form present """ return self.q(css='{} .section-name input'.format(parent_css)).present def change_section_name(self, new_name, parent_css=''): """ Change section name of first section present in course outline """ self.click_section_name(parent_css) self.q(css='{} .section-name input'.format(parent_css)).first.fill(new_name) self.q(css='{} .section-name .save-button'.format(parent_css)).first.click() self.wait_for_ajax() def click_release_date(self): """ Open release date edit modal of first section in course outline """ self.q(css='div.section-published-date a.edit-release-date').first.click()
wwj718/murp-edx
common/test/acceptance/pages/studio/overview.py
Python
agpl-3.0
5,973
[ "VisIt" ]
e559c0df69f171ae19fba87fd653750a64169a5e7c45565b541f4e6d2ae4f2a7
""" .. currentmodule:: pygmin.amber Module containing files for simulating bio-molecules using AMBER force-field AMBER ------------------------------------ .. autosummary:: :toctree: generated/ system openmm_potential gmin_potential """
js850/PyGMIN
pygmin/amber/__init__.py
Python
gpl-3.0
267
[ "Amber" ]
f7bfc0927c0bca4e6dc7d1b66f4e88f3bd5b185e5e672e698f80c52cf50d695b
import numpy as np class NETCDFHandler(object): """ Child class to ease netCDF file handling. Usage: * Class variable __file__ contains the netCDF file object * __file__ needs to be properly initialized by parent class * Complex types are supported in the following way: - Define the variable real and imaginary parts with suffixes _r, _i respectively, i.e. test_r, test_i - Use get/set methods appending '*' to variable name, i.e. get('test*'), set('test*', complex_array) """ def close(self): """ Close file """ self.__file__.close() def get(self, name): """ Get variable content :param name: Variable name """ if name[-1] == '*': content = np.empty(self.__file__.variables[name[:-1] + '_r'].shape, dtype=np.complex64) content.real = self.__file__.variables[name[:-1] + '_r'][:] content.imag = self.__file__.variables[name[:-1] + '_i'][:] else: content = self.__file__.variables[name][:] #return content[0] if content.size == 1 else content return content def set(self, name, value): """ Set variable content :param name: Variable name :param value: Variable content """ if name[-1] == '*': self.__file__.variables[name[:-1] + '_r'][:] = value.real self.__file__.variables[name[:-1] + '_i'][:] = value.imag else: self.__file__.variables[name][:] = value
pakodekker/oceansar
oceansar/ocs_io/netcdf.py
Python
gpl-3.0
1,612
[ "NetCDF" ]
73d4da7dd15efbc81f9e304300fb04da9aba797b031b2dc37f72c1cac38bf675
import unittest import os import json from pymatgen.core.periodic_table import Element from pymatgen.phonon.dos import PhononDos, CompletePhononDos from pymatgen.util.testing import PymatgenTest test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') import scipy class DosTest(PymatgenTest): def setUp(self): with open(os.path.join(test_dir, "NaCl_ph_dos.json"), "r") as f: self.dos = PhononDos.from_dict(json.load(f)) with open(os.path.join(test_dir, "NaCl_complete_ph_dos.json"), "r") as f: self.structure = CompletePhononDos.from_dict(json.load(f)).structure def test_properties(self): self.assertAlmostEqual(self.dos.densities[15], 0.0001665998) self.assertAlmostEqual(self.dos.frequencies[20], 0.0894965119) self.assertAlmostEqual(self.dos.get_interpolated_value(3.), 1.2915532670115628) self.assertEqual(len(self.dos.frequencies), 201) self.assertEqual(len(self.dos.densities), 201) def test_get_smeared_densities(self): smeared = self.dos.get_smeared_densities(0.01) self.assertAlmostEqual(smeared[20], 0.00084171007635058825) dens = self.dos.densities self.assertAlmostEqual(sum(dens), sum(smeared)) def test_dict_methods(self): s = json.dumps(self.dos.as_dict()) self.assertIsNotNone(s) self.assertMSONable(self.dos) def test_thermodynamic_functions(self): self.assertAlmostEqual(self.dos.cv(300, structure=self.structure), 48.049349514094615) self.assertAlmostEqual(self.dos.internal_energy(300, structure=self.structure), 15527.592023296782) self.assertAlmostEqual(self.dos.helmholtz_free_energy(300, structure=self.structure), -6998.026586063017) self.assertAlmostEqual(self.dos.entropy(300, structure=self.structure), 75.085395923749076) self.assertAlmostEqual(self.dos.zero_point_energy(structure=self.structure), 4847.4624833147582) class CompleteDosTest(PymatgenTest): def setUp(self): with open(os.path.join(test_dir, "NaCl_complete_ph_dos.json"), "r") as f: self.cdos = CompletePhononDos.from_dict(json.load(f)) def test_properties(self): site_Na = self.cdos.structure[0] site_Cl = self.cdos.structure[1] self.assertEqual(len(self.cdos.frequencies), 201) self.assertAlmostEqual(self.cdos.pdos[site_Na][30], 0.008058208) self.assertAlmostEqual(self.cdos.get_site_dos(site_Na).densities[30], 0.008058208) self.assertAlmostEqual(self.cdos.pdos[site_Cl][30], 0.0119040783) self.assertIn(Element.Na, self.cdos.get_element_dos()) self.assertIn(Element.Cl, self.cdos.get_element_dos()) sum_dos = self.cdos.get_element_dos()[Element.Na] + self.cdos.get_element_dos()[Element.Cl] self.assertArrayAlmostEqual(sum_dos.frequencies, self.cdos.frequencies) self.assertArrayAlmostEqual(sum_dos.densities, self.cdos.densities) def test_dict_methods(self): s = json.dumps(self.cdos.as_dict()) self.assertIsNotNone(s) self.assertMSONable(self.cdos) def test_str(self): self.assertIsNotNone(str(self.cdos)) if __name__ == '__main__': unittest.main()
dongsenfo/pymatgen
pymatgen/phonon/tests/test_dos.py
Python
mit
3,281
[ "pymatgen" ]
7bf60f9309c9e4ac8d9864b26daa8a4bc3815792c67c69806caed6e0d2ac4ded
#! PsiAPI energy example import psi4 psi4.set_output_file("output.dat", False) psi4.set_options({"SCF_TYPE": "DF", "BASIS": "cc-pVDZ", "REFERENCE": "ROHF"}) # just check if it runs :) psi4.wrapper_database.database('scf', 'O24by5mb', cp=1, subset=["4-0.9", "12-0.9", "20-0.9", "23-0.9"]) #psi4.wrapper_database.database('scf', 'O24by5mb', cp=0, subset=["4-0.9", "12-0.9", "20-0.9", "23-0.9"]) psi4.wrapper_database.database('scf', 'O24by5', cp=1, subset=["4-0.9", "12-0.9", "20-0.9", "23-0.9"]) psi4.wrapper_database.database('scf', 'O24by5', cp=0, subset=["4-0.9", "12-0.9", "20-0.9", "23-0.9"])
jturney/psi4
tests/python/databases/input.py
Python
lgpl-3.0
600
[ "Psi4" ]
6d5d8f76a444e0a05cd378849267a1a63e94c96036f75c2d1d217836671163a2
# nachans.py --- # # Filename: nachans.py # Description: # Author: subhasis ray # Maintainer: # Created: Fri Apr 17 23:58:13 2009 (+0530) # Version: # Last-Updated: Sat Dec 8 15:51:51 2012 (+0530) # By: subha # Update #: 402 # URL: # Keywords: # Compatibility: # # # Commentary: # # # # # Change log: # # # # # Code: from numpy import where, linspace, exp #import pylab import moose import config from channelbase import * class NaChannel(ChannelBase): """Dummy base class for all Na+ channels""" annotation = {'cno': 'cno:cno_0000105'} abstract = True Ek = 50e-3 def __init__(self, path): ChannelBase.__init__(self, path) class NaF(NaChannel): """Fast Na channel. """ abstract = False Xpower = 3 Ypower = 1 X = 0.0 # Y = 0.54876953 shift = -3.5e-3 tau_x = where((v_array + shift) < -30e-3, \ 1.0e-3 * (0.025 + 0.14 * exp((v_array + shift + 30.0e-3) / 10.0e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp(( - v_array - shift - 30.0e-3) / 10.0e-3))) inf_x = 1.0 / (1.0 + exp(( - v_array - shift - 38e-3) / 10e-3)) tau_y = 1.0e-3 * (0.15 + 1.15 / ( 1.0 + exp(( v_array + 37.0e-3) / 15.0e-3))) inf_y = 1.0 / (1.0 + exp((v_array + 62.9e-3) / 10.7e-3)) def __init__(self, path, shift=-3.5e-3, Ek=50e-3): NaChannel.__init__(self, path ) class NaF_TCR(NaF): """Fast Na+ channel for TCR cells. This is almost identical to NaF, but there is a nasty voltage shift in the tables.""" abstract = False shift_x = -5.5e-3 shift_y = -7e-3 tau_y = 1.0e-3 * (0.15 + 1.15 / ( 1.0 + exp(( v_array + 37.0e-3) / 15.0e-3))) inf_y = 1.0 / (1.0 + exp((v_array + shift_y + 62.9e-3) / 10.7e-3)) tau_x = where((v_array + shift_x) < -30e-3, \ 1.0e-3 * (0.025 + 0.14 * exp((v_array + shift_x + 30.0e-3) / 10.0e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp(( - v_array - shift_x - 30.0e-3) / 10.0e-3))) inf_x = 1.0 / (1.0 + exp(( - v_array - shift_x - 38e-3) / 10e-3)) def __init__(self, path): NaChannel.__init__(self, path) class NaF2(NaF): abstract = False # shift=-2.5 for all cortical interneurons including spiny stellates # In neuron cell templates fastNa_shift_naf2=-2.5 shift = -2.5e-3 tau_x = where((v_array + shift) < -30e-3, \ 1.0e-3 * (0.0125 + 0.1525 * exp ((v_array + shift + 30e-3) / 10e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((- v_array - shift - 30e-3) / 10e-3))) inf_x = 1.0 / (1.0 + exp(( - v_array - shift - 38e-3) / 10e-3)) tau_y = 1e-3 * (0.225 + 1.125 / ( 1 + exp( ( v_array + 37e-3 ) / 15e-3 ) )) inf_y = 1.0 / (1.0 + exp((v_array + 58.3e-3) / 6.7e-3)) def __init__(self, path): NaChannel.__init__(self, path) class NaF2_nRT(NaF2): """This is a version of NaF2 without the fastNa_shift - applicable to nRT cell.""" # for nRT cells, fastNa_shift_naf2 is not set in the cell # template. In naf2.mod it is set to 0 in PARAMETERS section. abstract = False tau_x = where(v_array < -30e-3, \ 1.0e-3 * (0.0125 + 0.1525 * exp ((v_array + 30e-3) / 10e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((-v_array - 30e-3) / 10e-3))) inf_x = 1.0 / (1.0 + exp(( - v_array - 38e-3) / 10e-3)) tau_y = 1e-3 * (0.225 + 1.125 / ( 1 + exp( ( v_array + 37e-3 ) / 15e-3 ) )) inf_y = 1.0 / (1.0 + exp((v_array + 58.3e-3) / 6.7e-3)) def __init__(self, path): NaF2.__init__(self, path) class NaP(NaChannel): abstract = False Xpower = 1.0 Ypower = 0.0 tau_x = where(v_array < -40e-3, \ 1.0e-3 * (0.025 + 0.14 * exp((v_array + 40e-3) / 10e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((-v_array - 40e-3) / 10e-3))) inf_x = 1.0 / (1.0 + exp((-v_array - 48e-3) / 10e-3)) def __init__(self, path, Ek=50e-3): NaChannel.__init__(self, path) class NaPF(NaChannel): """Persistent Na+ current, fast""" abstract = False Xpower = 3 tau_x = where(v_array < -30e-3, \ 1.0e-3 * (0.025 + 0.14 * exp((v_array + 30.0e-3) / 10.0e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((- v_array - 30.0e-3) / 10.0e-3))) inf_x = 1.0 / (1.0 + exp((-v_array - 38e-3) / 10e-3)) def __init__(self, path): NaChannel.__init__(self, path) class NaPF_SS(NaPF): abstract = False shift = -2.5e-3 v = v_array + shift tau_x = where((v_array + shift) < -30e-3, \ 1.0e-3 * (0.025 + 0.14 * exp(((v_array + shift) + 30.0e-3) / 10.0e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((- (v_array + shift) - 30.0e-3) / 10.0e-3))) inf_x = 1.0 / (1.0 + exp((- (v_array + shift) - 38e-3) / 10e-3)) def __init__(self, path): NaChannel.__init__(self, path) class NaPF_TCR(NaPF): """Persistent Na+ channel specific to TCR cells. Only difference with NaPF is power of m is 1 as opposed 3.""" abstract = False shift = 7e-3 Xpower = 1 tau_x = where((v_array + shift) < -30e-3, \ 1.0e-3 * (0.025 + 0.14 * exp(((v_array + shift) + 30.0e-3) / 10.0e-3)), \ 1.0e-3 * (0.02 + 0.145 * exp((- (v_array + shift) - 30.0e-3) / 10.0e-3))) inf_x = 1.0 / (1.0 + exp((-(v_array + shift) - 38e-3) / 10e-3)) def __init__(self, path): NaChannel.__init__(self, path) def initNaChannelPrototypes(): channel_names = [ 'NaF', 'NaF2', 'NaF2_nRT', 'NaP', 'NaPF', 'NaPF_SS', 'NaPF_TCR', 'NaF_TCR', ] _proto = {} for name in channel_names: chanclass = eval(name) _proto[name] = chanclass(prototypes[name]) return _proto # # nachans.py ends here
dilawar/moose-full
moose-examples/traub_2005/py/nachans.py
Python
gpl-2.0
5,936
[ "MOOSE", "NEURON" ]
ba3759ee6a0cac845e3d5bf929a646670a34f9ddb5141ce8db852dde49b8eb44
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ Provides an interface to manage URI scheme support in iris. """ import collections from collections import OrderedDict import glob import os.path import re import iris.exceptions # Saving routines, indexed by file extension. class _SaversDict(dict): """A dictionary that can only have string keys with no overlap.""" def __setitem__(self, key, value): if not isinstance(key, str): raise ValueError("key is not a string") if key in self: raise ValueError("A saver already exists for", key) for k in self.keys(): if k.endswith(key) or key.endswith(k): raise ValueError( "key %s conflicts with existing key %s" % (key, k) ) dict.__setitem__(self, key, value) _savers = _SaversDict() def run_callback(callback, cube, field, filename): """ Runs the callback mechanism given the appropriate arguments. Args: * callback: A function to add metadata from the originating field and/or URI which obeys the following rules: 1. Function signature must be: ``(cube, field, filename)``. 2. Modifies the given cube inplace, unless a new cube is returned by the function. 3. If the cube is to be rejected the callback must raise an :class:`iris.exceptions.IgnoreCubeException`. .. note:: It is possible that this function returns None for certain callbacks, the caller of this function should handle this case. """ from iris.cube import Cube if callback is None: return cube # Call the callback function on the cube, generally the function will # operate on the cube in place, but it is also possible that the function # will return a completely new cube instance. try: result = callback(cube, field, filename) except iris.exceptions.IgnoreCubeException: result = None else: if result is None: result = cube elif not isinstance(result, Cube): raise TypeError( "Callback function returned an " "unhandled data type." ) return result def decode_uri(uri, default="file"): r""" Decodes a single URI into scheme and scheme-specific parts. In addition to well-formed URIs, it also supports bare file paths. Both Windows and UNIX style paths are accepted. .. testsetup:: from iris.io import * Examples: >>> from iris.io import decode_uri >>> print(decode_uri('http://www.thing.com:8080/resource?id=a:b')) ('http', '//www.thing.com:8080/resource?id=a:b') >>> print(decode_uri('file:///data/local/dataZoo/...')) ('file', '///data/local/dataZoo/...') >>> print(decode_uri('/data/local/dataZoo/...')) ('file', '/data/local/dataZoo/...') >>> print(decode_uri('file:///C:\data\local\dataZoo\...')) ('file', '///C:\\data\\local\\dataZoo\\...') >>> print(decode_uri('C:\data\local\dataZoo\...')) ('file', 'C:\\data\\local\\dataZoo\\...') >>> print(decode_uri('dataZoo/...')) ('file', 'dataZoo/...') """ # make sure scheme has at least 2 letters to avoid windows drives # put - last in the brackets so it refers to the character, not a range # reference on valid schemes: http://tools.ietf.org/html/std66#section-3.1 match = re.match(r"^([a-zA-Z][a-zA-Z0-9+.-]+):(.+)", uri) if match: scheme = match.group(1) part = match.group(2) else: # Catch bare UNIX and Windows paths scheme = default part = uri return scheme, part def expand_filespecs(file_specs): """ Find all matching file paths from a list of file-specs. Args: * file_specs (iterable of string): File paths which may contain '~' elements or wildcards. Returns: A well-ordered list of matching absolute file paths. If any of the file-specs match no existing files, an exception is raised. """ # Remove any hostname component - currently unused filenames = [ os.path.abspath( os.path.expanduser(fn[2:] if fn.startswith("//") else fn) ) for fn in file_specs ] # Try to expand all filenames as globs glob_expanded = OrderedDict( [[fn, sorted(glob.glob(fn))] for fn in filenames] ) # If any of the specs expanded to an empty list then raise an error all_expanded = glob_expanded.values() if not all(all_expanded): msg = "One or more of the files specified did not exist:" for pattern, expanded in glob_expanded.items(): if expanded: msg += '\n - "{}" matched {} file(s)'.format( pattern, len(expanded) ) else: msg += '\n * "{}" didn\'t match any files'.format(pattern) raise IOError(msg) return [fname for fnames in all_expanded for fname in fnames] def load_files(filenames, callback, constraints=None): """ Takes a list of filenames which may also be globs, and optionally a constraint set and a callback function, and returns a generator of Cubes from the given files. .. note:: Typically, this function should not be called directly; instead, the intended interface for loading is :func:`iris.load`. """ from iris.fileformats import FORMAT_AGENT all_file_paths = expand_filespecs(filenames) # Create default dict mapping iris format handler to its associated filenames handler_map = collections.defaultdict(list) for fn in all_file_paths: with open(fn, "rb") as fh: handling_format_spec = FORMAT_AGENT.get_spec( os.path.basename(fn), fh ) handler_map[handling_format_spec].append(fn) # Call each iris format handler with the approriate filenames for handling_format_spec in sorted(handler_map): fnames = handler_map[handling_format_spec] if handling_format_spec.constraint_aware_handler: for cube in handling_format_spec.handler( fnames, callback, constraints ): yield cube else: for cube in handling_format_spec.handler(fnames, callback): yield cube def load_http(urls, callback): """ Takes a list of urls and a callback function, and returns a generator of Cubes from the given URLs. .. note:: Typically, this function should not be called directly; instead, the intended interface for loading is :func:`iris.load`. """ # Create default dict mapping iris format handler to its associated filenames handler_map = collections.defaultdict(list) for url in urls: handling_format_spec = iris.fileformats.FORMAT_AGENT.get_spec( url, None ) handler_map[handling_format_spec].append(url) # Call each iris format handler with the appropriate filenames for handling_format_spec in sorted(handler_map): fnames = handler_map[handling_format_spec] for cube in handling_format_spec.handler(fnames, callback): yield cube def _dot_save(cube, target): # A simple wrapper for `iris.fileformats.dot.save` which allows the # saver to be registered without triggering the import of # `iris.fileformats.dot`. from iris.fileformats.dot import save return save(cube, target) def _dot_save_png(cube, target, **kwargs): # A simple wrapper for `iris.fileformats.dot.save_png` which allows the # saver to be registered without triggering the import of # `iris.fileformats.dot`. from iris.fileformats.dot import save_png return save_png(cube, target, **kwargs) def _grib_save(cube, target, append=False, **kwargs): # A simple wrapper for the grib save routine, which allows the saver to be # registered without having the grib implementation installed. try: from iris_grib import save_grib2 except ImportError: raise RuntimeError( "Unable to save GRIB file - " '"iris_grib" package is not installed.' ) save_grib2(cube, target, append, **kwargs) def _check_init_savers(): from iris.fileformats import netcdf, pp if "pp" not in _savers: _savers.update( { "pp": pp.save, "nc": netcdf.save, "dot": _dot_save, "dotpng": _dot_save_png, "grib2": _grib_save, } ) def add_saver(file_extension, new_saver): """ Add a custom saver to the Iris session. Args: * file_extension: A string such as "pp" or "my_format". * new_saver: A function of the form ``my_saver(cube, target)``. See also :func:`iris.io.save` """ # Make sure it's a func with 2+ args if ( not hasattr(new_saver, "__call__") or new_saver.__code__.co_argcount < 2 ): raise ValueError("Saver routines must be callable with 2+ arguments.") # Try to add this saver. Invalid keys will be rejected. _savers[file_extension] = new_saver def find_saver(filespec): """ Find the saver function appropriate to the given filename or extension. Args: * filespec - A string such as "my_file.pp" or "PP". Returns: A save function or None. Save functions can be passed to :func:`iris.io.save`. """ _check_init_savers() matches = [ ext for ext in _savers if filespec.lower().endswith("." + ext) or filespec.lower() == ext ] # Multiple matches could occur if one of the savers included a '.': # e.g. _savers = {'.dot.png': dot_png_saver, '.png': png_saver} if len(matches) > 1: fmt = "Multiple savers found for %r: %s" matches = ", ".join(map(repr, matches)) raise ValueError(fmt % (filespec, matches)) return _savers[matches[0]] if matches else None def save(source, target, saver=None, **kwargs): """ Save one or more Cubes to file (or other writeable). Iris currently supports three file formats for saving, which it can recognise by filename extension: * netCDF - the Unidata network Common Data Format: * see :func:`iris.fileformats.netcdf.save` * GRIB2 - the WMO GRIdded Binary data format: * see :func:`iris_grib.save_grib2`. * PP - the Met Office UM Post Processing Format: * see :func:`iris.fileformats.pp.save` A custom saver can be provided to the function to write to a different file format. Args: * source: :class:`iris.cube.Cube`, :class:`iris.cube.CubeList` or sequence of cubes. * target: A filename (or writeable, depending on file format). When given a filename or file, Iris can determine the file format. Kwargs: * saver: Optional. Specifies the file format to save. If omitted, Iris will attempt to determine the format. If a string, this is the recognised filename extension (where the actual filename may not have it). Otherwise the value is a saver function, of the form: ``my_saver(cube, target)`` plus any custom keywords. It is assumed that a saver will accept an ``append`` keyword if it's file format can handle multiple cubes. See also :func:`iris.io.add_saver`. All other keywords are passed through to the saver function; see the relevant saver documentation for more information on keyword arguments. Examples:: # Save a cube to PP iris.save(my_cube, "myfile.pp") # Save a cube list to a PP file, appending to the contents of the file # if it already exists iris.save(my_cube_list, "myfile.pp", append=True) # Save a cube to netCDF, defaults to NETCDF4 file format iris.save(my_cube, "myfile.nc") # Save a cube list to netCDF, using the NETCDF3_CLASSIC storage option iris.save(my_cube_list, "myfile.nc", netcdf_format="NETCDF3_CLASSIC") .. warning:: Saving a cube whose data has been loaded lazily (if `cube.has_lazy_data()` returns `True`) to the same file it expects to load data from will cause both the data in-memory and the data on disk to be lost. .. code-block:: python cube = iris.load_cube("somefile.nc") # The next line causes data loss in 'somefile.nc' and the cube. iris.save(cube, "somefile.nc") In general, overwriting a file which is the source for any lazily loaded data can result in corruption. Users should proceed with caution when attempting to overwrite an existing file. """ from iris.cube import Cube, CubeList # Determine format from filename if isinstance(target, str) and saver is None: saver = find_saver(target) elif hasattr(target, "name") and saver is None: saver = find_saver(target.name) elif isinstance(saver, str): saver = find_saver(saver) if saver is None: raise ValueError("Cannot save; no saver") # Single cube? if isinstance(source, Cube): saver(source, target, **kwargs) # CubeList or sequence of cubes? elif isinstance(source, CubeList) or ( isinstance(source, (list, tuple)) and all([isinstance(i, Cube) for i in source]) ): # Only allow cubelist saving for those fileformats that are capable. if "iris.fileformats.netcdf" not in saver.__module__: # Make sure the saver accepts an append keyword if "append" not in saver.__code__.co_varnames: raise ValueError( "Cannot append cubes using saver function " "'%s' in '%s'" % (saver.__code__.co_name, saver.__code__.co_filename) ) # Force append=True for the tail cubes. Don't modify the incoming # kwargs. kwargs = kwargs.copy() for i, cube in enumerate(source): if i != 0: kwargs["append"] = True saver(cube, target, **kwargs) # Netcdf saver. else: saver(source, target, **kwargs) else: raise ValueError("Cannot save; non Cube found in source")
rcomer/iris
lib/iris/io/__init__.py
Python
lgpl-3.0
14,713
[ "NetCDF" ]
7b30d9efbea76183556f97a9076d32b0431f99bf30b1ef91f76818ae0d4fda0b
#!/usr/bin/env python """ Determine number of processors and memory for the worker node """ __RCSID__ = "$Id$" from DIRAC.Core.Base import Script from DIRAC import gLogger from DIRAC.WorkloadManagementSystem.Utilities import JobParameters Script.setUsageMessage('\n'.join(['Get the parameters (Memory and Number of processors) of a worker node', 'Usage:', ' %s [option]... [cfgfile]' % Script.scriptName, 'Arguments:', ' cfgfile: DIRAC Cfg with description of the configuration (optional)'])) ceName = '' ceType = '' def setCEName(args): global ceName ceName = args def setSite(args): global Site Site = args def setQueue(args): global Queue Queue = args Script.registerSwitch("N:", "Name=", "Computing Element Name (Mandatory)", setCEName) Script.registerSwitch("S:", "Site=", "Site Name (Mandatory)", setSite) Script.registerSwitch("Q:", "Queue=", "Queue Name (Mandatory)", setQueue) Script.parseCommandLine(ignoreErrors=True) gLogger.info("Getting number of processors") numberOfProcessor = JobParameters.getNumberOfProcessors(Site, ceName, Queue) gLogger.info("Getting memory (RAM) from MJF") maxRAM = JobParameters.getMemoryFromMJF() if not maxRAM: gLogger.info("maxRAM could not be found in MJF, using JobParameters.getMemoryFromProc()") maxRAM = JobParameters.getMemoryFromProc() # just communicating it back gLogger.notice(numberOfProcessor, maxRAM)
andresailer/DIRAC
WorkloadManagementSystem/scripts/dirac-wms-get-wn-parameters.py
Python
gpl-3.0
1,529
[ "DIRAC" ]
732bfd113269317415aeeb687a50ec4c731ad78a959140f067cbc07a5aee7b45
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. import pytest from shuup import configuration from shuup.admin.views.dashboard import DashboardView from shuup.admin.views.wizard import WizardView from shuup.core.models import AnonymousContact, Category, Product, Shop from shuup.front.apps.carousel.models import Carousel, Slide from shuup.front.apps.carousel.plugins import CarouselPlugin from shuup.testing.factories import ( CategoryFactory, ProductFactory, get_default_shop, get_default_supplier, get_default_tax_class, ) from shuup.testing.modules.sample_data import manager from shuup.testing.modules.sample_data.data import BUSINESS_SEGMENTS from shuup.testing.modules.sample_data.forms import ConsolidateObjectsForm from shuup.testing.modules.sample_data.views import ConsolidateSampleObjectsView from shuup.testing.utils import apply_request_middleware from shuup.utils.django_compat import reverse from shuup.xtheme.models import SavedViewConfig @pytest.mark.django_db def test_sample_data_manager(): shop = get_default_shop() assert manager.get_installed_business_segment(shop) is None assert manager.get_installed_products(shop) == [] assert manager.get_installed_categories(shop) == [] assert manager.get_installed_carousel(shop) is None assert manager.has_installed_samples(shop) is False BUSINESS_SEG = "default" PRODUCTS = [1, 2, 3] CATEGORIES = [4, 5, 6] CAROUSEL = 1 manager.save_categories(shop, CATEGORIES) manager.save_products(shop, PRODUCTS) manager.save_carousel(shop, CAROUSEL) manager.save_business_segment(shop, BUSINESS_SEG) assert manager.get_installed_business_segment(shop) == BUSINESS_SEG assert manager.get_installed_products(shop) == PRODUCTS assert manager.get_installed_categories(shop) == CATEGORIES assert manager.get_installed_carousel(shop) == CAROUSEL assert manager.has_installed_samples(shop) is True new_shop = Shop.objects.create() assert manager.get_installed_business_segment(new_shop) is None assert manager.get_installed_products(new_shop) == [] assert manager.get_installed_categories(new_shop) == [] assert manager.get_installed_carousel(new_shop) is None assert manager.has_installed_samples(new_shop) is False manager.clear_installed_samples(shop) assert manager.get_installed_business_segment(shop) is None assert manager.get_installed_products(shop) == [] assert manager.get_installed_categories(shop) == [] assert manager.get_installed_carousel(shop) is None assert manager.has_installed_samples(shop) is False @pytest.mark.django_db def test_sample_data_wizard_pane(rf, admin_user, settings): settings.SHUUP_SETUP_WIZARD_PANE_SPEC = ["shuup.testing.modules.sample_data.views.SampleObjectsWizardPane"] shop = get_default_shop() get_default_tax_class() data = { "pane_id": "sample", "sample-business_segment": "default", "sample-categories": True, "sample-products": True, "sample-carousel": True, } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = WizardView.as_view()(request) assert response.status_code == 200 assert Product.objects.count() == len(BUSINESS_SEGMENTS["default"]["products"]) anon_contact = AnonymousContact() supplier = get_default_supplier() # check for the injected plugin using the carousel assert Carousel.objects.count() == 1 carousel = Carousel.objects.first() assert Slide.objects.count() == len(BUSINESS_SEGMENTS["default"]["carousel"]["slides"]) svc = SavedViewConfig.objects.first() assert svc.view_name == "IndexView" layout = svc.get_layout_data("front_content") assert layout["rows"][0]["cells"][0]["config"]["carousel"] == carousel.pk assert layout["rows"][0]["cells"][0]["plugin"] == CarouselPlugin.identifier for product in Product.objects.all(): # all products must be orderable and have images assert product.get_shop_instance(shop).is_orderable(supplier=supplier, customer=anon_contact, quantity=1) assert product.primary_image is not None assert Category.objects.count() == len(BUSINESS_SEGMENTS["default"]["categories"]) request = apply_request_middleware(rf.get("/"), user=admin_user) response = WizardView.as_view()(request) assert response.status_code == 302 assert response["Location"] == reverse("shuup_admin:dashboard") @pytest.mark.django_db def test_forms(settings): shop = get_default_shop() # check whether the fields are dynamically added manager.clear_installed_samples(shop) consolidate_form = ConsolidateObjectsForm(**{"shop": shop}) assert len(consolidate_form.fields) == 0 # field categories appears categories = [CategoryFactory().pk, CategoryFactory().pk, CategoryFactory().pk] manager.save_categories(shop, categories) consolidate_form = ConsolidateObjectsForm(**{"shop": shop}) assert "categories" in consolidate_form.fields # field products appears products = [ProductFactory().pk, ProductFactory().pk, ProductFactory().pk] manager.save_products(shop, products) consolidate_form = ConsolidateObjectsForm(**{"shop": shop}) assert "products" in consolidate_form.fields # field carousel appears carousel = Carousel.objects.create(name="stuff") manager.save_carousel(shop, carousel.pk) consolidate_form = ConsolidateObjectsForm(**{"shop": shop}) assert "carousel" in consolidate_form.fields @pytest.mark.django_db def test_admin(rf, admin_user): shop = get_default_shop() configuration.set(shop, "setup_wizard_complete", True) # just visit to make sure everything is ok request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200 categories = [CategoryFactory().pk, CategoryFactory().pk, CategoryFactory().pk] manager.save_categories(shop, categories) request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200 @pytest.mark.django_db def test_consolidate_objects(rf, admin_user): shop = get_default_shop() # just visit to make sure GET is ok request = apply_request_middleware(rf.get("/"), user=admin_user) response = ConsolidateSampleObjectsView.as_view()(request) assert response.status_code == 200 def populate_samples(): manager.clear_installed_samples(shop) categories = [CategoryFactory().pk, CategoryFactory().pk, CategoryFactory().pk] products = [ProductFactory().pk, ProductFactory().pk, ProductFactory().pk, ProductFactory().pk] carousel = Carousel.objects.create(name="crazy stuff").pk manager.save_categories(shop, categories) manager.save_products(shop, products) manager.save_carousel(shop, carousel) def clear_objs(): Product.objects.all().delete() Category.objects.all().delete() Carousel.objects.all().delete() # consolidate everything populate_samples() data = {"categories": False, "products": False, "carousel": False} request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = ConsolidateSampleObjectsView.as_view()(request) assert response.status_code == 302 assert response["Location"] == reverse("shuup_admin:dashboard") assert Category.objects.count() == 3 assert Product.objects.count() == 4 assert Carousel.objects.count() == 1 assert manager.get_installed_business_segment(shop) is None assert manager.get_installed_products(shop) == [] assert manager.get_installed_categories(shop) == [] assert manager.get_installed_carousel(shop) is None # consolidate nothing clear_objs() populate_samples() data = {"products": True, "categories": True, "carousel": True} request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = ConsolidateSampleObjectsView.as_view()(request) assert response.status_code == 302 assert response["Location"] == reverse("shuup_admin:dashboard") assert Category.objects.all_except_deleted().count() == 0 assert Product.objects.all_except_deleted().count() == 0 assert Carousel.objects.count() == 0 assert manager.get_installed_business_segment(shop) is None assert manager.get_installed_products(shop) == [] assert manager.get_installed_categories(shop) == [] assert manager.get_installed_carousel(shop) is None # consolidate some clear_objs() populate_samples() data = {"products": False, "categories": False, "carousel": True} request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = ConsolidateSampleObjectsView.as_view()(request) assert response.status_code == 302 assert response["Location"] == reverse("shuup_admin:dashboard") assert Category.objects.all_except_deleted().count() == 3 assert Product.objects.all_except_deleted().count() == 4 assert Carousel.objects.count() == 0 assert manager.get_installed_business_segment(shop) is None assert manager.get_installed_products(shop) == [] assert manager.get_installed_categories(shop) == [] assert manager.get_installed_carousel(shop) is None
shoopio/shoop
shuup_tests/admin/test_sample_data.py
Python
agpl-3.0
9,616
[ "VisIt" ]
4d72746c50f07bb8c494f6a5457b23fefd12a86157e2e3821262f292d3166a23
import numpy as np from neuroanalysis.fitting import Gaussian, SearchFit import pyqtgraph as pg pg.dbg() # make some noise with a gaussian bump model = Gaussian() x = np.linspace(0, 100, 1000) y = np.random.normal(size=len(x)) + model.eval(x=x, xoffset=71, yoffset=0, sigma=5, amp=10) plt = pg.plot() plt.plot(x, y, pen=0.5) # If we attempt to fit with xoffset bounded between 0 and 100, it is likely # the fit will fail: fit = model.fit(data=y, x=x, params={'xoffset': (50, 0, 100), 'yoffset': 0, 'amp': (0, -50, 50), 'sigma': (5, 1, 20)}) plt.plot(x, fit.best_fit, pen='r') # Instead, brute-force search for the best fit over multiple ranges for xoffset and amp: amp = [{'amp': (-10, -50, 0)}, {'amp': (10, 0, 50)}] xoffset = [{'xoffset':(x+5, x, x+10)} for x in range(0, 100, 10)] # Total number of fit attempts is len(amp) * len(xoffset) = 20 search = SearchFit(model, [amp, xoffset], params={'sigma': (5, 1, 20), 'yoffset': 0}, x=x, data=y) # Optionally, let the user know how the fit is progressing: with pg.ProgressDialog("Fitting...", maximum=len(search)) as dlg: for result in search.iter_fit(): print("Init params this iteration:", result['params']) dlg += 1 if dlg.wasCanceled(): raise Exception("User canceled fit") plt.plot(x, search.best_result.best_fit, pen='g') print("Best fit parameters:", search.best_result.best_values)
campagnola/neuroanalysis
examples/search_fit.py
Python
mit
1,395
[ "Gaussian" ]
1ece1cf7faf366d2dd44764fec1e8da63ff5c1a3c842b8447423a0acf1d5f163
# Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2021, 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 htt"://www.gnu.org/licenses. # # http://numenta.org/licenses/ # import string import numpy as np import torch __all__ = [ "PrototypeFigure1B", ] class PrototypeFigure1B: """ Mixin for generating data used to plot Figure 1B in the following CNS submission: "Going Beyond the Point Neuron: Active Dendrites and Sparse Representations for Continual Learning"; Karan Grewal, Jeremy Forest, Subutai Ahmad. """ def setup_experiment(self, config): super().setup_experiment(config) if not hasattr(self, "ha_hook"): raise Exception("This experiment must use a Hidden Activations hook.") def validate(self, **kwargs): ret = super().validate(**kwargs) if 1 + self.current_task == self.num_tasks: # Validation loop for plotting purposes, where labels are unshared self.ha_hook.start_tracking() self.task_as_targets_eval() self.ha_hook.stop_tracking() # Save values for plotting # A key is just a unique identifier for this run, so that previously-saved # files aren't overwritten key = "".join(np.random.choice([s for s in string.ascii_lowercase], 4)) for name, _, hidden_activations in self.ha_hook.get_statistics(): targets = self.ha_targets[:self.ha_max_samples] filename = f"{self.num_tasks}_{name}_{key}.pt" torch.save(hidden_activations, f"x_{filename}") torch.save(targets, f"y_{filename}") return ret def task_as_targets_eval(self): """ This method runs the evaluation loop similar to `self.evaluate_model`, but modified so that (1) target labels are converted to task labels, and (2) nothing is returned. """ self.model.eval() with torch.no_grad(): for data, target in self.val_loader: if isinstance(data, list): data, _ = data data = data.flatten(start_dim=1) # This next line converts target labels to task labels, so test # examples can be grouped as desired target = target // self.num_classes_per_task data, target = data.to(self.device), target.to(self.device) # Select the context by comparing distances to all context prototypes context = torch.cdist(self.contexts, data) context = context.argmin(dim=0) context = self.contexts[context] # Perform forward pass to register hidden activations via hooks _ = self.model(data, context) if self.ha_hook.tracking: # Targets were initialized on the cpu which could differ from the # targets collected during the forward pass. self.ha_targets = self.ha_targets.to(target.device) # Concatenate and discard the older targets. self.ha_targets = torch.cat([target, self.ha_targets], dim=0) self.ha_targets = self.ha_targets[:self.ha_max_samples] else: print("Warning: Hook tracking is off.")
mrcslws/nupic.research
packages/dendrites/src/nupic/research/frameworks/dendrites/mixins/prototype_figure_1b.py
Python
agpl-3.0
4,062
[ "NEURON" ]
3f02dc9be23d366d621e637212690c62b77313c880740d962199ac74a13cf22c
"""Rewrite assertion AST to produce nice error messages""" import ast import errno import functools import importlib.machinery import importlib.util import io import itertools import marshal import os import struct import sys import tokenize import types import atomicwrites from _pytest._io.saferepr import saferepr from _pytest._version import version from _pytest.assertion import util from _pytest.assertion.util import ( # noqa: F401 format_explanation as _format_explanation, ) from _pytest.pathlib import fnmatch_ex from _pytest.pathlib import PurePath # pytest caches rewritten pycs in __pycache__. PYTEST_TAG = "{}-pytest-{}".format(sys.implementation.cache_tag, version) PYC_EXT = ".py" + (__debug__ and "c" or "o") PYC_TAIL = "." + PYTEST_TAG + PYC_EXT class AssertionRewritingHook: """PEP302/PEP451 import hook which rewrites asserts.""" def __init__(self, config): self.config = config try: self.fnpats = config.getini("python_files") except ValueError: self.fnpats = ["test_*.py", "*_test.py"] self.session = None self._rewritten_names = set() self._must_rewrite = set() # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file, # which might result in infinite recursion (#3506) self._writing_pyc = False self._basenames_to_check_rewrite = {"conftest"} self._marked_for_rewrite_cache = {} self._session_paths_checked = False def set_session(self, session): self.session = session self._session_paths_checked = False # Indirection so we can mock calls to find_spec originated from the hook during testing _find_spec = importlib.machinery.PathFinder.find_spec def find_spec(self, name, path=None, target=None): if self._writing_pyc: return None state = self.config._assertstate if self._early_rewrite_bailout(name, state): return None state.trace("find_module called for: %s" % name) spec = self._find_spec(name, path) if ( # the import machinery could not find a file to import spec is None # this is a namespace package (without `__init__.py`) # there's nothing to rewrite there # python3.5 - python3.6: `namespace` # python3.7+: `None` or spec.origin in {None, "namespace"} # we can only rewrite source files or not isinstance(spec.loader, importlib.machinery.SourceFileLoader) # if the file doesn't exist, we can't rewrite it or not os.path.exists(spec.origin) ): return None else: fn = spec.origin if not self._should_rewrite(name, fn, state): return None return importlib.util.spec_from_file_location( name, fn, loader=self, submodule_search_locations=spec.submodule_search_locations, ) def create_module(self, spec): return None # default behaviour is fine def exec_module(self, module): fn = module.__spec__.origin state = self.config._assertstate self._rewritten_names.add(module.__name__) # The requested module looks like a test file, so rewrite it. This is # the most magical part of the process: load the source, rewrite the # asserts, and load the rewritten source. We also cache the rewritten # module code in a special pyc. We must be aware of the possibility of # concurrent pytest processes rewriting and loading pycs. To avoid # tricky race conditions, we maintain the following invariant: The # cached pyc is always a complete, valid pyc. Operations on it must be # atomic. POSIX's atomic rename comes in handy. write = not sys.dont_write_bytecode cache_dir = os.path.join(os.path.dirname(fn), "__pycache__") if write: try: os.mkdir(cache_dir) except OSError: e = sys.exc_info()[1].errno if e == errno.EEXIST: # Either the __pycache__ directory already exists (the # common case) or it's blocked by a non-dir node. In the # latter case, we'll ignore it in _write_pyc. pass elif e in {errno.ENOENT, errno.ENOTDIR}: # One of the path components was not a directory, likely # because we're in a zip file. write = False elif e in {errno.EACCES, errno.EROFS, errno.EPERM}: state.trace("read only directory: %r" % os.path.dirname(fn)) write = False else: raise cache_name = os.path.basename(fn)[:-3] + PYC_TAIL pyc = os.path.join(cache_dir, cache_name) # Notice that even if we're in a read-only directory, I'm going # to check for a cached pyc. This may not be optimal... co = _read_pyc(fn, pyc, state.trace) if co is None: state.trace("rewriting {!r}".format(fn)) source_stat, co = _rewrite_test(fn, self.config) if write: self._writing_pyc = True try: _write_pyc(state, co, source_stat, pyc) finally: self._writing_pyc = False else: state.trace("found cached rewritten pyc for {!r}".format(fn)) exec(co, module.__dict__) def _early_rewrite_bailout(self, name, state): """This is a fast way to get out of rewriting modules. Profiling has shown that the call to PathFinder.find_spec (inside of the find_spec from this class) is a major slowdown, so, this method tries to filter what we're sure won't be rewritten before getting to it. """ if self.session is not None and not self._session_paths_checked: self._session_paths_checked = True for path in self.session._initialpaths: # Make something as c:/projects/my_project/path.py -> # ['c:', 'projects', 'my_project', 'path.py'] parts = str(path).split(os.path.sep) # add 'path' to basenames to be checked. self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0]) # Note: conftest already by default in _basenames_to_check_rewrite. parts = name.split(".") if parts[-1] in self._basenames_to_check_rewrite: return False # For matching the name it must be as if it was a filename. path = PurePath(os.path.sep.join(parts) + ".py") for pat in self.fnpats: # if the pattern contains subdirectories ("tests/**.py" for example) we can't bail out based # on the name alone because we need to match against the full path if os.path.dirname(pat): return False if fnmatch_ex(pat, path): return False if self._is_marked_for_rewrite(name, state): return False state.trace("early skip of rewriting module: {}".format(name)) return True def _should_rewrite(self, name, fn, state): # always rewrite conftest files if os.path.basename(fn) == "conftest.py": state.trace("rewriting conftest file: {!r}".format(fn)) return True if self.session is not None: if self.session.isinitpath(fn): state.trace( "matched test file (was specified on cmdline): {!r}".format(fn) ) return True # modules not passed explicitly on the command line are only # rewritten if they match the naming convention for test files fn_path = PurePath(fn) for pat in self.fnpats: if fnmatch_ex(pat, fn_path): state.trace("matched test file {!r}".format(fn)) return True return self._is_marked_for_rewrite(name, state) def _is_marked_for_rewrite(self, name, state): try: return self._marked_for_rewrite_cache[name] except KeyError: for marked in self._must_rewrite: if name == marked or name.startswith(marked + "."): state.trace( "matched marked file {!r} (from {!r})".format(name, marked) ) self._marked_for_rewrite_cache[name] = True return True self._marked_for_rewrite_cache[name] = False return False def mark_rewrite(self, *names): """Mark import names as needing to be rewritten. The named module or package as well as any nested modules will be rewritten on import. """ already_imported = ( set(names).intersection(sys.modules).difference(self._rewritten_names) ) for name in already_imported: mod = sys.modules[name] if not AssertionRewriter.is_rewrite_disabled( mod.__doc__ or "" ) and not isinstance(mod.__loader__, type(self)): self._warn_already_imported(name) self._must_rewrite.update(names) self._marked_for_rewrite_cache.clear() def _warn_already_imported(self, name): from _pytest.warning_types import PytestAssertRewriteWarning from _pytest.warnings import _issue_warning_captured _issue_warning_captured( PytestAssertRewriteWarning( "Module already imported so cannot be rewritten: %s" % name ), self.config.hook, stacklevel=5, ) def get_data(self, pathname): """Optional PEP302 get_data API.""" with open(pathname, "rb") as f: return f.read() def _write_pyc(state, co, source_stat, pyc): # Technically, we don't have to have the same pyc format as # (C)Python, since these "pycs" should never be seen by builtin # import. However, there's little reason deviate. try: with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp: fp.write(importlib.util.MAGIC_NUMBER) # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903) mtime = int(source_stat.st_mtime) & 0xFFFFFFFF size = source_stat.st_size & 0xFFFFFFFF # "<LL" stands for 2 unsigned longs, little-ending fp.write(struct.pack("<LL", mtime, size)) fp.write(marshal.dumps(co)) except EnvironmentError as e: state.trace("error writing pyc file at {}: errno={}".format(pyc, e.errno)) # we ignore any failure to write the cache file # there are many reasons, permission-denied, __pycache__ being a # file etc. return False return True def _rewrite_test(fn, config): """read and rewrite *fn* and return the code object.""" stat = os.stat(fn) with open(fn, "rb") as f: source = f.read() tree = ast.parse(source, filename=fn) rewrite_asserts(tree, source, fn, config) co = compile(tree, fn, "exec", dont_inherit=True) return stat, co def _read_pyc(source, pyc, trace=lambda x: None): """Possibly read a pytest pyc containing rewritten code. Return rewritten code if successful or None if not. """ try: fp = open(pyc, "rb") except IOError: return None with fp: try: stat_result = os.stat(source) mtime = int(stat_result.st_mtime) size = stat_result.st_size data = fp.read(12) except EnvironmentError as e: trace("_read_pyc({}): EnvironmentError {}".format(source, e)) return None # Check for invalid or out of date pyc file. if ( len(data) != 12 or data[:4] != importlib.util.MAGIC_NUMBER or struct.unpack("<LL", data[4:]) != (mtime & 0xFFFFFFFF, size & 0xFFFFFFFF) ): trace("_read_pyc(%s): invalid or out of date pyc" % source) return None try: co = marshal.load(fp) except Exception as e: trace("_read_pyc({}): marshal.load error {}".format(source, e)) return None if not isinstance(co, types.CodeType): trace("_read_pyc(%s): not a code object" % source) return None return co def rewrite_asserts(mod, source, module_path=None, config=None): """Rewrite the assert statements in mod.""" AssertionRewriter(module_path, config, source).run(mod) def _saferepr(obj): """Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the special escape sequences, especially '\n{' and '\n}' are likely to be present in JSON reprs. """ return saferepr(obj).replace("\n", "\\n") def _format_assertmsg(obj): """Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects saferepr() is used first. """ # reprlib appears to have a bug which means that if a string # contains a newline it gets escaped, however if an object has a # .__repr__() which contains newlines it does not get escaped. # However in either case we want to preserve the newline. replaces = [("\n", "\n~"), ("%", "%%")] if not isinstance(obj, str): obj = saferepr(obj) replaces.append(("\\n", "\n~")) for r1, r2 in replaces: obj = obj.replace(r1, r2) return obj def _should_repr_global_name(obj): if callable(obj): return False try: return not hasattr(obj, "__name__") except Exception: return True def _format_boolop(explanations, is_or): explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")" if isinstance(explanation, str): return explanation.replace("%", "%%") else: return explanation.replace(b"%", b"%%") def _call_reprcompare(ops, results, expls, each_obj): for i, res, expl in zip(range(len(ops)), results, expls): try: done = not res except Exception: done = True if done: break if util._reprcompare is not None: custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1]) if custom is not None: return custom return expl def _call_assertion_pass(lineno, orig, expl): if util._assertion_pass is not None: util._assertion_pass(lineno=lineno, orig=orig, expl=expl) def _check_if_assertion_pass_impl(): """Checks if any plugins implement the pytest_assertion_pass hook in order not to generate explanation unecessarily (might be expensive)""" return True if util._assertion_pass else False UNARY_MAP = {ast.Not: "not %s", ast.Invert: "~%s", ast.USub: "-%s", ast.UAdd: "+%s"} BINOP_MAP = { ast.BitOr: "|", ast.BitXor: "^", ast.BitAnd: "&", ast.LShift: "<<", ast.RShift: ">>", ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", ast.Mod: "%%", # escaped for string formatting ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Pow: "**", ast.Is: "is", ast.IsNot: "is not", ast.In: "in", ast.NotIn: "not in", ast.MatMult: "@", } def set_location(node, lineno, col_offset): """Set node location information recursively.""" def _fix(node, lineno, col_offset): if "lineno" in node._attributes: node.lineno = lineno if "col_offset" in node._attributes: node.col_offset = col_offset for child in ast.iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, lineno, col_offset) return node def _get_assertion_exprs(src: bytes): # -> Dict[int, str] """Returns a mapping from {lineno: "assertion test expression"}""" ret = {} depth = 0 lines = [] assert_lineno = None seen_lines = set() def _write_and_reset() -> None: nonlocal depth, lines, assert_lineno, seen_lines ret[assert_lineno] = "".join(lines).rstrip().rstrip("\\") depth = 0 lines = [] assert_lineno = None seen_lines = set() tokens = tokenize.tokenize(io.BytesIO(src).readline) for tp, src, (lineno, offset), _, line in tokens: if tp == tokenize.NAME and src == "assert": assert_lineno = lineno elif assert_lineno is not None: # keep track of depth for the assert-message `,` lookup if tp == tokenize.OP and src in "([{": depth += 1 elif tp == tokenize.OP and src in ")]}": depth -= 1 if not lines: lines.append(line[offset:]) seen_lines.add(lineno) # a non-nested comma separates the expression from the message elif depth == 0 and tp == tokenize.OP and src == ",": # one line assert with message if lineno in seen_lines and len(lines) == 1: offset_in_trimmed = offset + len(lines[-1]) - len(line) lines[-1] = lines[-1][:offset_in_trimmed] # multi-line assert with message elif lineno in seen_lines: lines[-1] = lines[-1][:offset] # multi line assert with escapd newline before message else: lines.append(line[:offset]) _write_and_reset() elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}: _write_and_reset() elif lines and lineno not in seen_lines: lines.append(line) seen_lines.add(lineno) return ret class AssertionRewriter(ast.NodeVisitor): """Assertion rewriting implementation. The main entrypoint is to call .run() with an ast.Module instance, this will then find all the assert statements and rewrite them to provide intermediate values and a detailed assertion error. See http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html for an overview of how this works. The entry point here is .run() which will iterate over all the statements in an ast.Module and for each ast.Assert statement it finds call .visit() with it. Then .visit_Assert() takes over and is responsible for creating new ast statements to replace the original assert statement: it rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false and calls pytest_assertion_pass hook if expression is true. For this .visit_Assert() uses the visitor pattern to visit all the AST nodes of the ast.Assert.test field, each visit call returning an AST node and the corresponding explanation string. During this state is kept in several instance attributes: :statements: All the AST statements which will replace the assert statement. :variables: This is populated by .variable() with each variable used by the statements so that they can all be set to None at the end of the statements. :variable_counter: Counter to create new unique variables needed by statements. Variables are created using .variable() and have the form of "@py_assert0". :expl_stmts: The AST statements which will be executed to get data from the assertion. This is the code which will construct the detailed assertion message that is used in the AssertionError or for the pytest_assertion_pass hook. :explanation_specifiers: A dict filled by .explanation_param() with %-formatting placeholders and their corresponding expressions to use in the building of an assertion message. This is used by .pop_format_context() to build a message. :stack: A stack of the explanation_specifiers dicts maintained by .push_format_context() and .pop_format_context() which allows to build another %-formatted string while already building one. This state is reset on every new assert statement visited and used by the other visitors. """ def __init__(self, module_path, config, source): super().__init__() self.module_path = module_path self.config = config if config is not None: self.enable_assertion_pass_hook = config.getini( "enable_assertion_pass_hook" ) else: self.enable_assertion_pass_hook = False self.source = source @functools.lru_cache(maxsize=1) def _assert_expr_to_lineno(self): return _get_assertion_exprs(self.source) def run(self, mod): """Find all assert statements in *mod* and rewrite them.""" if not mod.body: # Nothing to do. return # Insert some special imports at the top of the module but after any # docstrings and __future__ imports. aliases = [ ast.alias("builtins", "@py_builtins"), ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), ] doc = getattr(mod, "docstring", None) expect_docstring = doc is None if doc is not None and self.is_rewrite_disabled(doc): return pos = 0 lineno = 1 for item in mod.body: if ( expect_docstring and isinstance(item, ast.Expr) and isinstance(item.value, ast.Str) ): doc = item.value.s if self.is_rewrite_disabled(doc): return expect_docstring = False elif ( not isinstance(item, ast.ImportFrom) or item.level > 0 or item.module != "__future__" ): lineno = item.lineno break pos += 1 else: lineno = item.lineno imports = [ ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases ] mod.body[pos:pos] = imports # Collect asserts. nodes = [mod] while nodes: node = nodes.pop() for name, field in ast.iter_fields(node): if isinstance(field, list): new = [] for i, child in enumerate(field): if isinstance(child, ast.Assert): # Transform assert. new.extend(self.visit(child)) else: new.append(child) if isinstance(child, ast.AST): nodes.append(child) setattr(node, name, new) elif ( isinstance(field, ast.AST) # Don't recurse into expressions as they can't contain # asserts. and not isinstance(field, ast.expr) ): nodes.append(field) @staticmethod def is_rewrite_disabled(docstring): return "PYTEST_DONT_REWRITE" in docstring def variable(self): """Get a new variable.""" # Use a character invalid in python identifiers to avoid clashing. name = "@py_assert" + str(next(self.variable_counter)) self.variables.append(name) return name def assign(self, expr): """Give *expr* a name.""" name = self.variable() self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) return ast.Name(name, ast.Load()) def display(self, expr): """Call saferepr on the expression.""" return self.helper("_saferepr", expr) def helper(self, name, *args): """Call a helper in this module.""" py_name = ast.Name("@pytest_ar", ast.Load()) attr = ast.Attribute(py_name, name, ast.Load()) return ast.Call(attr, list(args), []) def builtin(self, name): """Return the builtin called *name*.""" builtin_name = ast.Name("@py_builtins", ast.Load()) return ast.Attribute(builtin_name, name, ast.Load()) def explanation_param(self, expr): """Return a new named %-formatting placeholder for expr. This creates a %-formatting placeholder for expr in the current formatting context, e.g. ``%(py0)s``. The placeholder and expr are placed in the current format context so that it can be used on the next call to .pop_format_context(). """ specifier = "py" + str(next(self.variable_counter)) self.explanation_specifiers[specifier] = expr return "%(" + specifier + ")s" def push_format_context(self): """Create a new formatting context. The format context is used for when an explanation wants to have a variable value formatted in the assertion message. In this case the value required can be added using .explanation_param(). Finally .pop_format_context() is used to format a string of %-formatted values as added by .explanation_param(). """ self.explanation_specifiers = {} self.stack.append(self.explanation_specifiers) def pop_format_context(self, expl_expr): """Format the %-formatted string with current format context. The expl_expr should be an ast.Str instance constructed from the %-placeholders created by .explanation_param(). This will add the required code to format said string to .expl_stmts and return the ast.Name instance of the formatted string. """ current = self.stack.pop() if self.stack: self.explanation_specifiers = self.stack[-1] keys = [ast.Str(key) for key in current.keys()] format_dict = ast.Dict(keys, list(current.values())) form = ast.BinOp(expl_expr, ast.Mod(), format_dict) name = "@py_format" + str(next(self.variable_counter)) if self.enable_assertion_pass_hook: self.format_variables.append(name) self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form)) return ast.Name(name, ast.Load()) def generic_visit(self, node): """Handle expressions we don't have custom code for.""" assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res)) def visit_Assert(self, assert_): """Return the AST statements to replace the ast.Assert instance. This rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false. """ if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1: from _pytest.warning_types import PytestAssertRewriteWarning import warnings warnings.warn_explicit( PytestAssertRewriteWarning( "assertion is always true, perhaps remove parentheses?" ), category=None, filename=self.module_path, lineno=assert_.lineno, ) self.statements = [] self.variables = [] self.variable_counter = itertools.count() if self.enable_assertion_pass_hook: self.format_variables = [] self.stack = [] self.expl_stmts = [] self.push_format_context() # Rewrite assert into a bunch of statements. top_condition, explanation = self.visit(assert_.test) # If in a test module, check if directly asserting None, in order to warn [Issue #3191] if self.module_path is not None: self.statements.append( self.warn_about_none_ast( top_condition, module_path=self.module_path, lineno=assert_.lineno ) ) if self.enable_assertion_pass_hook: # Experimental pytest_assertion_pass hook negation = ast.UnaryOp(ast.Not(), top_condition) msg = self.pop_format_context(ast.Str(explanation)) # Failed if assert_.msg: assertmsg = self.helper("_format_assertmsg", assert_.msg) gluestr = "\n>assert " else: assertmsg = ast.Str("") gluestr = "assert " err_explanation = ast.BinOp(ast.Str(gluestr), ast.Add(), msg) err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation) err_name = ast.Name("AssertionError", ast.Load()) fmt = self.helper("_format_explanation", err_msg) exc = ast.Call(err_name, [fmt], []) raise_ = ast.Raise(exc, None) statements_fail = [] statements_fail.extend(self.expl_stmts) statements_fail.append(raise_) # Passed fmt_pass = self.helper("_format_explanation", msg) orig = self._assert_expr_to_lineno()[assert_.lineno] hook_call_pass = ast.Expr( self.helper( "_call_assertion_pass", ast.Num(assert_.lineno), ast.Str(orig), fmt_pass, ) ) # If any hooks implement assert_pass hook hook_impl_test = ast.If( self.helper("_check_if_assertion_pass_impl"), self.expl_stmts + [hook_call_pass], [], ) statements_pass = [hook_impl_test] # Test for assertion condition main_test = ast.If(negation, statements_fail, statements_pass) self.statements.append(main_test) if self.format_variables: variables = [ ast.Name(name, ast.Store()) for name in self.format_variables ] clear_format = ast.Assign(variables, ast.NameConstant(None)) self.statements.append(clear_format) else: # Original assertion rewriting # Create failure message. body = self.expl_stmts negation = ast.UnaryOp(ast.Not(), top_condition) self.statements.append(ast.If(negation, body, [])) if assert_.msg: assertmsg = self.helper("_format_assertmsg", assert_.msg) explanation = "\n>assert " + explanation else: assertmsg = ast.Str("") explanation = "assert " + explanation template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation)) msg = self.pop_format_context(template) fmt = self.helper("_format_explanation", msg) err_name = ast.Name("AssertionError", ast.Load()) exc = ast.Call(err_name, [fmt], []) raise_ = ast.Raise(exc, None) body.append(raise_) # Clear temporary variables by setting them to None. if self.variables: variables = [ast.Name(name, ast.Store()) for name in self.variables] clear = ast.Assign(variables, ast.NameConstant(None)) self.statements.append(clear) # Fix line numbers. for stmt in self.statements: set_location(stmt, assert_.lineno, assert_.col_offset) return self.statements def warn_about_none_ast(self, node, module_path, lineno): """ Returns an AST issuing a warning if the value of node is `None`. This is used to warn the user when asserting a function that asserts internally already. See issue #3191 for more details. """ # Using parse because it is different between py2 and py3. AST_NONE = ast.parse("None").body[0].value val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE]) send_warning = ast.parse( """\ from _pytest.warning_types import PytestAssertRewriteWarning from warnings import warn_explicit warn_explicit( PytestAssertRewriteWarning('asserting the value None, please use "assert is None"'), category=None, filename={filename!r}, lineno={lineno}, ) """.format( filename=module_path, lineno=lineno ) ).body return ast.If(val_is_none, send_warning, []) def visit_Name(self, name): # Display the repr of the name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast.Call(self.builtin("locals"), [], []) inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs]) dorepr = self.helper("_should_repr_global_name", name) test = ast.BoolOp(ast.Or(), [inlocs, dorepr]) expr = ast.IfExp(test, self.display(name), ast.Str(name.id)) return name, self.explanation_param(expr) def visit_BoolOp(self, boolop): res_var = self.variable() expl_list = self.assign(ast.List([], ast.Load())) app = ast.Attribute(expl_list, "append", ast.Load()) is_or = int(isinstance(boolop.op, ast.Or)) body = save = self.statements fail_save = self.expl_stmts levels = len(boolop.values) - 1 self.push_format_context() # Process each operand, short-circuiting if needed. for i, v in enumerate(boolop.values): if i: fail_inner = [] # cond is set in a prior loop iteration below self.expl_stmts.append(ast.If(cond, fail_inner, [])) # noqa self.expl_stmts = fail_inner self.push_format_context() res, expl = self.visit(v) body.append(ast.Assign([ast.Name(res_var, ast.Store())], res)) expl_format = self.pop_format_context(ast.Str(expl)) call = ast.Call(app, [expl_format], []) self.expl_stmts.append(ast.Expr(call)) if i < levels: cond = res if is_or: cond = ast.UnaryOp(ast.Not(), cond) inner = [] self.statements.append(ast.If(cond, inner, [])) self.statements = body = inner self.statements = save self.expl_stmts = fail_save expl_template = self.helper("_format_boolop", expl_list, ast.Num(is_or)) expl = self.pop_format_context(expl_template) return ast.Name(res_var, ast.Load()), self.explanation_param(expl) def visit_UnaryOp(self, unary): pattern = UNARY_MAP[unary.op.__class__] operand_res, operand_expl = self.visit(unary.operand) res = self.assign(ast.UnaryOp(unary.op, operand_res)) return res, pattern % (operand_expl,) def visit_BinOp(self, binop): symbol = BINOP_MAP[binop.op.__class__] left_expr, left_expl = self.visit(binop.left) right_expr, right_expl = self.visit(binop.right) explanation = "({} {} {})".format(left_expl, symbol, right_expl) res = self.assign(ast.BinOp(left_expr, binop.op, right_expr)) return res, explanation def visit_Call(self, call): """ visit `ast.Call` nodes """ new_func, func_expl = self.visit(call.func) arg_expls = [] new_args = [] new_kwargs = [] for arg in call.args: res, expl = self.visit(arg) arg_expls.append(expl) new_args.append(res) for keyword in call.keywords: res, expl = self.visit(keyword.value) new_kwargs.append(ast.keyword(keyword.arg, res)) if keyword.arg: arg_expls.append(keyword.arg + "=" + expl) else: # **args have `arg` keywords with an .arg of None arg_expls.append("**" + expl) expl = "{}({})".format(func_expl, ", ".join(arg_expls)) new_call = ast.Call(new_func, new_args, new_kwargs) res = self.assign(new_call) res_expl = self.explanation_param(self.display(res)) outer_expl = "{}\n{{{} = {}\n}}".format(res_expl, res_expl, expl) return res, outer_expl def visit_Starred(self, starred): # From Python 3.5, a Starred node can appear in a function call res, expl = self.visit(starred.value) new_starred = ast.Starred(res, starred.ctx) return new_starred, "*" + expl def visit_Attribute(self, attr): if not isinstance(attr.ctx, ast.Load): return self.generic_visit(attr) value, value_expl = self.visit(attr.value) res = self.assign(ast.Attribute(value, attr.attr, ast.Load())) res_expl = self.explanation_param(self.display(res)) pat = "%s\n{%s = %s.%s\n}" expl = pat % (res_expl, res_expl, value_expl, attr.attr) return res, expl def visit_Compare(self, comp): self.push_format_context() left_res, left_expl = self.visit(comp.left) if isinstance(comp.left, (ast.Compare, ast.BoolOp)): left_expl = "({})".format(left_expl) res_variables = [self.variable() for i in range(len(comp.ops))] load_names = [ast.Name(v, ast.Load()) for v in res_variables] store_names = [ast.Name(v, ast.Store()) for v in res_variables] it = zip(range(len(comp.ops)), comp.ops, comp.comparators) expls = [] syms = [] results = [left_res] for i, op, next_operand in it: next_res, next_expl = self.visit(next_operand) if isinstance(next_operand, (ast.Compare, ast.BoolOp)): next_expl = "({})".format(next_expl) results.append(next_res) sym = BINOP_MAP[op.__class__] syms.append(ast.Str(sym)) expl = "{} {} {}".format(left_expl, sym, next_expl) expls.append(ast.Str(expl)) res_expr = ast.Compare(left_res, [op], [next_res]) self.statements.append(ast.Assign([store_names[i]], res_expr)) left_res, left_expl = next_res, next_expl # Use pytest.assertion.util._reprcompare if that's available. expl_call = self.helper( "_call_reprcompare", ast.Tuple(syms, ast.Load()), ast.Tuple(load_names, ast.Load()), ast.Tuple(expls, ast.Load()), ast.Tuple(results, ast.Load()), ) if len(comp.ops) > 1: res = ast.BoolOp(ast.And(), load_names) else: res = load_names[0] return res, self.explanation_param(self.pop_format_context(expl_call))
ekwoodrich/python-dvrip
env/lib/python3.5/site-packages/_pytest/assertion/rewrite.py
Python
mit
39,456
[ "VisIt" ]
90605415410cc00873ef7daea6bade30cd74cdc82fdbe2af61b9dade7e10197f
import os import logging import re import simtk.unit as units import numpy as np from intermol.forces import * import intermol.forces.forcefunctions as ff from intermol.exceptions import (UnimplementedFunctional, UnsupportedFunctional, UnimplementedSetting, UnsupportedSetting, LammpsError, InterMolError) from intermol.atom import Atom from intermol.molecule import Molecule from intermol.moleculetype import MoleculeType from intermol.system import System logger = logging.getLogger('InterMolLog') ENGINE = 'lammps' def load(in_file): """Load a LAMMPS input file into a `System`. Args: in_file: include_dir: defines: Returns: system: """ parser = LammpsParser(in_file) return parser.read() def save(in_file, system, unit_set='real', nonbonded_style='pair_style lj/cut/coul/long 9.0 9.0\nkspace_style pppm 1e-6\n'): """write a `System` into LAMMPS input file. Args: in_file: system: unit_set: nonbonded_style: default is for a periodic system Returns: system: """ parser = LammpsParser(in_file, system) return parser.write(unit_set=unit_set, nonbonded_style=nonbonded_style) class LammpsParser(object): """A class containing methods to read and write LAMMPS files. """ SCALE_INTO = 2.0 SCALE_FROM = 0.5 lammps_bonds = { 'harmonic': HarmonicBond, 'morse': MorseBond, 'class2': QuarticBond, # TODO: coefficients need special handling. 'fene': FeneExpandableBond, # TODO: need special handling for LJ terms 'fene/expand': FeneExpandableBond, # TODO: need special handling for LJ terms 'quartic': QuarticBreakableBond, 'nonlinear': NonlinearBond } lookup_lammps_bonds = {v: k for k, v in lammps_bonds.items()} # Add some non 1-to-1 mappings. lookup_lammps_bonds[HarmonicPotentialBond] = 'harmonic' lammps_bond_types = dict( (k, eval(v.__name__ + 'Type')) for k, v in lammps_bonds.items()) def canonical_bond(self, params, bond, direction='into'): """Convert to/from the canonical form of this interaction. """ # TODO: Gromacs says harmonic potential bonds do not have constraints or # exclusions. Check that this logic is supported. if direction == 'into': canonical_force_scale = self.SCALE_INTO else: try: typename = self.lookup_lammps_bonds[bond.__class__] except KeyError: if bond.__class__.__name__ in ['FeneBond', 'ConnectionBond']: raise UnimplementedFunctional(bond, ENGINE) else: raise UnsupportedFunctional(bond, ENGINE) canonical_force_scale = self.SCALE_FROM if bond.__class__ in [HarmonicBond, HarmonicPotentialBond]: params['k'] *= canonical_force_scale if bond.__class__ == HarmonicPotentialBond: typename = 'harmonic' if direction == 'into': return bond, params else: return typename, [params] # we expect a list lammps_angles = { 'harmonic': HarmonicAngle, 'cosine': CosineAngle, 'cosine/squared': CosineSquaredAngle, 'charmm': UreyBradleyAngle } lookup_lammps_angles = dict((v, k) for k, v in lammps_angles.items()) lammps_angle_types = dict( (k, eval(v.__name__ + 'Type')) for k, v in lammps_angles.items()) def canonical_angle(self, params, angle, direction): """Convert from the canonical form of this interaction. """ if direction == 'into': canonical_force_scale = self.SCALE_INTO angletest = angle else: try: typename = self.lookup_lammps_angles[angle.__class__] except KeyError: raise UnsupportedFunctional(angle, ENGINE) angletest = angle.__class__ canonical_force_scale = self.SCALE_FROM if angletest in [HarmonicAngle, CosineSquaredAngle, UreyBradleyAngle]: params['k'] *= canonical_force_scale if angletest == UreyBradleyAngle: params['kUB'] *= canonical_force_scale if direction == 'into': return angle, params else: return typename, [params] # We expect a list lammps_dihedrals = { 'opls': FourierDihedral, 'multi/harmonic': RbDihedral, 'charmm': ProperPeriodicDihedral, # not quite canonical form, but easily interconvertible } # Have to manually reverse dihedrals -- not unique. lookup_lammps_dihedrals = { TrigDihedral: 'Trig', RbDihedral: 'multi/harmonic', FourierDihedral: 'opls', ProperPeriodicDihedral: 'charmm' # not quite canonical form, but easily interconvertible } lammps_dihedral_types = dict( (k, eval(v.__name__ + 'Type')) for k, v in lammps_dihedrals.items()) lammps_impropers = { 'harmonic': ImproperHarmonicDihedral, 'cvff': TrigDihedral, } lookup_lammps_impropers = dict((v, k) for k, v in lammps_impropers.items()) lammps_improper_types = dict( (k, eval(v.__name__ + 'Type')) for k, v in lammps_impropers.items()) def canonical_dihedral(self, params, dihedral, direction='into'): """Convert from the canonical form of this interaction. """ if direction == 'into': converted_dihedral = dihedral # Default if dihedral == ProperPeriodicDihedral: # Proper dihedral convertfunc = convert_dihedral_from_proper_to_trig converted_dihedral = TrigDihedral elif dihedral == ImproperHarmonicDihedral: convertfunc = convert_nothing elif dihedral == RbDihedral: convertfunc = convert_dihedral_from_RB_to_trig converted_dihedral = TrigDihedral elif dihedral == FourierDihedral: convertfunc = convert_dihedral_from_fourier_to_trig converted_dihedral = TrigDihedral # Now actually convert the dihedral. params = convertfunc(params) # Adjust scaling conventions. canonical_force_scale = self.SCALE_INTO if converted_dihedral == ImproperHarmonicDihedralType: params['k'] *= canonical_force_scale return converted_dihedral, params else: dihedral_class = dihedral.__class__ canonical_force_scale = self.SCALE_FROM if dihedral_class == TrigDihedral: if False: #dihedral.improper: # TODO d_type = '4' paramlist = convert_dihedral_from_trig_to_proper(params) else: if (params['phi'].value_in_unit(units.degrees) in [0, 180] and params['fc5']._value == 0 and params['fc6']._value == 0): typename = 'multi/harmonic' parameters = convert_dihedral_from_trig_to_RB(params) paramlist = [parameters] else: # Print as proper dihedral. If one nonzero term, as a # type 1, if multiple, type 9. typename = 'charmm' paramlist = convert_dihedral_from_trig_to_proper(params) elif dihedral_class == ImproperHarmonicDihedral: params['k'] *= canonical_force_scale typename = 'harmonic' paramlist = [params] else: raise UnsupportedFunctional(dihedral, ENGINE) return typename, paramlist def create_kwds_from_entries(self, entries, force_class, offset=0): return ff.create_kwds_from_entries(self.unitvars, self.paramlist, entries, force_class, offset=offset) def get_parameter_list_from_force(self, force): return ff.get_parameter_list_from_force(force, self.paramlist) def get_parameter_kwds_from_force(self, force): return ff.get_parameter_kwds_from_force( force, self.get_parameter_list_from_force, self.paramlist) def __init__(self, in_file, system=None): """ """ self.in_file = in_file if not system: system = System() self.system = system self.data_file = None def set_units(self, unit_set): """Set what unit set to use. """ self.RAD = units.radians self.DEGREE = units.degrees self.MOLE = units.mole self.TEMP = units.kelvin if unit_set == 'real': self.DIST = units.angstroms self.VEL = units.angstroms / units.femtosecond self.ENERGY = units.kilocalorie / units.mole self.MASS = units.grams / units.mole self.CHARGE = units.elementary_charge elif unit_set == 'metal': self.DIST = units.angstroms self.VEL = units.angstroms / units.picosecond self.ENERGY = units.joule / units.coulomb * units.elementary_charge self.MASS = units.grams / units.mole self.CHARGE = units.elementary_charge elif unit_set == 'si': self.DIST = units.meters self.VEL = units.meters / units.second self.ENERGY = units.joules self.MASS = units.kilograms self.CHARGE = units.coulomb elif unit_set == 'cgs': self.DIST = units.centimeter self.VEL = units.centimeter / units.second self.ENERGY = units.erg self.MASS = units.grams self.CHARGE = np.sqrt(units.erg * units.centimeter) elif unit_set == 'micro': self.DIST = units.micrometers self.VEL = units.nanometers / units.nanosecond self.ENERGY = units.picogram * ( units.micrometer / units.microsecond) ^ 2 self.MASS = units.attograms self.CHARGE = units.elementary_charge elif unit_set == 'nano': self.DIST = units.nanometers self.VEL = units.nanometer / units.nanosecond self.ENERGY = units.attogram * ( units.nanometer / units.nanosecond) ^ 2 self.MASS = units.attograms self.CHARGE = units.elementary_charge elif unit_set == 'lj': self.DIST = units.dimensionless self.VEL = units.dimensionless self.ENERGY = units.dimensionless self.MASS = units.dimensionless self.CHARGE = units.dimensionless logger.warning("Using unit type lj: All values are dimensionless. " "This is untested and will likely fail. " "See LAMMPS doc for more.") elif unit_set == 'electron': self.DIST = units.bohr self.VEL = units.bohr / units.atu self.ENERGY = units.hartree self.MASS = units.amu self.CHARGE = units.elementary_charge else: raise LammpsError('Unsupported unit set specified: {0}'.format(unit_set)) # Now create the dictionary of which units go in which order # for each command. we need to pass 'self' so that we can # access the different unit sets, but the function unitvars is # not actually a member, so we have to do it in a nonstandard way. self.paramlist = ff.build_paramlist('lammps') self.unitvars = ff.build_unitvars('lammps', self.paramlist, dumself=self) def read(self): """Reads a LAMMPS input file and a data file specified within. Returns: system: """ self.read_input() if self.data_file: self.read_data(self.data_file) else: raise LammpsError("No data file found in input script") return self.system def read_input(self): """Reads a LAMMPS input file. Args: input_file (str): Name of LAMMPS input file to read in. """ self.input_dir = os.path.dirname(os.path.realpath(self.in_file)) parsable_keywords = { 'units': self.parse_units, 'atom_style': self.parse_atom_style, 'dimension': self.parse_dimension, 'boundary': self.parse_boundary, 'pair_style': self.parse_pair_style, 'kspace_style': self.parse_kspace_style, 'pair_modify': self.parse_pair_modify, 'bond_style': self.parse_bond_style, 'angle_style': self.parse_angle_style, 'dihedral_style': self.parse_dihedral_style, 'improper_style': self.parse_improper_style, 'special_bonds': self.parse_special_bonds, 'read_data': self.parse_read_data} defaults = [ 'units lj', 'atom_style atomic', 'dimension 3', 'boundary p p p', 'pair_style none', 'kspace_style none', 'pair_modify mix geometric shift no table 12 tabinner sqrt(2.0) tail no compute yes', 'bond_style none', 'angle_style none', 'dihedral_style none', 'improper_style none', 'special_bonds lj 0.0 0.0 0.0 coul 0.0 0.0 0.0 angle no dihedral no extra 0'] keyword_defaults = {x.split()[0]: x for x in defaults} keyword_check = {x: False for x in keyword_defaults.keys()} with open(self.in_file, 'r') as input_lines: for line in input_lines: if line.strip(): keyword = line.split()[0] if keyword in parsable_keywords: parsable_keywords[keyword](line.split()) keyword_check[keyword] = True for key in keyword_check.keys(): if not (keyword_check[key]): logger.warning('Keyword {0} not set, using LAMMPS default value {1}'.format( key, " ".join(keyword_defaults[key].split()[1:]))) parsable_keywords[key](keyword_defaults[key].split()) self.set_units(self.unit_set) def read_data(self, data_file): """Reads a LAMMPS data file. Args: data_file (str): name of LAMMPS data file to read in. """ # Read box, masses and forcefield info from data file. parsable_keywords = {'Masses': self.parse_masses, 'Pair Coeffs': self.parse_pair_coeffs, 'Bond Coeffs': self.parse_bond_coeffs, 'Angle Coeffs': self.parse_angle_coeffs, 'Dihedral Coeffs': self.parse_dihedral_coeffs, 'Improper Coeffs': self.parse_improper_coeffs} with open(data_file, 'r') as data_lines: self.molecule_name = next(data_lines).strip() # Currently only reading a single molecule/moleculeType # per LAMMPS file. self.current_mol_type = MoleculeType(self.molecule_name) self.current_mol_type.nrexcl = 3 # TODO: automate determination! # NOTE: nrexcl is a global in lammps and should probably be # determined in parse_special_bonds self.system.add_molecule_type(self.current_mol_type) self.current_mol = Molecule(self.molecule_name) self.system.add_molecule(self.current_mol) for line in data_lines: if line.strip(): # Remove trailing comment line = line.partition('#')[0] # Catch all box dimensions. if ('xlo' in line) and ('xhi' in line): self.parse_box(line.split(), 0) elif ('ylo' in line) and ('yhi' in line): self.parse_box(line.split(), 1) elif ('zlo' in line) and ('zhi' in line): self.parse_box(line.split(), 2) # Other headers. else: keyword = line.strip() if keyword in parsable_keywords: parsable_keywords[keyword](data_lines) # Read atoms, velocities and connectivity information from data file. parsable_keywords = {'Atoms': self.parse_atoms, 'Velocities': self.parse_velocities, 'Bonds': self.parse_bonds, 'Angles': self.parse_angles, 'Dihedrals': self.parse_dihedrals, 'Impropers': self.parse_impropers} with open(data_file, 'r') as data_lines: for line in data_lines: if line.strip(): keyword = line.partition('#')[0].strip() if keyword in parsable_keywords: parsable_keywords[keyword](data_lines) # Indentify 1-2, 1-3, and 1-4 neighbors and create pair forces for mol_type in self.system.molecule_types.values(): molecule = list(mol_type.molecules)[0] onetwo = [set() for i in range(len(molecule.atoms) + 1)] onethree = [set() for i in range(len(molecule.atoms) + 1)] onefour = [set() for i in range(len(molecule.atoms) + 1)] # 1-2 neighbors for bond in mol_type.bond_forces: onetwo[bond.atom1].add(bond.atom2) onetwo[bond.atom2].add(bond.atom1) for ai in [atom.index for atom in molecule.atoms]: # 1-3 neighbors for aj in onetwo[ai]: for ak in onetwo[aj]: if not ((ak == ai) or (ak in onetwo[ai])): onethree[ai].add(ak) # 1-4 neighbors for aj in onethree[ai]: for ak in onetwo[aj]: if not ((ak == ai) or (ak in onetwo[ai]) or (ak in onethree[ai])): onefour[ai].add(ak) # Generate 1-4 pairs (need to check nrexcl, lj/coulomb correction) for ai in [atom.index for atom in molecule.atoms]: for aj in onefour[ai]: if aj >= ai: mol_type.pair_forces.add(LjDefaultPair(ai, aj)) def parse_units(self, line): """ """ assert (len(line) == 2), "Invalid units specified in input file." self.unit_set = line[1] def parse_atom_style(self, line): """ Note: Assuming 'full' as default for everything else. """ self.atom_style = line[1] if len(line) > 2: raise UnimplementedSetting(line, ENGINE) # TODO: Add remaining atom_styles # http://lammps.sandia.gov/doc/atom_style.html # See issue: self.q_idx = None self.res_idx = None if self.atom_style == 'full': self.res_idx = 1 self.type_idx = 2 self.q_idx = 3 self.pos_idx = (4, 5, 6) elif self.atom_style == 'molecular': self.res_idx = 1 self.type_idx = 2 self.pos_idx = (3, 4, 5) elif self.atom_style == 'charge': self.type_idx = 1 self.q_idx = 2 self.pos_idx = (3, 4, 5) elif self.atom_style in ('angle', 'atomic', 'bond'): self.type_idx = 1 self.pos_idx = (2, 3, 4) def parse_dimension(self, line): """ """ self.dimension = int(line[1]) if self.dimension not in [2, 3]: raise LammpsError("Invalid dimension specified in input file " "(must be 2 or 3).") def parse_boundary(self, line): """ """ self.boundaries = [line[1], line[2], line[3]] if len(self.boundaries) != self.dimension: raise LammpsError("Boundaries do not match specified dimension " "in input file") def parse_pair_style(self, line): """ """ self.pair_style = [] if line[1] in ('lj/cut/coul/long', 'lj/cut', 'lj/cut/coul/cut'): self.pair_style.append(line[1]) self.system.nonbonded_function = 1 else: raise UnimplementedSetting(line, ENGINE) def parse_kspace_style(self, line): """ Note: Currently ignored. """ if line[1] == 'pppm': pass def parse_pair_modify(self, line): """ """ if line[1] == 'mix': if line[2] == 'geometric': self.system.combination_rule = 'Multiply-Sigeps' elif line[2] == 'arithmetic': self.system.combination_rule = 'Lorentz-Berthelot' else: raise UnimplementedSetting(line, ENGINE) else: raise UnimplementedSetting(line, ENGINE) def parse_bonded_style(self, line): """ """ style_set = set() if len(line) == 2: style_set.add(line[1]) elif line[1] == 'hybrid': for style in line[2:]: style_set.add(style) else: raise LammpsError("Invalid style in input file: {}!".format(line)) return style_set def parse_bond_style(self, line): """ """ self.bond_style = self.parse_bonded_style(line) def parse_angle_style(self, line): """ """ self.angle_style = self.parse_bonded_style(line) def parse_dihedral_style(self, line): """ """ self.dihedral_style = self.parse_bonded_style(line) # TODO: correctly determine gen-pairs state if self.dihedral_style == 'opls': self.system.genpairs = 'yes' def parse_improper_style(self, line): """ """ self.improper_style = self.parse_bonded_style(line) def parse_special_bonds(self, line): """ """ if 'lj/coul' in line: self.system.lj_correction = float(line[line.index('lj/coul') + 3]) self.system.coulomb_correction = float( line[line.index('lj/coul') + 3]) elif 'lj' in line and 'coul' in line: self.system.lj_correction = float(line[line.index('lj') + 3]) self.system.coulomb_correction = float(line[line.index('coul') + 3]) elif 'lj' in line: self.system.lj_correction = float(line[line.index('lj') + 3]) elif 'coul' in line: self.system.coulomb_correction = float(line[line.index('coul') + 3]) else: raise UnimplementedSetting(line, ENGINE) def parse_read_data(self, line): """ """ if len(line) == 2: self.data_file = os.path.join(self.input_dir, line[1]) else: raise UnimplementedSetting(line, ENGINE) def parse_box(self, line, dim): """Read box information from data file. Args: line (str): Current line in input file. dim (int): Dimension specified in line. """ fields = [float(field) for field in line[:2]] box_length = fields[1] - fields[0] if box_length > 0: self.system.box_vector[dim, dim] = box_length * self.DIST else: raise LammpsError("Negative box length specified in data file.") def parse_masses(self, data_lines): """Read masses from data file.""" next(data_lines) # toss out blank line self.mass_dict = dict() for line in data_lines: if not line.strip(): break # found another blank line fields = line.partition('#')[0].split() self.mass_dict[int(fields[0])] = float(fields[1]) * self.MASS def parse_pair_coeffs(self, data_lines): """Read pair coefficients from data file.""" next(data_lines) # toss out blank line self.nb_types = dict() for line in data_lines: if not line.strip(): break # found another blank line fields = [float(field) for field in line.partition('#')[0].split()] if len(self.pair_style) == 1: # TODO: lookup of type of pairstyle to determine format if self.system.nonbonded_function == 1: self.nb_types[int(fields[0])] = [fields[1] * self.ENERGY, fields[2] * self.DIST] else: raise UnimplementedSetting(line, ENGINE) else: raise UnimplementedFunctional(line, ENGINE) def parse_force_coeffs(self, data_lines, force_name, force_classes, force_style, lammps_forces, canonical_force): """Read force coefficients from data file.""" next(data_lines) # toss out blank line for line in data_lines: if not line.strip(): break # found another blank line fields = line.partition('#')[0].split() warn = False if len(force_style) == 1: style = list(force_style)[0] # awkward to have to translate to list to get the only member! if style == fields[1]: field_offset = 2 else: if re.search('[a-zA-Z]+', fields[1]): if style == 'none': style = fields[1] field_offset = 2 else: warn = True else: field_offset = 1 elif len(force_style) > 1: style = fields[1] field_offset = 2 if style not in force_style: warn = True else: raise LammpsError("No entries found in '%s_style'." % (force_name)) if warn: logger.warning('{0} type found in {1} Coeffs that was not ' 'specified in {2}_style: {3}'.format(force_name, force_name, force_name, style)) # what internal force correspond to this style force_class = lammps_forces[style] # Get the parameters from the line and translate into keywords kwds = self.create_kwds_from_entries(fields, force_class, offset=field_offset) # translate the force into canonical form force_class, kwds = canonical_force(kwds, force_class, direction='into') # add to the dictionary of this force term force_classes[int(fields[0])] = [force_class, kwds] def parse_bond_coeffs(self, data_lines): self.bond_classes = dict() self.parse_force_coeffs(data_lines, "Bond", self.bond_classes, self.bond_style, self.lammps_bonds, self.canonical_bond) def parse_angle_coeffs(self, data_lines): self.angle_classes = dict() self.parse_force_coeffs(data_lines, "Angle", self.angle_classes, self.angle_style, self.lammps_angles, self.canonical_angle) def parse_dihedral_coeffs(self, data_lines): self.dihedral_classes = dict() self.parse_force_coeffs(data_lines, "Dihedral", self.dihedral_classes, self.dihedral_style, self.lammps_dihedrals, self.canonical_dihedral) def parse_improper_coeffs(self, data_lines): self.improper_classes = dict() self.parse_force_coeffs(data_lines, "Improper", self.improper_classes, self.improper_style, self.lammps_impropers, self.canonical_dihedral) def parse_atoms(self, data_lines): """Read atoms from data file.""" next(data_lines) # toss out blank line for line in data_lines: if not line.strip(): break # found another blank line fields = line.partition('#')[0].split() if len(fields) == 10: # TODO: store image flags? pass new_atom_type = None if self.system.combination_rule == "Multiply-C6C12": logger.warning("Combination rule 'Multiply-C6C12' not yet implemented") elif self.system.combination_rule in ['Multiply-Sigeps', 'Lorentz-Berthelot']: atomtype = 'lmp_{:03d}'.format(int(fields[self.type_idx])) bondtype = atomtype new_atom_type = AtomSigepsType( atomtype, # atomtype bondtype, # bondtype -1, # atomic_number self.mass_dict[int(fields[self.type_idx])], # mass 0 * self.CHARGE, # charge (0 for atomtype) 'A', # ptype self.nb_types[int(fields[self.type_idx])][1], # sigma self.nb_types[int(fields[self.type_idx])][0]) # epsilon self.system.add_atomtype(new_atom_type) atom = Atom(int(fields[0]), # index 'A{:x}'.format(int(fields[0])), # name (A + idx in hex) 1, # residue_index (lammps doesn't track this) 'R{:02d}'.format(1)) # residue_name (R + moltype num) atom.atomtype = (0, atomtype) atom.atomic_number = 0 #TODO: this must be defined for Desmond output; can we get this from LAMMPS? atom.cgnr = 0 # TODO: look into alternatives atom.mass = (0, self.mass_dict[int(fields[self.type_idx])]) atom.epsilon = (0, self.nb_types[int(fields[self.type_idx])][0]) atom.sigma = (0, self.nb_types[int(fields[self.type_idx])][1]) atom.bondingtype = bondtype if self.q_idx: atom.charge = (0, float(fields[self.q_idx]) * self.CHARGE) else: atom.charge = (0, 0.0 * self.CHARGE) atom.position = [float(fields[self.pos_idx[0]]) * self.DIST, float(fields[self.pos_idx[1]]) * self.DIST, float(fields[self.pos_idx[2]]) * self.DIST] self.current_mol.add_atom(atom) def parse_velocities(self, data_lines): """ """ next(data_lines) atoms = self.current_mol.atoms vel_dict = dict() for line in data_lines: if not line.strip(): break fields = [field for field in line.partition('#')[0].split()] vel_dict[int(fields[0])] = fields[1:4] for atom in atoms: atom._velocity = [float(vel) * self.VEL for vel in vel_dict[atom.index]] def parse_force(self, data_lines, force_classes, forceSet, n=0): """Read bonds, angles, dihedrals, impropers from data file.""" next(data_lines) # toss out blank line for line in data_lines: if not line.strip(): break # found another blank line fields = [int(field) for field in line.partition('#')[0].split()] new_force = None coeff_num = fields[1] atom_nums = fields[2:n + 2] paraminfo = force_classes[coeff_num] kwds = paraminfo[1] new_force = paraminfo[0](*atom_nums, **kwds) forceSet.add(new_force) def parse_bonds(self, data_lines): self.parse_force(data_lines, self.bond_classes, self.current_mol_type.bond_forces, n=2) def parse_angles(self, data_lines): self.parse_force(data_lines, self.angle_classes, self.current_mol_type.angle_forces, n=3) def parse_dihedrals(self, data_lines): self.parse_force(data_lines, self.dihedral_classes, self.current_mol_type.dihedral_forces, n=4) def parse_impropers(self, data_lines): self.parse_force(data_lines, self.improper_classes, self.current_mol_type.dihedral_forces, n=4) def get_force_atoms(self, force, forceclass): """Return the atoms involved in a force. """ if forceclass in ['Bond', 'Pair']: return [force.atom1, force.atom2] elif forceclass in ['Angle']: return [force.atom1, force.atom2, force.atom3] elif forceclass in ['Dihedral', 'Improper']: return [force.atom1, force.atom2, force.atom3, force.atom4] else: logger.warning("No interaction type %s defined!" % (forceclass)) def get_force_bondingtypes(self, force, forceclass): """Return the atoms involved in a force. """ if forceclass in ['Bond', 'Pair']: return [force.bondingtype1, force.bondingtype2] elif forceclass in ['Angle']: return [force.bondingtype1, force.bondingtype2, force.bondingtype3] elif forceclass in ['Dihedral', 'Improper']: return [force.bondingtype1, force.bondingtype2, force.bondingtype3, force.bondingtype4] else: logger.warning("No interaction type %s defined!" % (forceclass)) def write_forces(self, forces, offset, force_name, lookup_lammps_force, lammps_force_types, canonical_force): """The general force writing function. Currently supports bonds, angles, dihedrals, impropers. """ logger.debug(" Writing {0:s}s...".format(force_name)) force_list = self.force_dict[force_name] force_count = len(force_list) coeff_name = '{0} Coeffs'.format(force_name) coeff_list = self.force_dict[coeff_name] numeric_coeff = self.numeric_coeff[coeff_name] type_count = len(numeric_coeff) + 1 style_set = self.style_dict[force_name] for force in forces: atom_indices = self.get_force_atoms(force, force_name) atom_bondingtypes = self.get_force_bondingtypes(force, force_name) try: lookup_lammps_force[force.__class__] except KeyError: logger.warning("Found unimplemented {0} type {1} for LAMMPS!".format( force_name, force.__class__.__name__)) # Get the parameters of the force. kwds = self.get_parameter_kwds_from_force(force) # Convert keywords from canonical form. style, kwdslist = canonical_force(kwds, force, direction='from') force_type = lammps_force_types[style] style_set.add(style) # A single force can produce multiple forces. for kwds in kwdslist: temp_force_type = force_type(*atom_bondingtypes, **kwds) # New type found. Write out the force coefficients. # TODO: Check by content would be nice but may lead to the # equality issues again. if temp_force_type not in numeric_coeff: # Get the numerical type for this interaction. numeric_coeff[temp_force_type] = type_count line = '{0:d} {1}'.format(type_count, style) type_count += 1 # Generate the list of parameters for this force in the # order they appear in the file format. params = self.get_parameter_list_from_force(temp_force_type) # Generate the units for this force. u = self.unitvars[force_type.__name__] for i, p in enumerate(params): if p.unit == units.dimensionless and isinstance(p._value, int): # LAMMPS expects an integer. line += "%10d" % (p.value_in_unit(u[i])) elif style == 'charmm' and p.unit == units.degrees: if force_name == 'Dihedral': # LAMMPS loves enforcing unnecessary integers. line += "%10d" % (p.value_in_unit(u[i])) else: line += "%18.8e" % (p.value_in_unit(u[i])) else: line += "%18.8e" % (p.value_in_unit(u[i])) line += '\n' coeff_list.append(line) # Write out the force entry. line = '{0:-6d} {1:6d}'.format(force_count, numeric_coeff[temp_force_type]) for atom in atom_indices: line += ' {0:d}'.format(atom + offset) line += '\n' force_list.append(line) force_count += 1 def write_bonds(self, mol_type, offset): bonds = sorted(mol_type.bond_forces, key=lambda x: (x.atom1, x.atom2)) self.write_forces(bonds, offset, "Bond", self.lookup_lammps_bonds, self.lammps_bond_types, self.canonical_bond) def write_angles(self, mol_type, offset): angles = sorted(mol_type.angle_forces, key=lambda x: (x.atom1, x.atom2, x.atom3)) return self.write_forces(angles, offset, "Angle", self.lookup_lammps_angles, self.lammps_angle_types, self.canonical_angle) def write_dihedrals(self, mol_type, offset): """Separate dihedrals from impropers. """ dihedral_forces = {force for force in mol_type.dihedral_forces if force.__class__ != ImproperHarmonicDihedral} dihedrals = sorted(dihedral_forces, key=lambda x: (x.atom1, x.atom2, x.atom3, x.atom4)) return self.write_forces(dihedrals, offset, "Dihedral", self.lookup_lammps_dihedrals, self.lammps_dihedral_types, self.canonical_dihedral) def write_impropers(self, mol_type, offset): """Separate dihedrals from impropers. """ improper_forces = {force for force in mol_type.dihedral_forces if force.__class__ == ImproperHarmonicDihedral} impropers = sorted(improper_forces, key=lambda x: (x.atom1, x.atom2, x.atom3, x.atom4)) return self.write_forces(impropers, offset, "Improper", self.lookup_lammps_impropers, self.lammps_improper_types, self.canonical_dihedral) def write_virtuals(self, mol_type, offset): if len(mol_type.virtual_forces) > 0: logger.warning('Virtuals not currently supported: will need to be ' 'implemeneted from shake and rigid') def write(self, unit_set='real',nonbonded_style=None): """Writes a LAMMPS data and corresponding input file. Args: data_file (str): Name of LAMMPS data file to write to. unit_set (str): LAMMPS unit set for output file. """ self.data_file = os.path.splitext(self.in_file)[0] + '.lmp' self.set_units(unit_set) # Containers for lines which are ultimately written to output files. mass_list = list() mass_list.append('\nMasses\n\n') pair_coeffs = list() atom_list = list() atom_list.append('\nAtoms\n\n') vel_list = list() vel_list.append('\nVelocities\n\n') # Dicts for type information. atom_type_dict = dict() # str_type:int_type a_type_i = 1 # counter for atom types # Dicts to store the final outputs. self.force_dict = {'Bond': ['\nBonds\n\n'], 'Bond Coeffs': ['\nBond Coeffs\n\n'], 'Angle': ['\nAngles\n\n'], 'Angle Coeffs': ['\nAngle Coeffs\n\n'], 'Dihedral': ['\nDihedrals\n\n'], 'Dihedral Coeffs': ['\nDihedral Coeffs\n\n'], 'Improper': ['\nImpropers\n\n'], 'Improper Coeffs': ['\nImproper Coeffs\n\n'] } # Dicts to store the numeric values for each type (force:int). self.numeric_coeff = {'Bond Coeffs': {}, 'Angle Coeffs': {}, 'Dihedral Coeffs': {}, 'Improper Coeffs': {} } self.style_dict = {'Bond': set(), 'Angle': set(), 'Dihedral': set(), 'Improper': set() } # Read all atom specific and FF information. offset = 0 for mol_name, mol_type in self.system.molecule_types.items(): logger.debug( " Writing moleculetype {0}...".format(mol_name)) # OrderedSet isn't indexable so get the first molecule by iterating. molecule = next(iter(mol_type.molecules)) atoms_per_molecule = len(molecule.atoms) for molecule in mol_type.molecules: # Atom index offsets from 1 for each molecule. self.write_bonds(mol_type, offset) self.write_angles(mol_type, offset) self.write_dihedrals(mol_type, offset) self.write_impropers(mol_type, offset) # Only issues warning now. self.write_virtuals(mol_type, offset) offset += atoms_per_molecule # Atom specific information. x_min = y_min = z_min = np.inf logger.debug(" Writing atoms...") atom_charges = False for molecule in mol_type.molecules: for atom in molecule.atoms: # Type, mass and pair coeffs. if atom.atomtype[0] not in atom_type_dict: atom_type_dict[atom.atomtype[0]] = a_type_i mass_list.append('{0:d} {1:11.7f}\n'.format( a_type_i, atom.mass[0].value_in_unit(self.MASS))) pair_coeffs.append('pair_coeff {0:d} {0:d} {1:11.7f} {2:11.7f}\n'.format( a_type_i, atom.epsilon[0].value_in_unit(self.ENERGY), atom.sigma[0].value_in_unit(self.DIST))) a_type_i += 1 # Box minima. x_coord = atom.position[0].value_in_unit(self.DIST) y_coord = atom.position[1].value_in_unit(self.DIST) z_coord = atom.position[2].value_in_unit(self.DIST) if x_coord < x_min: x_min = x_coord if y_coord < y_min: y_min = y_coord if z_coord < z_min: z_min = z_coord atom_list.append('{0:-6d} {1:-6d} {2:-6d} {3:5.8f} {4:12.7f} {5:12.7f} {6:12.7f}\n'.format( atom.index, atom.residue_index, atom_type_dict[atom.atomtype[0]], atom.charge[0].value_in_unit(self.CHARGE), x_coord, y_coord, z_coord)) if atom.charge[0]._value != 0: atom_charges = True if np.any(atom.velocity): vel_list.append( '{0:-6d} {1:11.7f} {2:11.7f} {3:11.7f}\n'.format( atom.index, atom.velocity[0].value_in_unit(self.VEL), atom.velocity[1].value_in_unit(self.VEL), atom.velocity[2].value_in_unit(self.VEL))) else: vel_list.append( '{0:-6d} {1:11.7f} {2:11.7f} {3:11.7f}\n'.format( atom.index, 0, 0, 0)) for pair in mol_type.pair_forces: if not isinstance(pair, (LjDefaultPairType, LjqDefaultPairType)): atom1_type = int(atom_list[pair.atom1].split()[2]) atom2_type = int(atom_list[pair.atom2].split()[2]) if atom2_type < atom1_type: # LAMMPS requires i < j atom1_type, atom2_type = atom2_type, atom1_type pair_coeffs.append('pair_coeff {0:d} {1:d} {2:11.7f} {3:11.7f}\n'.format( atom1_type, atom2_type, pair.epsilon.value_in_unit(self.ENERGY), pair.sigma.value_in_unit(self.DIST))) bond_list = self.force_dict['Bond'] angle_list = self.force_dict['Angle'] dihedral_list = self.force_dict['Dihedral'] improper_list = self.force_dict['Improper'] bond_coeffs = self.force_dict['Bond Coeffs'] angle_coeffs = self.force_dict['Angle Coeffs'] dihedral_coeffs = self.force_dict['Dihedral Coeffs'] improper_coeffs = self.force_dict['Improper Coeffs'] bond_styles = self.style_dict['Bond'] angle_styles = self.style_dict['Angle'] dihedral_styles = self.style_dict['Dihedral'] improper_styles = self.style_dict['Improper'] # Write the actual data file. with open(self.data_file, 'w') as f: # Front matter. f.write(self.system.name + '\n') f.write('\n') n_atoms = len(atom_list) - 1 n_bonds = len(bond_list) - 1 n_angles = len(angle_list) - 1 n_dihedrals = len(dihedral_list) - 1 n_impropers = len(improper_list) - 1 n_atom_types = len(atom_type_dict) n_bond_types = len(bond_coeffs) - 1 n_angle_types = len(angle_coeffs) - 1 n_dihedral_types = len(dihedral_coeffs) - 1 n_improper_types = len(improper_coeffs) - 1 f.write('{0} atoms\n'.format(n_atoms)) f.write('{0} bonds\n'.format(n_bonds)) f.write('{0} angles\n'.format(n_angles)) f.write('{0} dihedrals\n'.format(n_dihedrals)) f.write('{0} impropers\n'.format(n_impropers)) f.write('\n') f.write('{0} atom types\n'.format(n_atom_types)) if n_bond_types > 0: f.write('{0} bond types\n'.format(n_bond_types)) if n_angle_types > 0: f.write('{0} angle types\n'.format(n_angle_types)) if n_dihedral_types > 0: f.write('{0} dihedral types\n'.format(n_dihedral_types)) if n_improper_types > 0: f.write('{0} improper types\n'.format(n_improper_types)) f.write('\n') # Shifting of box dimensions. f.write('{0:11.7f} {1:11.7f} xlo xhi\n'.format( x_min, x_min + self.system.box_vector[0][0].value_in_unit( self.DIST))) f.write('{0:11.7f} {1:11.7f} ylo yhi\n'.format( y_min, y_min + self.system.box_vector[1][1].value_in_unit( self.DIST))) f.write('{0:11.7f} {1:11.7f} zlo zhi\n'.format( z_min, z_min + self.system.box_vector[2][2].value_in_unit( self.DIST))) for mass in mass_list: f.write(mass) # Forcefield coefficients. coeff_types = [bond_coeffs, angle_coeffs, dihedral_coeffs, improper_coeffs] for coefficients in coeff_types: if len(coefficients) > 1: for coeff in coefficients: f.write(coeff) # Atoms and velocities. for atom in atom_list: f.write(atom) for vel in vel_list: f.write(vel) # Forces. force_lists = [bond_list, angle_list, dihedral_list, improper_list] for force_list in force_lists: if len(force_list) > 1: for force in force_list: f.write(force) # Write the corresponding input file. with open(self.in_file, 'w') as f: f.write('units {0}\n'.format(unit_set)) f.write('atom_style full\n') # TODO f.write('\n') f.write('dimension 3\n') # TODO f.write('boundary p p p\n') # TODO f.write('\n') # bonded if len(bond_coeffs) > 1: f.write('bond_style hybrid {0}\n'.format( " ".join(bond_styles))) if len(angle_coeffs) > 1: f.write('angle_style hybrid {0}\n'.format( " ".join(angle_styles))) if len(dihedral_coeffs) > 1: f.write('dihedral_style hybrid {0}\n'.format( " ".join(dihedral_styles))) if len(improper_coeffs) > 1: f.write('improper_style hybrid {0}\n'.format( " ".join(improper_styles))) f.write('special_bonds lj {0} {1} {2} coul {3} {4} {5}\n'.format( 0.0, 0.0, self.system.lj_correction, 0.0, 0.0, self.system.coulomb_correction)) f.write('\n') # Specify the path to the corresponding data file that we just wrote. f.write('read_data {0}\n'.format(os.path.basename(self.data_file))) f.write('\n') # non-bonded: either defaults, or specified by user f.write(nonbonded_style) for line in pair_coeffs: f.write(line) f.write('\n') if self.system.combination_rule == 'Lorentz-Berthelot': f.write('pair_modify mix arithmetic\n') elif self.system.combination_rule == 'Multiply-Sigeps': f.write('pair_modify mix geometric\n') else: logger.warning("Unsupported pair combination rule on writing input file!") f.write('\n') if len(mol_type.rigidwaters) > 0: f.write('fix settle all shake 0.000001 100 0 t') for rigidwater in mol_type.rigidwaters: molecules = list(mol_type.molecules) a1 = atom_type_dict[molecules[0].atoms[rigidwater.atom1-1].atomtype[0]] a2 = atom_type_dict[molecules[0].atoms[rigidwater.atom1].atomtype[0]] # get the atom types of the first two molecules # settles should be numbered from 0, not 1? # first, write out all the atom types involved: should be the first two in the molecule. f.write(' {0:d} {1:d} a'.format(a1,a2)) angle_i = 0 # add up the angles until the settle. I think this is problematic because # it doesn't take into account any transformation to the number of # angles when lammps writes out. for mol_name_j, mol_type_j in self.system.molecule_types.items(): if mol_name_j != mol_name: angle_i += len(mol_type_j.angle_forces)*len(mol_type_j.molecules) elif mol_name_j == mol_name: break # only one angle per settle angle_range = np.arange(angle_i+1,angle_i+len(mol_type.molecules)+1) for a in angle_range: f.write(' {0:d}'.format(a)) if (a-angle_i)%10 == 0: f.write(' &\n') f.write('\n') # Specify the output energies that we are interested in. energy_terms = " ".join(['ebond', 'eangle', 'edihed', 'eimp', 'epair', 'evdwl', 'ecoul', 'elong', 'etail', 'pe']) f.write('thermo_style custom {0}\n'.format(energy_terms)) f.write('\n') f.write('run 0\n')
ctk3b/InterMol
intermol/lammps/lammps_parser.py
Python
mit
53,114
[ "CHARMM", "Desmond", "Gromacs", "LAMMPS" ]
dd50f069928afe79b31f4c3d3968e993d1ae44e9890295dd5f5d5d68c92d3900
# Copyright 2018, Brian May # # This file is part of Karaage. # # Karaage 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. # # Karaage 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 Karaage If not, see <http://www.gnu.org/licenses/>. from typing import Dict import tldap.django.helpers as dhelpers import tldap.fields from tldap.database import ( Changeset, Database, LdapObject, SearchOptions, helpers, ) class BaseAccount(LdapObject): """ An abstract Generic LDAP account. """ @classmethod def get_fields(cls) -> Dict[str, tldap.fields.Field]: fields = { **helpers.get_fields_common(), **helpers.get_fields_person(), **helpers.get_fields_account(), **helpers.get_fields_shadow(), 'default_project': tldap.fields.FakeField(required=True), } return fields @classmethod def get_search_options(cls, database: Database) -> SearchOptions: settings = database.settings return SearchOptions( base_dn=settings['LDAP_ACCOUNT_BASE'], object_class={'inetOrgPerson', 'organizationalPerson', 'person'}, pk_field="uid", ) @classmethod def on_load(cls, python_data: LdapObject, _database: Database) -> LdapObject: python_data = helpers.load_person(python_data, OpenldapGroup) python_data = helpers.load_account(python_data, OpenldapGroup) python_data = helpers.load_shadow(python_data) return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: settings = database.settings changes = helpers.save_person(changes, database) changes = helpers.save_account(changes, database, {'uid', 'cn', 'givenName', 'sn', 'o', 'default_project'}) changes = helpers.save_shadow(changes) changes = helpers.rdn_to_dn(changes, 'uid', settings['LDAP_ACCOUNT_BASE']) return changes def __repr__(self): return f"user:{self['uid'][0]}" class BaseGroup(LdapObject): """ An abstract generic LDAP Group. """ @classmethod def get_fields(cls) -> Dict[str, tldap.fields.Field]: fields = { **helpers.get_fields_common(), **helpers.get_fields_group(), } return fields @classmethod def get_search_options(cls, database: Database) -> SearchOptions: settings = database.settings return SearchOptions( base_dn=settings['LDAP_GROUP_BASE'], object_class={'posixGroup'}, pk_field="cn", ) @classmethod def on_load(cls, python_data: LdapObject, _database: Database) -> LdapObject: return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: settings = database.settings changes = helpers.save_group(changes) changes = helpers.set_object_class(changes, ['top', 'posixGroup']) changes = helpers.rdn_to_dn(changes, 'cn', settings['LDAP_GROUP_BASE']) return changes @classmethod def add_member(cls, changes: Changeset, member: BaseAccount) -> Changeset: return helpers.add_group_member(changes, member) @classmethod def remove_member(cls, changes: Changeset, member: BaseAccount) -> Changeset: return helpers.remove_group_member(changes, member) def __repr__(self): return f"group:{self['cn'][0]}" class OpenldapAccount(BaseAccount): """ An OpenLDAP specific account with the pwdpolicy schema. """ @classmethod def get_fields(cls) -> Dict[str, tldap.fields.Field]: fields = { **BaseAccount.get_fields(), **helpers.get_fields_pwdpolicy(), } return fields @classmethod def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject: python_data = BaseAccount.on_load(python_data, database) python_data = helpers.load_pwdpolicy(python_data) return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: changes = BaseAccount.on_save(changes, database) changes = dhelpers.save_account(changes, OpenldapAccount, database) changes = helpers.save_pwdpolicy(changes) changes = helpers.set_object_class(changes, ['top', 'person', 'inetOrgPerson', 'organizationalPerson', 'shadowAccount', 'posixAccount', 'pwdPolicy']) return changes class OpenldapGroup(BaseGroup): """ An OpenLDAP specific group. """ @classmethod def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject: python_data = BaseGroup.on_load(python_data, database) python_data = helpers.load_group(python_data, OpenldapAccount) return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: changes = BaseGroup.on_save(changes, database) changes = dhelpers.save_group(changes, OpenldapGroup, database) return changes class Ds389Account(BaseAccount): """ A DS389 specific account with the password object schema. """ @classmethod def get_fields(cls) -> Dict[str, tldap.fields.Field]: fields = { **BaseAccount.get_fields(), **helpers.get_fields_password_object(), } return fields @classmethod def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject: python_data = BaseAccount.on_load(python_data, database) python_data = helpers.load_password_object(python_data) return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: changes = BaseAccount.on_save(changes, database) changes = dhelpers.save_account(changes, Ds389Account, database) changes = helpers.save_password_object(changes) changes = helpers.set_object_class(changes, ['top', 'person', 'inetOrgPerson', 'organizationalPerson', 'shadowAccount', 'posixAccount', 'passwordObject']) return changes class Ds389Group(BaseGroup): """ A DS389 specific group. """ @classmethod def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject: python_data = BaseGroup.on_load(python_data, database) python_data = helpers.load_group(python_data, Ds389Account) return python_data @classmethod def on_save(cls, changes: Changeset, database: Database) -> Changeset: changes = BaseGroup.on_save(changes, database) changes = dhelpers.save_group(changes, Ds389Group, database) return changes
brianmay/karaage
karaage/datastores/ldap_schemas.py
Python
gpl-3.0
7,236
[ "Brian" ]
17adc35aed242f95f229a2dbaaf76c5e58a74b08e2eabffb5270cc44bf0d007e
######################################################################## # $HeadURL$ ######################################################################## """ DIRAC FileCatalog Security Manager mix-in class """ __RCSID__ = "$Id$" import os from DIRAC import S_OK, S_ERROR from DIRAC.Core.Security.Properties import FC_MANAGEMENT class SecurityManagerBase: def __init__( self, database=None ): self.db = database def setDatabase( self, database ): self.db = database def getPathPermissions( self, paths, credDict ): """ Get path permissions according to the policy """ return S_ERROR('The getPathPermissions method must be implemented in the inheriting class') def hasAccess(self,opType,paths,credDict): # Check if admin access is granted first result = self.hasAdminAccess( credDict ) if not result['OK']: return result if result['Value']: # We are admins, allow everything permissions = {} for path in paths: permissions[path] = True return S_OK( {'Successful':permissions,'Failed':{}} ) successful = {} failed = {} if not opType.lower() in ['read','write','execute']: return S_ERROR("Operation type not known") if self.db.globalReadAccess and (opType.lower() == 'read'): for path in paths: successful[path] = True resDict = {'Successful':successful,'Failed':{}} return S_OK(resDict) result = self.getPathPermissions(paths,credDict) if not result['OK']: return result permissions = result['Value']['Successful'] for path,permDict in permissions.items(): if permDict[opType]: successful[path] = True else: successful[path] = False resDict = {'Successful':successful,'Failed':failed} return S_OK(resDict) def hasAdminAccess(self,credDict): if FC_MANAGEMENT in credDict['properties']: return S_OK(True) return S_OK(False) class NoSecurityManager(SecurityManagerBase): def getPathPermissions(self,paths,credDict): """ Get path permissions according to the policy """ permissions = {} for path in paths: permissions[path] = {'Read':True,'Write':True,'Execute':True} return S_OK( {'Successful':permissions,'Failed':{}} ) def hasAccess(self,opType,paths,credDict): successful = {} for path in paths: successful[path] = True resDict = {'Successful':successful,'Failed':{}} return S_OK(resDict) def hasAdminAccess(self,credDict): return S_OK(True) class DirectorySecurityManager(SecurityManagerBase): def getPathPermissions(self,paths,credDict): """ Get path permissions according to the policy """ toGet = dict(zip(paths,[ [path] for path in paths ])) permissions = {} failed = {} while toGet: res = self.db.dtree.getPathPermissions(toGet.keys(),credDict) if not res['OK']: return res for path,mode in res['Value']['Successful'].items(): for resolvedPath in toGet[path]: permissions[resolvedPath] = mode toGet.pop(path) for path,error in res['Value']['Failed'].items(): if error != 'No such file or directory': for resolvedPath in toGet[path]: failed[resolvedPath] = error toGet.pop(path) for path,resolvedPaths in toGet.items(): if path == '/': for resolvedPath in resolvedPaths: permissions[path] = {'Read':True,'Write':True,'Execute':True} if not toGet.has_key(os.path.dirname(path)): toGet[os.path.dirname(path)] = [] toGet[os.path.dirname(path)] += resolvedPaths toGet.pop(path) if self.db.globalReadAccess: for path in permissions: permissions[path]['Read'] = True return S_OK( {'Successful':permissions,'Failed':failed} ) class FullSecurityManager(SecurityManagerBase): def getPathPermissions(self,paths,credDict): """ Get path permissions according to the policy """ toGet = dict(zip(paths,[ [path] for path in paths ])) permissions = {} failed = {} res = self.db.fileManager.getPathPermissions(paths,credDict) if not res['OK']: return res for path,mode in res['Value']['Successful'].items(): for resolvedPath in toGet[path]: permissions[resolvedPath] = mode toGet.pop(path) for path,resolvedPaths in toGet.items(): if path == '/': for resolvedPath in resolvedPaths: permissions[path] = {'Read':True,'Write':True,'Execute':True} if not toGet.has_key(os.path.dirname(path)): toGet[os.path.dirname(path)] = [] toGet[os.path.dirname(path)] += resolvedPaths toGet.pop(path) while toGet: paths = toGet.keys() res = self.db.dtree.getPathPermissions(paths,credDict) if not res['OK']: return res for path,mode in res['Value']['Successful'].items(): for resolvedPath in toGet[path]: permissions[resolvedPath] = mode toGet.pop(path) for path,error in res['Value']['Failed'].items(): if error != 'No such file or directory': for resolvedPath in toGet[path]: failed[resolvedPath] = error toGet.pop(path) for path,resolvedPaths in toGet.items(): if path == '/': for resolvedPath in resolvedPaths: permissions[path] = {'Read':True,'Write':True,'Execute':True} if not toGet.has_key(os.path.dirname(path)): toGet[os.path.dirname(path)] = [] toGet[os.path.dirname(path)] += resolvedPaths toGet.pop(path) if self.db.globalReadAccess: for path in permissions: permissions[path]['Read'] = True return S_OK( {'Successful':permissions,'Failed':failed} )
Sbalbp/DIRAC
DataManagementSystem/DB/FileCatalogComponents/SecurityManager.py
Python
gpl-3.0
5,772
[ "DIRAC" ]
bc5c7fb9cf03efdd313e9effe1a6c585075ac6095ce0715b6dd06af0a7faa640
#!/usr/bin/env python3 ## This scripts automates the processes of calling the Reborn script for each model run and generates the new spawnfiles accordingly. import os import argparse import numpy as np #parser = argparse.ArgumentParser() #parser.add_argument('-n', '--file number', required=True, help='How many files') #parser.add_argument('-y', '--new year', required=True, help='How many files') n=55 y=5 x = 1 filelist = "./reborn_v1.0.py -i " #### Thi is requires if you are using split.py - nested loop #for x in range(n): # complete = filelist + "Part_" + str(x) + "_" + particles + ".nc -o Part_" + str(x) + "_" + str(y) + "year -s /gpfs/home/zgv09gsu/Final_Year/PAR-SPA_output_files/Python_Scripts/spawn_particles_Part_"+str(x) + " 1996-01-01 01:00:00" for i in range(1,53): complete = filelist + "Part_" + str(i) + ".nc -o spawn_particles_Part_" + str(i) + " -s /gpfs/home/zgv09gsu/Model_data/HPC_Admin_troubleshoot/new/Commander/PAR-SPA_run_files/spawn_particles_Part_1" + " 1996-01-01 01:00:00" #print(x, i) os.system(complete) os.system("rm -f spawn_particles_Part_" + str(i)) #os.system("cp spawn_particles_Part_* /gpfs/home/zgv09gsu/Model_data/HPC_Admin_troubleshoot/new/Commander/PAR-SPA_run_files/") os.system("mkdir Spawn_Dir") os.system("mv spawn_particles_Part_* Spawn_Dir/") print("\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/") print("Copied new spawn file to run directory and moved origional to Spawn_Dir/") print("Moved NetCDF data to: combined_nc/") os.system("mkdir All_nc_Data") os.system("mkdir All_nc_Data/Log_Files") os.system("mv Part_*.log All_nc_Data/Log_Files") os.system("mv Part_* All_nc_Data/")
abstractwisdom/Age-Tracer
Combine.py
Python
gpl-3.0
1,710
[ "NetCDF" ]
ad08d6dba2114f12c78540fda7b2aacef3d5a7829cf82140c6bb8e9f516b2228
# Copyright 2014-2018 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. from __future__ import print_function, division from pyscf.nao.m_libnao import libnao from ctypes import POINTER, c_double, c_int64 from numpy import require, zeros libnao.dens_libnao.argtypes = ( POINTER(c_double),# crds[i,0:3] POINTER(c_int64), # ncrds POINTER(c_double),# dens[i,0:] POINTER(c_int64)) # ndens def dens_libnao(crds, nspin): """ Compute the electronic density using library call """ assert crds.ndim==2 assert crds.shape[-1]==3 nc = crds.shape[0] crds_cp = require(crds, dtype=c_double, requirements='C') dens = require( zeros((nc, nspin)), dtype=c_double, requirements='CW') libnao.dens_libnao( crds_cp.ctypes.data_as(POINTER(c_double)), c_int64(nc), dens.ctypes.data_as(POINTER(c_double)), c_int64(nspin)) return dens
gkc1000/pyscf
pyscf/nao/m_dens_libnao.py
Python
apache-2.0
1,403
[ "PySCF" ]
b077865f9371e20fd42b7068fcb66d67940724d4ea2192d3ce7abf712bf7b832
from collections import defaultdict from rdkit import Chem from .. RINGParser import Read import yaml import os from .. Error import PatternMatchError from . Group import Group from . DataDir import get_data_dir # Scheme contains the group pattern information, and can assign groups # based on the smiles. class Scheme(object): pass class GroupAdditivityScheme(Scheme): def __init__(self, patterns=[], pretreatment_rules=[], remaps={}, other_descriptors=[], smiles_based_descriptors=[], smarts_based_descriptors=[], include=[]): """Load group-additivity scheme from file-system `path` or builtin. Parameters ---------- path : str Specify either the path to a file containing the data or a symbolic name of a builtin scheme to load (*e.g.* ``benson`` to load the standard Benson groups scheme.) Returns ------- scheme : :class:`GroupScheme` Group scheme containing the loaded data. Raises ------ pgradd.error.GroupSchemeError If `signature` is specified and does not match the signature of the loaded data. """ self.patterns = patterns self.pretreatment_rules = pretreatment_rules self.remaps = remaps self.other_descriptors = other_descriptors self.smiles_based_descriptors = smiles_based_descriptors self.smarts_based_descriptors = smarts_based_descriptors for scheme in include: if isinstance(scheme, GroupAdditivityScheme): scheme_object = scheme else: scheme_object = self.Load(scheme['include'][0]) self.patterns += scheme_object.patterns self.pretreatment_rules += scheme_object.pretreatment_rules self.remaps.update(scheme_object.remaps) self.other_descriptors += scheme_object.other_descriptors self.smiles_based_descriptors = scheme_object.\ smiles_based_descriptors self.smarts_based_descriptors = scheme_object.\ smarts_based_descriptors @classmethod def Load(cls, path): if os.sep not in path and '.' not in path and not os.path.exists(path): # [JTF] where's our data directory? base_path = os.path.join(get_data_dir(), path) # Load the scheme.yaml file in that directory: actual_path = os.path.join(base_path, 'scheme.yaml') else: actual_path = path abs_path = os.path.abspath(actual_path) fid = open(abs_path, 'r') scheme_data = yaml.load(fid, Loader=yaml.SafeLoader) fid.close() # change to molquery for i in range(0, len(scheme_data['patterns'])): scheme_data['patterns'][i]['connectivity'] = \ Read(scheme_data['patterns'][i]['connectivity']) patterns = scheme_data['patterns'] pretreatment_rules = [] remaps = {} other_descriptors = [] smiles_based_descriptors = [] smarts_based_descriptors = [] if 'pretreatment_rules' in scheme_data: pretreatment_rules = scheme_data['pretreatment_rules'] if 'remaps' in scheme_data: remaps = scheme_data['remaps'] if 'other_descriptors' in scheme_data: for i in range(0, len(scheme_data['other_descriptors'])): scheme_data['other_descriptors'][i]['connectivity'] = \ Read(scheme_data['other_descriptors'][i]['connectivity']) other_descriptors = scheme_data['other_descriptors'] if 'smiles_based_descriptors' in scheme_data: for i in range(0, len(scheme_data['smiles_based_descriptors'])): scheme_data['smiles_based_descriptors'][i]['smarts'] = \ Chem.MolFromSmarts(scheme_data['smiles_based_descriptors'] [i]['smarts']) smiles_based_descriptors = scheme_data['smiles_based_descriptors'] if 'smarts_based_descriptors' in scheme_data: for i in range(0, len(scheme_data['smarts_based_descriptors'])): scheme_data['smarts_based_descriptors'][i]['smarts'] = \ Chem.MolFromSmarts(scheme_data['smarts_based_descriptors'] [i]['smarts']) smarts_based_descriptors = scheme_data['smarts_based_descriptors'] return cls(patterns, pretreatment_rules, remaps, other_descriptors, smiles_based_descriptors, smarts_based_descriptors) def GetDescriptors(self, mol, debug=0): if isinstance(mol, Chem.Mol): mol = Chem.AddHs(mol) Chem.Kekulize(mol) elif isinstance(mol, str): clean_mol = Chem.MolFromSmiles(mol) # sanitize false is necessary to read adsorbed hydrogen species. # (e.g. [Pt][H]) mol.replace('{', '') mol.replace('}', '') # mol = Chem.MolFromSmiles(mol,sanitize=False) # Stereochemistry # get's erased. :/ mol = Chem.MolFromSmiles(mol) if mol is None: print('Smiles could not be loaded.') raise Exception sanitize_except_aromatization(mol) mol = Chem.AddHs(mol) Chem.Kekulize(mol) # pretreatment # TODO # reaction_query = Read(self.pretreatment_rules[0][0]) # mol = reaction_query.ModifyMolInPlace(mol). # Change unspecified bond to ZERO, or weak bonds. for bond in mol.GetBonds(): if bond.GetBondType().__str__() == 'UNSPECIFIED': bond.SetBondType(Chem.BondType.ZERO) # aromatize C6 ring for benson _aromatization_Benson(mol) # assign groups self._AssignCenterPattern(mol, debug) groups = self._AssignGroup(mol) descriptors = self._AssignDescriptor(mol, clean_mol) all_descriptors = groups.copy() all_descriptors.update(descriptors) return all_descriptors def _AssignCenterPattern(self, mol, debug=0): for pattern in self.patterns: matches = pattern['connectivity'].GetQueryMatches(mol) # only the first atom is the center atom matches = set([match[0] for match in matches]) for match in matches: atom = mol.GetAtomWithIdx(match) if atom.HasProp('Group_Center_Name'): s = 'Group center overwritten:' + \ atom.GetProp('Group_Center_Name') + ' to ' + \ pattern['center_name'] s += '(' + pattern['connectivity'].__str__() + ')' raise PatternMatchError(s, atom) else: atom.SetProp('Group_Center_Name', pattern['center_name']) atom.SetProp('Group_Periph_Name', pattern['periph_name']) if debug: s = '\nPattern: ' + pattern['center_name'] +\ ',' + pattern['periph_name'] s += '\nMatches: ' + str(matches) print(s) # exception spitted if any atoms have no groups assigned for atom in mol.GetAtoms(): if not atom.HasProp('Group_Center_Name'): s = '\nSub group not assigned:\n' + Chem.MolToSmiles(mol) +\ ' Atom symbol: ' + atom.GetSymbol() + \ ' #radicalE: ' + atom.GetNumRadicalElectrons().__str__() +\ '\nConnectivity:' for bond in atom.GetBonds(): if bond.GetBeginAtomIdx() == atom.GetIdx(): s += '\n' + bond.GetEndAtom().GetSymbol() + ' ' + \ bond.GetBondType().__str__() else: s += '\n' + bond.GetBeginAtom().GetSymbol() + ' ' + \ bond.GetBondType().__str__() s += '\n Occured ' raise PatternMatchError(s, atom) def _AssignGroup(self, mol): groups = defaultdict(int) for atom in mol.GetAtoms(): csg = atom.GetProp('Group_Center_Name') if csg != 'none': psgs = list() for neighboratom in atom.GetNeighbors(): psg = neighboratom.GetProp('Group_Periph_Name') if psg != 'none': psgs.append(psg) group = Group(self, csg, psgs) groups[group.name] += 1 atom.SetProp('Group_name', group.name) else: atom.SetProp('Group_name', 'none') # remapping if hasattr(self, 'remaps'): for atom in mol.GetAtoms(): if atom.GetProp('Group_name') in self.remaps: atom.SetProp('Group_name', self.remaps[atom.GetProp('Group_name')][0][1]) for group in list(groups.keys()): if group in self.remaps: n = groups.pop(group) for remap in self.remaps[group]: nn = n*remap[0] groups[remap[1]] += nn return groups def _AssignDescriptor(self, mol, clean_mol): descriptors = defaultdict(int) for descriptor in self.other_descriptors: matches = descriptor['connectivity'].GetQueryMatches(mol) matches = set([tuple(set(match)) for match in matches]) if matches: descriptors[descriptor['name']] += len(matches) for descriptor in self.smiles_based_descriptors: matches = clean_mol.GetSubstructMatches(descriptor['smiles'], useChirality=descriptor ['useChirality']) matches = set([tuple(set(match)) for match in matches]) if matches: descriptors[descriptor['name']] += len(matches) for descriptor in self.smarts_based_descriptors: matches = mol.GetSubstructMatches(descriptor['smarts'], useChirality=descriptor ['useChirality']) matches = set([tuple(set(match)) for match in matches]) if matches: descriptors[descriptor['name']] += len(matches) # remaps if hasattr(self, 'remaps'): for descriptor in list(descriptors.keys()): if descriptor in self.remaps: n = descriptors.pop(descriptor) for remap in self.remaps[descriptor]: nn = n*remap[0] descriptors[remap[1]] += nn return descriptors def sanitize_except_aromatization(mol): Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_ADJUSTHS) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_CLEANUP) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_CLEANUPCHIRALITY) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_FINDRADICALS) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_KEKULIZE) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_PROPERTIES) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_SETCONJUGATION) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_SETHYBRIDIZATION) Chem.SanitizeMol(mol, sanitizeOps=Chem.rdmolops.SanitizeFlags. SANITIZE_SYMMRINGS) def _aromatization_Benson(mol): # Benson's aromatic bond criteria: # C6 ring # No oxygen atoms # No triple bond (radical is okay) # Evenly spaced 3 double bond rings = Chem.GetSymmSSSR(mol) for i in range(0, len(rings)): # ring size check if len(rings[i]) != 6: continue # atom check if mol.GetAtomWithIdx(rings[i][0]).GetSymbol() != 'C': continue if mol.GetAtomWithIdx(rings[i][1]).GetSymbol() != 'C': continue if mol.GetAtomWithIdx(rings[i][2]).GetSymbol() != 'C': continue if mol.GetAtomWithIdx(rings[i][3]).GetSymbol() != 'C': continue if mol.GetAtomWithIdx(rings[i][4]).GetSymbol() != 'C': continue if mol.GetAtomWithIdx(rings[i][5]).GetSymbol() != 'C': continue # bond check if mol.GetBondBetweenAtoms(rings[i][0], rings[i][1]).\ GetBondType().__str__() ==\ 'SINGLE': if mol.GetBondBetweenAtoms(rings[i][1], rings[i][2]).\ GetBondType().__str__() ==\ 'DOUBLE': if mol.GetBondBetweenAtoms(rings[i][2], rings[i][3]).\ GetBondType().__str__() ==\ 'SINGLE': if mol.GetBondBetweenAtoms(rings[i][3], rings[i][4]).\ GetBondType().__str__() ==\ 'DOUBLE': if mol.GetBondBetweenAtoms(rings[i][4], rings[i][5]).\ GetBondType().__str__() ==\ 'SINGLE': if mol.GetBondBetweenAtoms(rings[i][5], rings[i][0]).\ GetBondType().__str__() ==\ 'DOUBLE': pass else: continue else: continue else: continue else: continue else: continue elif mol.GetBondBetweenAtoms(rings[i][0], rings[i][1]).\ GetBondType().__str__() ==\ 'DOUBLE': if mol.GetBondBetweenAtoms(rings[i][1], rings[i][2]).\ GetBondType().__str__() ==\ 'SINGLE': if mol.GetBondBetweenAtoms(rings[i][2], rings[i][3]).\ GetBondType().__str__() ==\ 'DOUBLE': if mol.GetBondBetweenAtoms(rings[i][3], rings[i][4]).\ GetBondType().__str__() ==\ 'SINGLE': if mol.GetBondBetweenAtoms(rings[i][4], rings[i][5]).\ GetBondType().__str__() ==\ 'DOUBLE': if mol.GetBondBetweenAtoms(rings[i][5], rings[i][0]).\ GetBondType().__str__() ==\ 'SINGLE': pass else: continue else: continue else: continue else: continue else: continue else: continue # if it survived all these continue, then this molecule is aromatic mol.GetAtomWithIdx(rings[i][0]).SetIsAromatic(True) mol.GetAtomWithIdx(rings[i][1]).SetIsAromatic(True) mol.GetAtomWithIdx(rings[i][2]).SetIsAromatic(True) mol.GetAtomWithIdx(rings[i][3]).SetIsAromatic(True) mol.GetAtomWithIdx(rings[i][4]).SetIsAromatic(True) mol.GetAtomWithIdx(rings[i][5]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][0], rings[i][1]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][1], rings[i][2]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][2], rings[i][3]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][3], rings[i][4]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][4], rings[i][5]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][5], rings[i][0]).SetIsAromatic(True) mol.GetBondBetweenAtoms(rings[i][0], rings[i][1]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][1], rings[i][2]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][2], rings[i][3]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][3], rings[i][4]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][4], rings[i][5]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][5], rings[i][0]).SetIsConjugated(True) mol.GetBondBetweenAtoms(rings[i][0], rings[i][1]).\ SetBondType(Chem.rdchem.BondType.AROMATIC) mol.GetBondBetweenAtoms(rings[i][1], rings[i][2]).\ SetBondType(Chem.rdchem.BondType.AROMATIC) mol.GetBondBetweenAtoms(rings[i][2], rings[i][3]).\ SetBondType(Chem.rdchem.BondType.AROMATIC) mol.GetBondBetweenAtoms(rings[i][3], rings[i][4]).\ SetBondType(Chem.rdchem.BondType.AROMATIC) mol.GetBondBetweenAtoms(rings[i][4], rings[i][5]).\ SetBondType(Chem.rdchem.BondType.AROMATIC) mol.GetBondBetweenAtoms(rings[i][5], rings[i][0]).\ SetBondType(Chem.rdchem.BondType.AROMATIC)
VlachosGroup/VlachosGroupAdditivity
pgradd/GroupAdd/Scheme.py
Python
mit
18,324
[ "RDKit" ]
064f3990030c64dacbb0121f2c52be5ef7f2908daf346f3d10c509a016a3f61c
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # --------------------------------------------------------------------------- # # Copyright (c) 2008-2013 Raoul Snyman # # Portions copyright (c) 2008-2013 Tim Bentley, Gerald Britton, Jonathan # # Corwin, Samuel Findlay, Michael Gorven, Scott Guerrieri, Matthias Hub, # # Meinert Jordan, Armin Köhler, Erik Lundin, Edwin Lunando, Brian T. Meyer. # # Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias Põldaru, # # Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, # # Maikel Stuivenberg, Martin Thompson, Jon Tibble, Dave Warnock, # # Frode Woldsund, Martin Zibricky, Patrick Zimmermann # # --------------------------------------------------------------------------- # # 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; version 2 of the License. # # # # 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., 59 # # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### """ The :mod:`songproimport` module provides the functionality for importing SongPro songs into the OpenLP database. """ import re from openlp.plugins.songs.lib import strip_rtf from openlp.plugins.songs.lib.songimport import SongImport class SongProImport(SongImport): """ The :class:`SongProImport` class provides the ability to import song files from SongPro export files. **SongPro Song File Format:** SongPro has the option to export under its File menu This produces files containing single or multiple songs The file is text with lines tagged with # followed by an identifier. This is documented here: http://creationsoftware.com/ImportIdentifiers.php An example here: http://creationsoftware.com/ExampleImportingManySongs.txt #A - next line is the Song Author #B - the lines following until next tagged line are the "Bridge" words (can be in rtf or plain text) which we map as B1 #C - the lines following until next tagged line are the chorus words (can be in rtf or plain text) which we map as C1 #D - the lines following until next tagged line are the "Ending" words (can be in rtf or plain text) which we map as E1 #E - this song ends here, so we process the song - and start again at the next line #G - next line is the Group #M - next line is the Song Number #N - next line are Notes #R - next line is the SongCopyright #O - next line is the Verse Sequence #T - next line is the Song Title #1 - #7 the lines following until next tagged line are the verse x words (can be in rtf or plain text) """ def __init__(self, manager, **kwargs): """ Initialise the SongPro importer. """ SongImport.__init__(self, manager, **kwargs) def doImport(self): """ Receive a single file or a list of files to import. """ self.encoding = None with open(self.import_source, 'r') as songs_file: self.import_wizard.progress_bar.setMaximum(0) tag = '' text = '' for file_line in songs_file: if self.stop_import_flag: break file_line = str(file_line, 'cp1252') file_text = file_line.rstrip() if file_text and file_text[0] == '#': self.processSection(tag, text.rstrip()) tag = file_text[1:] text = '' else: text += file_line def processSection(self, tag, text): """ Process a section of the song, i.e. title, verse etc. """ if tag == 'T': self.setDefaults() if text: self.title = text return elif tag == 'E': self.finish() return if 'rtf1' in text: result = strip_rtf(text, self.encoding) if result is None: return text, self.encoding = result text = text.rstrip() if not text: return if tag == 'A': self.parse_author(text) elif tag in ['B', 'C']: self.addVerse(text, tag) elif tag == 'D': self.addVerse(text, 'E') elif tag == 'G': self.topics.append(text) elif tag == 'M': matches = re.findall(r'\d+', text) if matches: self.songNumber = matches[-1] self.songBookName = text[:text.rfind(self.songNumber)] elif tag == 'N': self.comments = text elif tag == 'O': for char in text: if char == 'C': self.verseOrderList.append('C1') elif char == 'B': self.verseOrderList.append('B1') elif char == 'D': self.verseOrderList.append('E1') elif '1' <= char <= '7': self.verseOrderList.append('V' + char) elif tag == 'R': self.addCopyright(text) elif '1' <= tag <= '7': self.addVerse(text, 'V' + tag[1:])
marmyshev/item_title
openlp/plugins/songs/lib/songproimport.py
Python
gpl-2.0
6,318
[ "Brian" ]
d71f65d54e366998a60335be58e11bce247f459f5731e42faa84d8e32d9abc19
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Implements the graph generation for computation of gradients.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import contextlib import warnings import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import function as framework_function from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.framework.func_graph import FuncGraph from tensorflow.python.ops import array_grad # pylint: disable=unused-import from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops # pylint: disable=unused-import from tensorflow.python.ops import control_flow_grad # pylint: disable=unused-import from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import functional_ops from tensorflow.python.ops import image_grad # pylint: disable=unused-import from tensorflow.python.ops import linalg_grad # pylint: disable=unused-import from tensorflow.python.ops import linalg_ops # pylint: disable=unused-import from tensorflow.python.ops import logging_ops # pylint: disable=unused-import from tensorflow.python.ops import manip_grad # pylint: disable=unused-import from tensorflow.python.ops import math_grad # pylint: disable=unused-import from tensorflow.python.ops import math_ops from tensorflow.python.ops import optional_grad # pylint: disable=unused-import from tensorflow.python.ops import random_grad # pylint: disable=unused-import from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import compat from tensorflow.python.util.tf_export import tf_export # This is to avoid a circular dependency (eager.function depends on # gradients_impl). This is set in eager/function.py. _function = None # Warn the user if we convert a sparse representation to dense with at # least this number of elements. _LARGE_SPARSE_NUM_ELEMENTS = 100000000 def _IndexedSlicesToTensor(value, dtype=None, name=None, as_ref=False): """Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype. """ _ = as_ref if dtype and not dtype.is_compatible_with(value.dtype): raise ValueError( "Tensor conversion requested dtype %s for IndexedSlices with dtype %s" % (dtype.name, value.dtype.name)) if value.dense_shape is None: raise ValueError( "Tensor conversion requested for IndexedSlices without dense_shape: %s" % str(value)) # TODO(mrry): Consider adding static shape information to # IndexedSlices, to avoid using numpy here. if not context.executing_eagerly(): dense_shape_value = tensor_util.constant_value(value.dense_shape) if dense_shape_value is not None: num_elements = np.prod(dense_shape_value) if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor with %d " "elements. This may consume a large amount of memory." % num_elements) else: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " "This may consume a large amount of memory.") return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name) ops.register_tensor_conversion_function(ops.IndexedSlices, _IndexedSlicesToTensor) def _MarkReachedOps(from_ops, reached_ops, func_graphs): """Mark all ops reached from "from_ops". Args: from_ops: list of Operations. reached_ops: set of Operations. func_graphs: list of FuncGraphs. This method will traverse through these functions if they capture from_ops or any reachable ops. """ queue = collections.deque() queue.extend(from_ops) while queue: op = queue.popleft() if op not in reached_ops: reached_ops.add(op) for output in op.outputs: if _IsBackpropagatable(output): queue.extend(_Consumers(output, func_graphs)) def _PendingCount(to_ops, from_ops, colocate_gradients_with_ops, func_graphs, xs): """Initialize the pending count for ops between two lists of Operations. 'pending_count[op]' indicates the number of backprop inputs to this operation. Args: to_ops: list of Operations. from_ops: list of Operations. colocate_gradients_with_ops: Python bool. See docstring of gradients(). func_graphs: list of FuncGraphs. This method will traverse through these functions if they capture from_ops or any reachable ops. This is useful if to_ops occur in a function and from_ops are in an outer function or graph. xs: list of Tensors. Returns: A tuple containing: (1) the subset of to_ops reachable from from_ops by a path of zero or more backpropagatable tensors, (2) a mapping from operation to the number of backprop inputs to that op, and (3) a ControlFlowState object which is not None if the ops between from_ops and to_ops contain control flow loops. """ # Mark reachable ops from from_ops. reached_ops = set() _MarkReachedOps(from_ops, reached_ops, func_graphs) # X in reached_ops iff X is reachable from from_ops by a path of zero or more # backpropagatable tensors. reachable_to_ops = set(op for op in to_ops if op in reached_ops) # Mark between ops. between_ops = set() between_op_list = [] queue = collections.deque() queue.extend(to_ops) while queue: op = queue.popleft() # We are interested in this op. if op in reached_ops: between_ops.add(op) between_op_list.append(op) # Clear the boolean so we won't add the inputs again. reached_ops.remove(op) for inp in _NonEagerInputs(op, xs): queue.append(inp.op) # X in between_ops iff X is on a path of zero or more backpropagatable tensors # between from_ops and to_ops # 'loop_state' is None if there are no while loops. loop_state = control_flow_ops.MaybeCreateControlFlowState( between_op_list, between_ops, colocate_gradients_with_ops) # Initialize pending count for between ops. pending_count = collections.defaultdict(int) for op in between_op_list: for x in _NonEagerInputs(op, xs): if x.op in between_ops: pending_count[x.op] += 1 return reachable_to_ops, pending_count, loop_state def _AsList(x): return x if isinstance(x, (list, tuple)) else [x] def _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops, gradient_uid="__unsupported__"): """Fill in default values for grad_ys. Args: grad_ys: List of gradients, can contain None. ys: List of tensors. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gradient_uid: A unique identifier within the graph indicating which invocation of gradients is being executed. Used to cluster ops for compilation. Returns: A list of gradients to use, without None. Raises: ValueError: If sizes of gradients and inputs don't match TypeError: If type of any gradient is not valid for its input. """ if len(grad_ys) != len(ys): raise ValueError("Passed %d grad_ys for %d ys" % (len(grad_ys), len(ys))) grad_ys = ops.convert_n_to_tensor_or_indexed_slices(grad_ys, name="grad_y") new_grad_ys = [] for i in xrange(len(grad_ys)): grad_y = grad_ys[i] y = ys[i] with _maybe_colocate_with(y.op, gradient_uid, colocate_gradients_with_ops): if grad_y is None: if y.dtype.is_complex: raise TypeError( "Gradients of complex tensors must set grad_ys (y.dtype = %r)" % y.dtype) new_grad_ys.append( array_ops.fill( array_ops.shape(y), constant_op.constant(1, dtype=y.dtype, name="grad_ys_%d" % i))) continue if y.dtype.is_floating or y.dtype.is_integer: if not grad_y.dtype.is_floating and not grad_y.dtype.is_integer: raise TypeError( "Gradient type %s generated for real or " "integer-valued tensor %s with type %s must be " "real or integer" % (dtypes.as_dtype(grad_y.dtype).name, y, dtypes.as_dtype(y.dtype).name)) elif y.dtype.is_complex: if not grad_y.dtype.is_complex: raise TypeError( "Gradient type %s generated for complex-valued " "tensor %s with type %s must be real" % (dtypes.as_dtype( grad_y.dtype).name, y, dtypes.as_dtype(y.dtype).name)) elif y.dtype == dtypes.variant: if grad_y.dtype != dtypes.variant: raise TypeError( "Gradient type %s generated for variant " "tensor %s with type %s must be variant" % (dtypes.as_dtype( grad_y.dtype).name, y, dtypes.as_dtype(y.dtype).name)) elif y.dtype == dtypes.resource: # We assume y is the handle of a ResourceVariable. The gradient of a # ResourceVariable should be a numeric value, not another resource. if grad_y.dtype == dtypes.resource: raise TypeError("Input gradient %s for resource tensor %s should not " "be a resource" % (grad_y, y)) else: raise TypeError( "Tensor %s with type %s must be numeric " "to obtain a default gradient" % (y, dtypes.as_dtype(y.dtype).name)) # Create a grad_y tensor in the name scope of the gradient. # Required for TensorArrays to identify which gradient call a # grad_y value is coming from. if isinstance(grad_y, ops.IndexedSlices): new_grad_ys.append( ops.IndexedSlices( indices=(array_ops.identity( grad_y.indices, name="grad_ys_%d_indices" % i) if isinstance(grad_y.indices, ops.Tensor) else grad_y.indices), values=(array_ops.identity( grad_y.values, name="grad_ys_%d_values" % i) if isinstance( grad_y.values, ops.Tensor) else grad_y.values), dense_shape=(array_ops.identity( grad_y.dense_shape, name="grad_ys_%d_shape" % i) if isinstance(grad_y.dense_shape, ops.Tensor) else grad_y.dense_shape))) else: new_grad_ys.append(array_ops.identity(grad_y, name="grad_ys_%d" % i)) return new_grad_ys def IsTrainable(tensor_or_dtype): if isinstance(tensor_or_dtype, ops.Tensor): dtype = tensor_or_dtype.dtype else: dtype = tensor_or_dtype dtype = dtypes.as_dtype(dtype) return dtype.base_dtype in (dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128, dtypes.resource, dtypes.variant) def _IsBackpropagatable(tensor): if IsTrainable(tensor): return True dtype = dtypes.as_dtype(tensor.dtype) return dtype.base_dtype == dtypes.bfloat16 def _VerifyGeneratedGradients(grads, op): """Verify that gradients are valid in number and type. Args: grads: List of generated gradients. op: Operation for which the gradients where generated. Raises: ValueError: if sizes of gradients and inputs don't match. TypeError: if type of any gradient is not valid for its input. """ # While ops have inputs added to them during the gradient computation, so we # skip the below check. See while_v2 for details. if op.type == "While": return if len(grads) != len(op.inputs): raise ValueError("Num gradients %d generated for op %s do not match num " "inputs %d" % (len(grads), op.node_def, len(op.inputs))) def _StopOps(from_ops, stop_gradient_ops, pending_count, xs): """The set of ops that terminate the gradient computation. This computes the frontier of the forward graph *before* which backprop should stop. Operations in the returned set will not be differentiated. This set is defined as the subset of `from_ops` containing ops that have no predecessor in `from_ops`. `pending_count` is the result of `_PendingCount(xs, from_ops)`. An 'op' has predecessors in `from_ops` iff pending_count[op] > 0. In addition, none of `stop_gradient_ops` will be differentiated. Args: from_ops: list of Operations. stop_gradient_ops: list of Operations never to backprop through. pending_count: mapping from operation to number of backprop inputs. xs: list of Tensors. Returns: The set of operations. """ stop_ops = set() for op in from_ops: is_stop_op = True for inp in _NonEagerInputs(op, xs): if pending_count[inp.op] > 0: is_stop_op = False break if is_stop_op: stop_ops.add(op) stop_ops.update(op for op in stop_gradient_ops) return stop_ops @contextlib.contextmanager def _maybe_colocate_with(op, gradient_uid, colocate_gradients_with_ops): # pylint: disable=invalid-name """Context to colocate with `op` if `colocate_gradients_with_ops`.""" if colocate_gradients_with_ops: with ops._colocate_with_for_gradient(op, gradient_uid): # pylint: disable=protected-access yield else: yield def _IsPartitionedCall(op): return op.type == "PartitionedCall" or op.type == "StatefulPartitionedCall" def _SymGrad(op, out_grads): """Backprop through a function call node op given its outputs' gradients.""" f_in = [x for x in op.inputs] + out_grads f_types = [x.dtype for x in op.inputs] f = attr_value_pb2.NameAttrList() if _IsPartitionedCall(op): f.name = op.get_attr("f").name else: f.name = op.type for k in op.node_def.attr: f.attr[k].CopyFrom(op.node_def.attr[k]) # TODO(apassos) use a better dtype here in_grads = functional_ops.symbolic_gradient( input=f_in, Tout=[x if x != dtypes.resource else dtypes.float32 for x in f_types], f=f) return in_grads def _MaybeCompile(scope, op, func, grad_fn): """Compile the calculation in grad_fn if op was marked as compiled.""" scope = scope.rstrip("/").replace("/", "_") if func is not None: xla_compile = func.definition.attr["_XlaCompile"].b xla_separate_compiled_gradients = func.definition.attr[ "_XlaSeparateCompiledGradients"].b xla_scope = func.definition.attr["_XlaScope"].s.decode() else: try: xla_compile = op.get_attr("_XlaCompile") xla_separate_compiled_gradients = op.get_attr( "_XlaSeparateCompiledGradients") xla_scope = op.get_attr("_XlaScope").decode() except ValueError: return grad_fn() # Exit early if not xla_compile: return grad_fn() # Exit early # If the gradients are supposed to be compiled separately, we give them a # _XlaScope name that is based on the name_scope of the gradients. Otherwise # they just inherit the existing _XlaScope name, which lets them be merged # together with the non-gradient computation. if xla_separate_compiled_gradients: xla_grad_scope = "%s_grad_%s" % (xla_scope, scope) else: xla_grad_scope = xla_scope attrs = { "_XlaCompile": attr_value_pb2.AttrValue(b=xla_compile), "_XlaScope": attr_value_pb2.AttrValue(s=xla_grad_scope.encode()) } with ops.get_default_graph()._attr_scope(attrs): # pylint: disable=protected-access return grad_fn() def _RaiseNoGradWrtInitialLoopValError(op, from_ops, xs): """Raises an error if we backprop through a loop var.""" # Find the nearest 'to_op' reachable from 'op' to provide a more helpful error # message. target_op = None queue = collections.deque([op]) visited = set() while queue: curr_op = queue.popleft() if curr_op in visited: continue visited.add(curr_op) if curr_op in from_ops: target_op = curr_op break queue.extend(t.op for t in _NonEagerInputs(curr_op, xs)) assert target_op raise ValueError( "Cannot compute gradient inside while loop with respect to op '%s'. " "We do not support taking the gradient wrt or through the initial value " "of a loop variable. Gradients can be computed through loop invariants " "or wrt the input parameters to the loop body." % target_op.name) def _IsFunction(graph): return (isinstance(graph, FuncGraph) or isinstance(graph, framework_function._FuncGraph)) # pylint: disable=protected-access def _Captures(func_graph): if isinstance(func_graph, FuncGraph): return func_graph.captures else: assert isinstance(func_graph, framework_function._FuncGraph) # pylint: disable=protected-access return func_graph._captured # pylint: disable=protected-access def _MaybeCaptured(t): """If t is a captured value placeholder, returns the original captured value. Args: t: Tensor Returns: A tensor, potentially from a different Graph/FuncGraph. """ # pylint: disable=protected-access if (not isinstance(t, ops.EagerTensor) and _IsFunction(t.op.graph) and t.op.type == "Placeholder"): for input_t, placeholder_t in _Captures(t.op.graph).items(): if t == placeholder_t: return _MaybeCaptured(input_t) # pylint: enable=protected-access return t # TODO(skyewm): plumbing xs through everywhere is ugly, consider making # _GradientsHelper a class with xs as a member variable. def _NonEagerInputs(op, xs): """Returns the inputs of op, crossing closure boundaries where necessary. Does not return any captured EagerTensors, i.e., the number of tensors returned may be less than than the actual number of inputs. Args: op: Operation xs: list of Tensors we are differentiating w.r.t. Returns: A list of tensors. The tensors may be from multiple Graph/FuncGraphs if op is in a FuncGraph and has captured inputs. """ if _IsFunction(op.graph): # pylint: disable=protected-access inputs = [] for t in op.inputs: # If we're differentiating w.r.t. `t`, do not attempt to traverse through # it to a captured value. The algorithm needs to "see" `t` in this case, # even if it's a function input for a captured value, whereas usually we'd # like to traverse through these closures as if the captured value was the # direct input to op. if t not in xs: t = _MaybeCaptured(t) # Skip captured eager inputs. if isinstance(t, ops.EagerTensor): continue inputs.append(t) return inputs else: return op.inputs def _Consumers(t, func_graphs): """Returns the consumers of t, crossing closure boundaries where necessary. Args: t: Tensor func_graphs: a list of FuncGraphs that may have captured t. Returns: A list of tensors. The tensors will be from the current graph and/or func_graphs. """ consumers = t.consumers() for func in func_graphs: for input_t, placeholder in _Captures(func).items(): if input_t == t: consumers.extend(_Consumers(placeholder, func_graphs)) return consumers @tf_export(v1=["gradients"]) def gradients(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradients=None, unconnected_gradients=UnconnectedGradients.NONE): """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). `stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example: ```python a = tf.constant(0.) b = 2 * a g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) ``` Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to: ```python a = tf.stop_gradient(tf.constant(0.)) b = tf.stop_gradient(2 * a) g = tf.gradients(a + b, [a, b]) ``` `stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to `tf.stop_gradient` which is used during graph construction. When the two approaches are combined, backpropagation stops at both `tf.stop_gradient` nodes and nodes in `stop_gradients`, whichever is encountered first. All integer tensors are considered constant with respect to all `xs`, as if they were included in `stop_gradients`. `unconnected_gradients` determines the value returned for each x in xs if it is unconnected in the graph to ys. By default this is None to safeguard against errors. MAthematically these gradients are zero which can be requested using the `'zero'` option. `tf.UnconnectedGradients` provides the following options and behaviors: ```python a = tf.ones([1, 2]) b = tf.ones([3, 1]) g1 = tf.gradients([b], [a], unnconnected_gradients='none') sess.run(g1) # [None] g2 = tf.gradients([b], [a], unconnected_gradients='zero') sess.run(g2) # [array([[0., 0.]], dtype=float32)] ``` Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate through. unconnected_gradients: Optional. Specifies the gradient value returned when the given input tensors are unconnected. Accepted values are constants defined in the class `tf.UnconnectedGradients` and the default value is `none`. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. RuntimeError: if called in Eager mode. """ # Creating the gradient graph for control flow mutates Operations. # _mutation_lock ensures a Session.run call cannot occur between creating and # mutating new ops. with ops.get_default_graph()._mutation_lock(): # pylint: disable=protected-access return _GradientsHelper(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_method, stop_gradients, unconnected_gradients) @tf_export("gradients", v1=[]) def gradients_v2(ys, # pylint: disable=invalid-name xs, grad_ys=None, name="gradients", gate_gradients=False, aggregation_method=None, stop_gradients=None, unconnected_gradients=UnconnectedGradients.NONE): """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). `stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example: ```python a = tf.constant(0.) b = 2 * a g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) ``` Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to: ```python a = tf.stop_gradient(tf.constant(0.)) b = tf.stop_gradient(2 * a) g = tf.gradients(a + b, [a, b]) ``` `stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to `tf.stop_gradient` which is used during graph construction. When the two approaches are combined, backpropagation stops at both `tf.stop_gradient` nodes and nodes in `stop_gradients`, whichever is encountered first. All integer tensors are considered constant with respect to all `xs`, as if they were included in `stop_gradients`. `unconnected_gradients` determines the value returned for each x in xs if it is unconnected in the graph to ys. By default this is None to safeguard against errors. MAthematically these gradients are zero which can be requested using the `'zero'` option. `tf.UnconnectedGradients` provides the following options and behaviors: ```python a = tf.ones([1, 2]) b = tf.ones([3, 1]) g1 = tf.gradients([b], [a], unnconnected_gradients='none') sess.run(g1) # [None] g2 = tf.gradients([b], [a], unconnected_gradients='zero') sess.run(g2) # [array([[0., 0.]], dtype=float32)] ``` Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate through. unconnected_gradients: Optional. Specifies the gradient value returned when the given input tensors are unconnected. Accepted values are constants defined in the class `tf.UnconnectedGradients` and the default value is `none`. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. RuntimeError: if called in Eager mode. """ # Creating the gradient graph for control flow mutates Operations. # _mutation_lock ensures a Session.run call cannot occur between creating and # mutating new ops. with ops.get_default_graph()._mutation_lock(): # pylint: disable=protected-access return _GradientsHelper(ys, xs, grad_ys, name, True, gate_gradients, aggregation_method, stop_gradients, unconnected_gradients) def _GradientsHelper(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradients=None, unconnected_gradients=UnconnectedGradients.NONE, src_graph=None): """Implementation of gradients().""" if context.executing_eagerly(): raise RuntimeError("tf.gradients is not supported when eager execution " "is enabled. Use tf.GradientTape instead.") if src_graph is None: src_graph = ops.get_default_graph() try: unconnected_gradients = UnconnectedGradients(unconnected_gradients) except ValueError: raise ValueError( "Unknown value for unconnected_gradients: %r" % unconnected_gradients) # If src_graph is a _FuncGraph (i.e. a function body), gather it and all # ancestor graphs. This is necessary for correctly handling captured values. func_graphs = [] curr_graph = src_graph while _IsFunction(curr_graph): func_graphs.append(curr_graph) if isinstance(curr_graph, FuncGraph): curr_graph = curr_graph.outer_graph else: assert isinstance(curr_graph, framework_function._FuncGraph) # pylint: disable=protected-access curr_graph = curr_graph._outer_graph # pylint: disable=protected-access ys = _AsList(ys) xs = _AsList(xs) stop_gradients = [] if stop_gradients is None else _AsList(stop_gradients) if grad_ys is None: grad_ys = [None] * len(ys) else: grad_ys = _AsList(grad_ys) with ops.name_scope( name, "gradients", list(ys) + list(xs) + list(stop_gradients) + list(grad_ys)) as grad_scope: # Get a uid for this call to gradients that can be used to help # cluster ops for compilation. gradient_uid = ops.get_default_graph().unique_name("uid") ys = ops.convert_n_to_tensor_or_indexed_slices(ys, name="y") xs = [ x.handle if resource_variable_ops.is_resource_variable(x) else x for x in xs ] xs = ops.internal_convert_n_to_tensor_or_indexed_slices( xs, name="x", as_ref=True) grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops, gradient_uid) # The approach we take here is as follows: Create a list of all ops in the # subgraph between the ys and xs. Visit these ops in reverse order of ids # to ensure that when we visit an op the gradients w.r.t its outputs have # been collected. Then aggregate these gradients if needed, call the op's # gradient function, and add the generated gradients to the gradients for # its input. # Initialize the pending count for ops in the connected subgraph from ys # to the xs. to_ops = [t.op for t in ys] from_ops = [t.op for t in xs] stop_gradient_ops = [t.op for t in stop_gradients] reachable_to_ops, pending_count, loop_state = _PendingCount( to_ops, from_ops, colocate_gradients_with_ops, func_graphs, xs) # Iterate over the collected ops. # # grads: op => list of gradients received on each output endpoint of the # op. The gradients for each endpoint are initially collected as a list. # When it is time to call the op's gradient function, for each endpoint we # aggregate the list of received gradients into a Add() Operation if there # is more than one. grads = {} # Add the initial gradients for the ys. for y, grad_y in zip(ys, grad_ys): _SetGrad(grads, y, grad_y) # Initialize queue with to_ops. queue = collections.deque() # Add the ops in 'to_ops' into the queue. to_ops_set = set() for op in to_ops: # 'ready' handles the case where one output gradient relies on # another output's gradient. ready = (pending_count[op] == 0) if ready and op not in to_ops_set and op in reachable_to_ops: to_ops_set.add(op) queue.append(op) if loop_state: loop_exits = loop_state.ProcessUnusedLoopExits(pending_count, to_ops_set) for y in loop_exits: if IsTrainable(y): _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) stop_ops = _StopOps(from_ops, stop_gradient_ops, pending_count, xs) while queue: # generate gradient subgraph for op. op = queue.popleft() with _maybe_colocate_with(op, gradient_uid, colocate_gradients_with_ops): if loop_state: loop_state.EnterGradWhileContext(op, before=True) out_grads = _AggregatedGrads(grads, op, gradient_uid, loop_state, aggregation_method) if loop_state: loop_state.ExitGradWhileContext(op, before=True) grad_fn = None func_call = None is_partitioned_call = _IsPartitionedCall(op) # pylint: disable=protected-access is_func_call = ( src_graph._is_function(op.type) or is_partitioned_call) # pylint: enable=protected-access has_out_grads = any(isinstance(g, ops.Tensor) or g for g in out_grads) if has_out_grads and (op not in stop_ops): try: grad_fn = ops.get_gradient_function(op) except LookupError: if is_func_call: if is_partitioned_call: func_call = src_graph._get_function( # pylint: disable=protected-access compat.as_bytes(op.get_attr("f").name)) else: func_call = src_graph._get_function(op.type) # pylint: disable=protected-access # Note that __defun is not set if the graph is # imported. If it's set, we prefer to access the original # defun. func_call = getattr(op, "__defun", func_call) grad_fn = func_call.python_grad_func else: raise LookupError( "No gradient defined for operation '%s' (op type: %s)" % (op.name, op.type)) if loop_state: loop_state.EnterGradWhileContext(op, before=False) # NOTE(skyewm): We don't support computing gradients wrt a loop variable # unless it's within the context of a single iteration (i.e. the # gradient is wrt to the loop parameter in the body function, not wrt or # through the initial value). This means if we're in a while loop # context, we should never see a switch node from this context. # pylint: disable=protected-access if (control_flow_util.IsSwitch(op) and op._control_flow_context is not None and op._control_flow_context.IsWhileContext() and op._control_flow_context == ops.get_default_graph()._get_control_flow_context()): _RaiseNoGradWrtInitialLoopValError(op, from_ops, xs) # pylint: enable=protected-access if (grad_fn or is_func_call) and has_out_grads: # NOTE: If _AggregatedGrads didn't compute a value for the i'th # output, it means that the cost does not depend on output[i], # therefore dC/doutput[i] is 0. for i, out_grad in enumerate(out_grads): if (not isinstance(out_grad, ops.Tensor) and not out_grad) and ( (not grad_fn and is_func_call) or IsTrainable(op.outputs[i])): # Only trainable outputs or outputs for a function call that # will use SymbolicGradient get a zero gradient. Gradient # functions should ignore the gradient for other outputs. # TODO(apassos) gradients of resource handles might be an # issue here because of zeros. if loop_state: out_grads[i] = loop_state.ZerosLike(op, i) else: out_grads[i] = control_flow_ops.ZerosLikeOutsideLoop(op, i) with ops.name_scope(op.name + "_grad"): # pylint: disable=protected-access with src_graph._original_op(op): # pylint: enable=protected-access if grad_fn: # If grad_fn was found, do not use SymbolicGradient even for # functions. in_grads = _MaybeCompile(grad_scope, op, func_call, lambda: grad_fn(op, *out_grads)) else: # For function call ops, we add a 'SymbolicGradient' # node to the graph to compute gradients. in_grads = _MaybeCompile(grad_scope, op, func_call, lambda: _SymGrad(op, out_grads)) in_grads = _AsList(in_grads) _VerifyGeneratedGradients(in_grads, op) if gate_gradients and len([x for x in in_grads if x is not None]) > 1: with ops.device(None): with ops._colocate_with_for_gradient( # pylint: disable=protected-access None, gradient_uid, ignore_existing=True): in_grads = control_flow_ops.tuple(in_grads) _LogOpGradients(op, out_grads, in_grads) else: # If no grad_fn is defined or none of out_grads is available, # just propagate a list of None backwards. in_grads = [None] * len(_NonEagerInputs(op, xs)) for i, (t_in, in_grad) in enumerate(zip(_NonEagerInputs(op, xs), in_grads)): if in_grad is not None: if (isinstance(in_grad, ops.Tensor) and t_in.dtype != dtypes.resource): try: in_grad.set_shape(t_in.get_shape()) except ValueError: raise ValueError( "Incompatible shapes between op input and calculated " "input gradient. Forward operation: %s. Input index: %d. " "Original input shape: %s. " "Calculated input gradient shape: %s" % (op.name, i, t_in.shape, in_grad.shape)) _SetGrad(grads, t_in, in_grad) if loop_state: loop_state.ExitGradWhileContext(op, before=False) # Update pending count for the inputs of op and enqueue ready ops. _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state, xs) if loop_state: loop_state.PostProcessing() return [_GetGrad(grads, x, unconnected_gradients) for x in xs] def _HasAnyNotNoneGrads(grads, op): """Return true iff op has real gradient.""" out_grads = _GetGrads(grads, op) for out_grad in out_grads: if isinstance(out_grad, (ops.Tensor, ops.IndexedSlices)): return True if out_grad and isinstance(out_grad, collections.Sequence): if any(g is not None for g in out_grad): return True return False def _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state, xs): """Update pending count for the inputs of op and enqueue ready ops.""" for x in _NonEagerInputs(op, xs): pending_count[x.op] -= 1 ready = (pending_count[x.op] == 0) if loop_state and not ready: ready = pending_count[x.op] > 0 and control_flow_util.IsLoopSwitch(x.op) if ready: if control_flow_util.IsLoopExit(x.op): # if x is an exit without real gradient, defer processing them. grad_state = loop_state.GetGradState(x.op, before=False) grad_state.deferred_exits.append(x) grad_state.pending_exits_count -= 1 if grad_state.pending_exits_count == 0: # We now have all the exits so process them. has_not_none_grad = False for y in grad_state.deferred_exits: if _HasAnyNotNoneGrads(grads, y.op): has_not_none_grad = True queue.append(y.op) else: grad_state.unused_exits.append(y) if has_not_none_grad: # For an unused exit, if it has trainable outputs, backprop # a zero gradient. Otherwise, just ignore it. for y in grad_state.unused_exits: if IsTrainable(y): _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) else: # All exits are "unused" so use None as gradient. for y in grad_state.unused_exits: queue.append(y.op) else: queue.append(x.op) def _SetGrad(grads, t, grad): """Sets gradient "grad" in "grads" for tensor "t".""" op = t.op op_grads = grads.get(op) if not op_grads: op_grads = [[] for _ in xrange(len(op.outputs))] grads[op] = op_grads t_grads = op_grads[t.value_index] if isinstance(t_grads, list): t_grads.append(grad) else: assert control_flow_util.IsLoopSwitch(op) op_grads[t.value_index] = grad def _GetGrad(grads, t, unconnected_gradients): """Gets gradient for tensor "t".""" op = t.op op_grads = grads.get(op) if not op_grads: if unconnected_gradients == UnconnectedGradients.ZERO: t_dtype = t.dtype if t.dtype != dtypes.resource else dtypes.float32 return array_ops.zeros_like(t, dtype=t_dtype) elif unconnected_gradients == UnconnectedGradients.NONE: return None else: raise ValueError( "Unknown value for unconnected_gradients: %r" % unconnected_gradients) t_grad = op_grads[t.value_index] assert not isinstance( t_grad, list), ("gradients list should have been aggregated by now.") return t_grad def _GetGrads(grads, op): """Gets all gradients for op.""" if op in grads: return grads[op] else: return [[] for _ in xrange(len(op.outputs))] def _HandleNestedIndexedSlices(grad): assert isinstance(grad, ops.IndexedSlices) if isinstance(grad.values, ops.Tensor): return grad else: assert isinstance(grad.values, ops.IndexedSlices) g = _HandleNestedIndexedSlices(grad.values) return ops.IndexedSlices(g.values, array_ops.gather( grad.indices, g.indices), g.dense_shape) def _AccumulatorShape(inputs): shape = tensor_shape.unknown_shape() for i in inputs: if isinstance(i, ops.Tensor): shape = shape.merge_with(i.get_shape()) return shape def _LogOpGradients(op, out_grads, in_grads): """Log the in and out grads of an op.""" logging.vlog(1, "Gradient for '" + op.name + "'") def _FilterGrad(x): if x is None: return False if isinstance(x, (list, tuple)): return bool(x) else: return True logging.vlog(1, " in --> %s", ", ".join([x.name for x in out_grads if _FilterGrad(x)])) logging.vlog(1, " out --> %s", ", ".join([x.name for x in in_grads if _FilterGrad(x)])) def _MultiDeviceAddN(tensor_list, gradient_uid): """Adds tensors from potentially multiple devices.""" # Basic function structure comes from control_flow_ops.group(). # Sort tensors according to their devices. tensors_on_device = collections.defaultdict(lambda: []) for tensor in tensor_list: tensors_on_device[tensor.device].append(tensor) # For each device, add the tensors on that device first. # Then gather the partial sums from multiple devices. # TODO(sjhwang): Create hierarchical aggregation tree as pbar's suggestion. # E.g., aggregate per GPU, then per task, and so on. summands = [] def DeviceKey(dev): return "" if dev is None else dev for dev in sorted(six.iterkeys(tensors_on_device), key=DeviceKey): tensors = tensors_on_device[dev] with ops._colocate_with_for_gradient( # pylint: disable=protected-access tensors[0].op, gradient_uid, ignore_existing=True): summands.append(math_ops.add_n(tensors)) return math_ops.add_n(summands) @tf_export("AggregationMethod") class AggregationMethod(object): """A class listing aggregation methods used to combine gradients. Computing partial derivatives can require aggregating gradient contributions. This class lists the various methods that can be used to combine gradients in the graph: * `ADD_N`: All of the gradient terms are summed as part of one operation using the "AddN" op. It has the property that all gradients must be ready before any aggregation is performed. * `DEFAULT`: The system-chosen default aggregation method. """ ADD_N = 0 DEFAULT = ADD_N # The following are experimental and may not be supported in future releases. EXPERIMENTAL_TREE = 1 EXPERIMENTAL_ACCUMULATE_N = 2 def _AggregatedGrads(grads, op, gradient_uid, loop_state, aggregation_method=None): """Get the aggregated gradients for op. Args: grads: The map of memoized gradients. op: The op to get gradients for. gradient_uid: A unique identifier within the graph indicating which invocation of gradients is being executed. Used to cluster ops for compilation. loop_state: An object for maintaining the state of the while loops in the graph. It is of type ControlFlowState. None if the graph contains no while loops. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. Returns: A list of gradients, one per each output of `op`. If the gradients for a particular output is a list, this function aggregates it before returning. Raises: TypeError: if the incoming grads are not Tensors or IndexedSlices. ValueError: if the arguments are invalid. """ if aggregation_method is None: aggregation_method = AggregationMethod.DEFAULT if aggregation_method not in [ AggregationMethod.ADD_N, AggregationMethod.EXPERIMENTAL_TREE, AggregationMethod.EXPERIMENTAL_ACCUMULATE_N ]: raise ValueError( "Invalid aggregation_method specified %s." % aggregation_method) out_grads = _GetGrads(grads, op) for i, out_grad in enumerate(out_grads): if loop_state: if isinstance(out_grad, (ops.Tensor, ops.IndexedSlices)): assert control_flow_util.IsLoopSwitch(op) continue # Grads have to be Tensors or IndexedSlices if (isinstance(out_grad, collections.Sequence) and not all( isinstance(g, (ops.Tensor, ops.IndexedSlices)) for g in out_grad if g is not None )): raise TypeError("gradients have to be either all Tensors " "or all IndexedSlices") # Aggregate multiple gradients, and convert [] to None. if out_grad: if len(out_grad) < 2: used = "nop" out_grads[i] = out_grad[0] elif all(isinstance(g, ops.Tensor) for g in out_grad if g is not None): tensor_shape = _AccumulatorShape(out_grad) if (aggregation_method == AggregationMethod.EXPERIMENTAL_ACCUMULATE_N and len(out_grad) > 2 and tensor_shape.is_fully_defined()): # The benefit of using AccumulateN is that its inputs can be combined # in any order and this can allow the expression to be evaluated with # a smaller memory footprint. When used with gpu_allocator_retry, # it is possible to compute a sum of terms which are much larger than # total GPU memory. # AccumulateN can currently only be used if we know the shape for # an accumulator variable. If this is not known, or if we only have # 2 grads then we fall through to the "tree" case below. used = "accumulate_n" out_grads[i] = math_ops.accumulate_n(out_grad) elif aggregation_method in [ AggregationMethod.EXPERIMENTAL_TREE, AggregationMethod.EXPERIMENTAL_ACCUMULATE_N ]: # Aggregate all gradients by doing pairwise sums: this may # reduce performance, but it can improve memory because the # gradients can be released earlier. # # TODO(vrv): Consider replacing this with a version of # tf.AddN() that eagerly frees its inputs as soon as they are # ready, so the order of this tree does not become a problem. used = "tree" with ops.name_scope(op.name + "_gradient_sum"): running_sum = out_grad[0] for grad in out_grad[1:]: running_sum = math_ops.add_n([running_sum, grad]) out_grads[i] = running_sum else: used = "add_n" out_grads[i] = _MultiDeviceAddN(out_grad, gradient_uid) logging.vlog(2, " _AggregatedGrads %d x %s using %s", len(out_grad), tensor_shape, used) else: out_grads[i] = _AggregateIndexedSlicesGradients(out_grad) else: # not out_grad # out_grads[i] is [], thus its aggregation is simply None. out_grads[i] = None return out_grads def _AggregateIndexedSlicesGradients(grads): """Aggregates gradients of type `IndexedSlices` by concatenation.""" if len(grads) < 1: return None elif len(grads) == 1: return grads[0] else: grads = math_ops._as_indexed_slices_list( # pylint: disable=protected-access [g for g in grads if g is not None]) grads = [_HandleNestedIndexedSlices(x) for x in grads] # pylint: disable=protected-access # Form IndexedSlices out of the concatenated values and indices. concat_grad = ops.IndexedSlices( array_ops.concat([x.values for x in grads], axis=0), array_ops.concat([x.indices for x in grads], axis=0), grads[0].dense_shape) return concat_grad # TODO(vrv): Make this available when we want to make it public. def _hessian_vector_product(ys, xs, v): """Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length. """ # Validate the input length = len(xs) if len(v) != length: raise ValueError("xs and v must have the same length.") # First backprop grads = gradients(ys, xs) assert len(grads) == length elemwise_products = [ math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem)) for grad_elem, v_elem in zip(grads, v) if grad_elem is not None ] # Second backprop return gradients(elemwise_products, xs) @tf_export(v1=["hessians"]) def hessians(ys, xs, name="hessians", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None): """Constructs the Hessian of sum of `ys` with respect to `x` in `xs`. `hessians()` adds ops to the graph to output the Hessian matrix of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the Hessian of `sum(ys)`. The Hessian is a matrix of second-order partial derivatives of a scalar tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details). Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. name: Optional name to use for grouping all the gradient ops together. defaults to 'hessians'. colocate_gradients_with_ops: See `gradients()` documentation for details. gate_gradients: See `gradients()` documentation for details. aggregation_method: See `gradients()` documentation for details. Returns: A list of Hessian matrices of `sum(ys)` for each `x` in `xs`. Raises: LookupError: if one of the operations between `xs` and `ys` does not have a registered gradient function. """ xs = _AsList(xs) kwargs = { "colocate_gradients_with_ops": colocate_gradients_with_ops, "gate_gradients": gate_gradients, "aggregation_method": aggregation_method } # Compute first-order derivatives and iterate for each x in xs. hessians = [] _gradients = gradients(ys, xs, **kwargs) for gradient, x in zip(_gradients, xs): # change shape to one-dimension without graph branching gradient = array_ops.reshape(gradient, [-1]) # Declare an iterator and tensor array loop variables for the gradients. n = array_ops.size(x) loop_vars = [ array_ops.constant(0, dtypes.int32), tensor_array_ops.TensorArray(x.dtype, n) ] # Iterate over all elements of the gradient and compute second order # derivatives. _, hessian = control_flow_ops.while_loop( lambda j, _: j < n, lambda j, result: (j + 1, result.write(j, gradients(gradient[j], x)[0])), loop_vars ) _shape = array_ops.shape(x) _reshaped_hessian = array_ops.reshape(hessian.stack(), array_ops.concat((_shape, _shape), 0)) hessians.append(_reshaped_hessian) return hessians @tf_export("hessians", v1=[]) def HessiansV2(ys, xs, gate_gradients=False, aggregation_method=None, name="hessians"): return hessians(ys, xs, name=name, gate_gradients=gate_gradients, aggregation_method=aggregation_method) HessiansV2.__doc__ = hessians.__doc__
hfp/tensorflow-xsmm
tensorflow/python/ops/gradients_impl.py
Python
apache-2.0
57,017
[ "VisIt" ]
cc9337363be811592e49d1773b2eb94f7ac348368b07acd05d23ba052c8421ce
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Implements commands for running and interacting with Fuchsia on devices.""" import boot_data import logging import os import pkg_repo import re import subprocess import target import time from common import EnsurePathExists, GetHostToolPathFromPlatform, \ RunGnSdkFunction, SubprocessCallWithTimeout # The maximum times to attempt mDNS resolution when connecting to a freshly # booted Fuchsia instance before aborting. BOOT_DISCOVERY_ATTEMPTS = 30 # Number of failed connection attempts before redirecting system logs to stdout. CONNECT_RETRY_COUNT_BEFORE_LOGGING = 10 # Number of seconds between each device discovery. BOOT_DISCOVERY_DELAY_SECS = 4 # Time between a reboot command is issued and when connection attempts from the # host begin. _REBOOT_SLEEP_PERIOD = 20 # File indicating version of an image downloaded to the host _BUILD_ARGS = "buildargs.gn" # File on device that indicates Fuchsia version. _ON_DEVICE_VERSION_FILE = '/config/build-info/version' # File on device that indicates Fuchsia product. _ON_DEVICE_PRODUCT_FILE = '/config/build-info/product' def GetTargetType(): return DeviceTarget class DeviceTarget(target.Target): """Prepares a device to be used as a deployment target. Depending on the command line parameters, it automatically handling a number of preparatory steps relating to address resolution. If |_node_name| is unset: If there is one running device, use it for deployment and execution. If there are more than one running devices, then abort and instruct the user to re-run the command with |_node_name| If |_node_name| is set: If there is a running device with a matching nodename, then it is used for deployment and execution. If |_host| is set: Deploy to a device at the host IP address as-is.""" def __init__(self, out_dir, target_cpu, host, node_name, port, ssh_config, fuchsia_out_dir, os_check, logs_dir, system_image_dir): """out_dir: The directory which will contain the files that are generated to support the deployment. target_cpu: The CPU architecture of the deployment target. Can be "x64" or "arm64". host: The address of the deployment target device. node_name: The node name of the deployment target device. port: The port of the SSH service on the deployment target device. ssh_config: The path to SSH configuration data. fuchsia_out_dir: The path to a Fuchsia build output directory, for deployments to devices paved with local Fuchsia builds. os_check: If 'check', the target's SDK version must match. If 'update', the target will be repaved if the SDK versions mismatch. If 'ignore', the target's SDK version is ignored. system_image_dir: The directory which contains the files used to pave the device.""" super(DeviceTarget, self).__init__(out_dir, target_cpu, logs_dir) self._host = host self._port = port self._fuchsia_out_dir = None self._node_name = node_name or os.environ.get('FUCHSIA_NODENAME') self._system_image_dir = system_image_dir self._os_check = os_check self._pkg_repo = None if not self._system_image_dir and self._os_check != 'ignore': raise Exception("Image directory must be provided if a repave is needed.") if self._host and self._node_name: raise Exception('Only one of "--host" or "--name" can be specified.') if fuchsia_out_dir: if ssh_config: raise Exception('Only one of "--fuchsia-out-dir" or "--ssh_config" can ' 'be specified.') self._fuchsia_out_dir = os.path.expanduser(fuchsia_out_dir) # Use SSH keys from the Fuchsia output directory. self._ssh_config_path = os.path.join(self._fuchsia_out_dir, 'ssh-keys', 'ssh_config') self._os_check = 'ignore' elif ssh_config: # Use the SSH config provided via the commandline. self._ssh_config_path = os.path.expanduser(ssh_config) else: return_code, ssh_config_raw, _ = RunGnSdkFunction( 'fuchsia-common.sh', 'get-fuchsia-sshconfig-file') if return_code != 0: raise Exception('Could not get Fuchsia ssh config file.') self._ssh_config_path = os.path.expanduser(ssh_config_raw.strip()) @staticmethod def CreateFromArgs(args): return DeviceTarget(args.out_dir, args.target_cpu, args.host, args.node_name, args.port, args.ssh_config, args.fuchsia_out_dir, args.os_check, args.logs_dir, args.system_image_dir) @staticmethod def RegisterArgs(arg_parser): device_args = arg_parser.add_argument_group( 'device', 'External device deployment arguments') device_args.add_argument('--host', help='The IP of the target device. Optional.') device_args.add_argument('--node-name', help='The node-name of the device to boot or ' 'deploy to. Optional, will use the first ' 'discovered device if omitted.') device_args.add_argument('--port', '-p', type=int, default=None, help='The port of the SSH service running on the ' 'device. Optional.') device_args.add_argument('--ssh-config', '-F', help='The path to the SSH configuration used for ' 'connecting to the target device.') device_args.add_argument( '--os-check', choices=['check', 'update', 'ignore'], default='ignore', help="Sets the OS version enforcement policy. If 'check', then the " "deployment process will halt if the target\'s version doesn\'t " "match. If 'update', then the target device will automatically " "be repaved. If 'ignore', then the OS version won\'t be checked.") device_args.add_argument('--system-image-dir', help="Specify the directory that contains the " "Fuchsia image used to pave the device. Only " "needs to be specified if 'os_check' is not " "'ignore'.") def _Discover(self): """Queries mDNS for the IP address of a booted Fuchsia instance whose name matches |_node_name| on the local area network. If |_node_name| isn't specified, and there is only one device on the network, then returns the IP address of that advice. Sets |_host_name| and returns True if the device was found, or waits up to |timeout| seconds and returns False if the device couldn't be found.""" dev_finder_path = GetHostToolPathFromPlatform('device-finder') with open(os.devnull, 'w') as devnull: if self._node_name: command = [ dev_finder_path, 'resolve', '-device-limit', '1', # Exit early as soon as a host is found. self._node_name ] proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=devnull, text=True) else: proc = self.RunFFXCommand(['target', 'list', '-f', 'simple'], stdout=subprocess.PIPE, stderr=devnull, text=True) output = set(proc.communicate()[0].strip().split('\n')) if proc.returncode != 0: return False if self._node_name: # Handle the result of "device-finder resolve". self._host = output.pop().strip() else: name_host_pairs = [x.strip().split(' ') for x in output] if len(name_host_pairs) > 1: raise Exception('More than one device was discovered on the network. ' 'Use --node-name <name> to specify the device to use.' 'List of devices: {}'.format(output)) assert len(name_host_pairs) == 1 # Check if device has both address and name. if len(name_host_pairs[0]) < 2: return False self._host, self._node_name = name_host_pairs[0] logging.info('Found device "%s" at address %s.' % (self._node_name, self._host)) return True def Start(self): if self._host: self._WaitUntilReady() else: device_found = self._Discover() if device_found: self._WaitUntilReady() if self._os_check == 'ignore': return # If accessible, check version. new_version = self._GetSdkHash() installed_version = self._GetInstalledSdkVersion() if new_version == installed_version: logging.info('Fuchsia version installed on device matches Chromium ' 'SDK version. Skipping pave.') else: if self._os_check == 'check': raise Exception('Image and Fuchsia version installed on device ' 'does not match. Abort.') logging.info('Putting device in recovery mode') self.RunCommandPiped(['dm', 'reboot-recovery'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self._ProvisionDevice() else: if self._node_name: logging.info('Could not detect device %s.' % self._node_name) if self._os_check == 'update': logging.info('Assuming it is in zedboot. Continuing with paving...') self._ProvisionDevice() return raise Exception('Could not find device. If the device is connected ' 'to the host remotely, make sure that --host flag ' 'is set and that remote serving is set up.') def _GetInstalledSdkVersion(self): """Retrieves installed OS version from device. Returns: Tuple of strings, containing (product, version number) """ return (self.GetFileAsString(_ON_DEVICE_PRODUCT_FILE).strip(), self.GetFileAsString(_ON_DEVICE_VERSION_FILE).strip()) def _GetSdkHash(): """Read version of hash in pre-installed package directory. Returns: Tuple of (product, version) of image to be installed. Raises: VersionNotFoundError: if contents of buildargs.gn cannot be found or the version number cannot be extracted. """ # TODO(crbug.com/1261961): Stop processing buildargs.gn directly. with open(os.path.join(self._system_image_dir, _BUILD_ARGS)) as f: contents = f.readlines() if not contents: raise VersionNotFoundError('Could not retrieve %s' % _BUILD_ARGS) version_key = 'build_info_version' product_key = 'build_info_product' info_keys = [product_key, version_key] version_info = {} for line in contents: for k in info_keys: match = re.match(r'%s = "(.*)"' % k, line) if match: version_info[k] = match.group(1) if not (version_key in version_info and product_key in version_info): raise VersionNotFoundError( 'Could not extract version info from %s. Contents: %s' % (_BUILD_ARGS, contents)) return (version_info[product_key], version_info[version_key]) def GetPkgRepo(self): if not self._pkg_repo: if self._fuchsia_out_dir: # Deploy to an already-booted device running a local Fuchsia build. self._pkg_repo = pkg_repo.ExternalPkgRepo( os.path.join(self._fuchsia_out_dir, 'amber-files'), os.path.join(self._fuchsia_out_dir, '.build-id')) else: # Create an ephemeral package repository, then start both "pm serve" as # well as the bootserver. self._pkg_repo = pkg_repo.ManagedPkgRepo(self) return self._pkg_repo def _ParseNodename(self, output): # Parse the nodename from bootserver stdout. m = re.search(r'.*Proceeding with nodename (?P<nodename>.*)$', output, re.MULTILINE) if not m: raise Exception('Couldn\'t parse nodename from bootserver output.') self._node_name = m.groupdict()['nodename'] logging.info('Booted device "%s".' % self._node_name) # Repeatedly search for a device for |BOOT_DISCOVERY_ATTEMPT| # number of attempts. If a device isn't found, wait # |BOOT_DISCOVERY_DELAY_SECS| before searching again. logging.info('Waiting for device to join network.') for _ in range(BOOT_DISCOVERY_ATTEMPTS): if self._Discover(): break time.sleep(BOOT_DISCOVERY_DELAY_SECS) if not self._host: raise Exception('Device %s couldn\'t be discovered via mDNS.' % self._node_name) self._WaitUntilReady(); def _GetEndpoint(self): return (self._host, self._port) def _GetSshConfigPath(self): return self._ssh_config_path def _ProvisionDevice(self): _, auth_keys, _ = RunGnSdkFunction('fuchsia-common.sh', 'get-fuchsia-auth-keys-file') pave_command = [ os.path.join(self._system_image_dir, 'pave.sh'), '--authorized-keys', auth_keys.strip() ] if self._node_name: pave_command.extend(['-n', self._node_name, '-1']) logging.info(' '.join(pave_command)) return_code, stdout, stderr = SubprocessCallWithTimeout(pave_command, timeout_secs=300) if return_code != 0: raise Exception('Could not pave device.') self._ParseNodename(stderr) def Restart(self): """Restart the device.""" self.RunCommandPiped('dm reboot') time.sleep(_REBOOT_SLEEP_PERIOD) self.Start() def Stop(self): try: super(DeviceTarget, self).Stop() finally: # End multiplexed ssh connection, ensure that ssh logging stops before # tests/scripts return. if self.IsStarted(): self.RunCommand(['-O', 'exit'])
scheib/chromium
build/fuchsia/device_target.py
Python
bsd-3-clause
14,384
[ "Amber" ]
a776c16233c3d174870ec93496500f1aa3de7322c5e9367c64f30c8dad7661e5
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path as op import sys import re import logging from astropy.table import Table, Column from maize.apps.base import AttrDict, str2bool, eprint, sh, mkdir, which from maize.formats.base import must_open from maize.formats.pbs import PbsJob, create_job_chain def check_cfg_mapping(c): c.outdirs = c.outdir.split(",") assert len(c.outdirs) == 2, "not 2 outdirs: %s" % c.outdir for subdir in [c.dirw, c.temp_dir] + c.outdirs: if not op.isdir(subdir): mkdir(subdir) for fn in [c.ilist, c.genome, c.gff]: assert op.isfile(fn), "cannot read %s" % fn for key in 'samtools parallel sambamba bcftools bedtools'.split(): fp = which(c[key]) assert fp is not None, "not executable: %s" % c[key] c[key] = fp c.paired = str2bool(c.paired) if c.mapper == 'bwa': c.bwa = which(c.bwa) assert c.bwa is not None, "not executable: %s" % c.bwa elif c.mapper == 'hisat2': c.hisat2 = which(c.hisat2) assert c.hisat2 is not None, "not executable: %s" % c.hisat2 elif c.mapper == 'bowtie2': c.bowtie2 = which(c.bowtie2) assert c.bowtie2 is not None, "not executable: %s" % c.bowtie2 else: logging.error("unsupported mapper: %s" % c.mapper) sys.exit(1) njob = 3 c.pbs_walltimes = c.pbs_walltime.split(",") c.pbs_ppns = c.pbs_ppn.split(",") c.pbs_queues = c.pbs_queue.split(",") assert njob == len(c.pbs_queues) == len(c.pbs_walltimes) == len(c.pbs_ppns), "not %d jobs: %s" % (njob, c.pbs_queue) c.njob = njob return c def mapping(cfg, args): c = AttrDict(cfg['mapping']) c = check_cfg_mapping(c) if args.check: mapping_check(c) return 0 os.chdir(c.dirw) jcmds = [[ "cd %s" % c.dirw, ], [ "cd %s" % c.dirw, ], [ "cd %s" % c.dirw, ]] bcfgs = [ [dict(opt = 'bash')], [dict(opt = 'parallel', thread = c.pbs_ppns[1])], [dict(opt = 'bash'), dict(opt = 'parallel', thread = c.pbs_ppns[2]), ], ] assert c.njob == len(bcfgs) == len(jcmds), "not %d jobs" % c.njob jobs = [] for i in range(c.njob): prefix = "%s.%d" % (c.job_prefix, i+1) jcfg = { 'queue': c.pbs_queues[i], 'ppn': c.pbs_ppns[i], 'walltime': c.pbs_walltimes[i], 'email': c.pbs_email, } job = PbsJob.from_cfg(jcfg = jcfg, jcmds = jcmds[i], bcfgs = bcfgs[i], prefix = prefix, njob = len(bcfgs[i]), bash = c.bash, parallel = c.parallel) jobs.append(job) t = Table.read(c.ilist, format = 'ascii.tab') nrow = len(t) for i in range(nrow): sid = t['sid'][i] pre1= "%s/%s" % (c.outdirs[0], sid) fsam = "%s.sam" % pre1 input_str = '' if c.paired: f1p = t["TrimmedReadFile1Paired"][i] f1u = t["TrimmedReadFile1Unpaired"][i] f2p = t["TrimmedReadFile2Paired"][i] f2u = t["TrimmedReadFile2Unpaired"][i] if c.mapper == 'hisat2' or c.mapper == 'bowtie2': input_str = "-1 %s -2 %s -U %s,%s" % (f1p, f2p, f1u, f2u) elif c.mapper == 'bwa': input_str = "%s %s" % (f1p, f2p) else: ft = t["TrimmedReadFile"][i] if c.mapper == 'hisat2' or c.mapper == 'bowtie2': input_str = "-U %s" % ft elif c.mapper == 'bwa': input_str = "%s" % ft if c.mapper == 'bwa': jobs[0].subjobs[0].add_cmd("%s mem -t %s %s %s \ -R '@RG\\tID:%s\\tSM:%s' -a > %s.sam" % \ (c.bwa, c.pbs_ppns[0], c.bwa_db, input_str, \ sid, sid, pre1)) elif c.mapper == 'hisat2': jobs[0].subjobs[0].add_cmd("%s -p %s -x %s -q %s \ --no-spliced-alignment --rg-id %s --rg SM:%s -S %s.sam" % \ (c.hisat2, c.pbs_ppns[0], c.hisat_db, input_str, \ sid, sid, pre1)) elif c.mapper == 'bowtie2': jobs[0].subjobs[0].add_cmd("%s -p %s -x %s -q %s \ --rg-id %s --rg SM:%s --sensitive -S %s.sam" % \ (c.bowtie2, c.pbs_ppns[0], c.bowtie_db, input_str, \ sid, sid, pre1)) fbam = "%s.bam" % pre1 jobs[1].subjobs[0].add_cmd("%s view -Sb %s.sam -o %s.raw.bam" % \ (c.samtools, pre1, pre1)) jobs[2].subjobs[0].add_cmd("%s sort -t %s -m 60GB %s.raw.bam -o %s.bam" % \ (c.sambamba, c.pbs_ppns[2], pre1, pre1)) #bcmds[2].append("%s index -t %s %s.bam" % (sambamba, pbs_ppns[2], pre1)) pre2 = "%s/%s" % (c.outdirs[1], sid) jobs[2].subjobs[1].add_cmd("bam stat %s.bam --isize %s.ins.tsv > %s.tsv" % \ (pre1, pre2, pre2)) for job in jobs: job.write() fj = "%s.sh" % c.job_prefix create_job_chain([job.fname for job in jobs], fj) logging.debug("job chain with %s jobs was created: %s" % (c.njob, fj)) def mapping_check(cfg): t = Table.read(ilist, format = 'ascii.tab') nrow = len(t) newcols = '' if c.paired: newcols = '''BAM Pair Pair_Map Pair_Orphan Pair_Unmap Pair_Map_Hq Unpair Unpair_Map Unpair_Map_Hq'''.split() else: newcols = '''BAM Total Mapped Mapped_Hq'''.split() for newcol in newcols: t.add_column(Column(name = newcol, length = nrow, dtype = object)) for i in range(nrow): sid = t['sid'][i] bam = "%s/%s.bam" % (c.outdirs[0], sid) assert op.isfile(bam), "%s not exist" % bam fs = "%s/%s.tsv" % (c.outdirs[1], sid) assert op.isfile(fs), "%s not exist" % fs if c.paired: t['BAM'][i] = 0#bam t['Pair'][i] = 0#pair t['Pair_Map'][i] = 0#pair_map t['Pair_Orphan'][i] = 0#pair_orphan t['Pair_Unmap'][i] = 0#pair_unmap t['Pair_Map_Hq'][i] = 0#pair_map_hq t['Unpair'][i] = 0#unpair t['Unpair_Map'][i] = 0#unpair_map t['Unpair_Map_Hq'][i] = 0#unpair_map_hq else: t['BAM'] = 0#bam t['Total'] = 0#unpair t['Mapped'] = 0#unpair_map t['Mapped_Hq'] = 0#unpair_map_hq t.write(t.olist, format='ascii.tab', overwrite=True) if __name__ == "__main__": import argparse import configparser parser = argparse.ArgumentParser( formatter_class = argparse.ArgumentDefaultsHelpFormatter, description = 'Illumina DNA-Seq pipeline(s)' ) parser.add_argument('--config', "--cfg", default = "config.ini", help = 'config file') sp = parser.add_subparsers(title = 'available commands', dest = 'command') sp1 = sp.add_parser("mapping", formatter_class = argparse.ArgumentDefaultsHelpFormatter, help = 'mapping' ) sp1.add_argument("--check", action = 'store_true', help = "run script in check mode") sp1.set_defaults(func = mapping) args = parser.parse_args() assert op.isfile(args.config), "cannot read %s" % args.config cfg = configparser.ConfigParser() cfg._interpolation = configparser.ExtendedInterpolation() cfg.read(args.config) if args.command: args.func(cfg, args) else: print('Error: need to specify a sub command\n') parser.print_help()
orionzhou/robin
old/pipelines/dnaseq.py
Python
gpl-2.0
7,532
[ "BWA" ]
757d34f230bbcfc78c879b688b933a95b75ee040bb0ec1f29d21acccff079509
#!/usr/bin/env python # Copyright 2014-2018 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. import unittest from pyscf import lib from pyscf import scf from pyscf import gto from pyscf import grad from pyscf import cc from pyscf.grad import rks, uks, roks mol = gto.Mole() mol.verbose = 7 mol.output = '/dev/null' mol.atom = [ [1 , (0. , 0.1, .817)], ["F" , (0. , 0. , 0.)], ] mol.basis = {"H": '6-31g', "F": '6-31g',} mol.build() def tearDownModule(): global mol mol.stdout.close() del mol def finger(mat): return abs(mat).sum() class KnownValues(unittest.TestCase): def test_nr_rhf(self): rhf = scf.RHF(mol) rhf.conv_tol = 1e-14 rhf.scf() g = grad.RHF(rhf) self.assertAlmostEqual(finger(g.grad_elec()), 7.9210392362911595, 6) self.assertAlmostEqual(finger(g.kernel()), 0.367743084803, 6) def test_r_uhf(self): uhf = scf.dhf.UHF(mol) uhf.conv_tol = 1e-10 uhf.scf() g = grad.DHF(uhf) self.assertAlmostEqual(finger(g.grad_elec()), 7.9216825870803245, 6) g.level = 'LLLL' self.assertAlmostEqual(finger(g.grad_elec()), 7.924684281032623, 6) def test_energy_nuc(self): rhf = scf.RHF(mol) rhf.scf() g = grad.RHF(rhf) self.assertAlmostEqual(finger(g.grad_nuc()), 8.2887823210941249, 9) def test_ccsd(self): rhf = scf.RHF(mol) rhf.set(conv_tol=1e-10).scf() mycc = cc.CCSD(rhf) mycc.kernel() mycc.solve_lambda() g1 = mycc.nuc_grad_method().kernel() self.assertAlmostEqual(finger(g1), 0.43305028391866857, 6) def test_rhf_scanner(self): mol1 = mol.copy() mol1.set_geom_(''' H 0. 0. 0.9 F 0. 0.1 0.''') mf_scanner = grad.RHF(scf.RHF(mol).set(conv_tol=1e-14)).as_scanner() e, de = mf_scanner(mol) self.assertAlmostEqual(finger(de), 0.367743084803, 6) e, de = mf_scanner(mol1) self.assertAlmostEqual(finger(de), 0.041822093538, 6) def test_rks_scanner(self): mol1 = mol.copy() mol1.set_geom_(''' H 0. 0. 0.9 F 0. 0.1 0.''') mf_scanner = rks.Grad(scf.RKS(mol).set(conv_tol=1e-14)).as_scanner() e, de = mf_scanner(mol) self.assertAlmostEqual(finger(de), 0.458572523892797, 6) e, de = mf_scanner(mol1) self.assertAlmostEqual(finger(de), 0.12763259021187467, 6) def test_ccsd_scanner(self): mycc = cc.CCSD(scf.RHF(mol).set(conv_tol=1e-14)) cc_scanner = mycc.nuc_grad_method().as_scanner() e, de = cc_scanner(mol) self.assertAlmostEqual(finger(de), 0.4330503011412547, 5) mol1 = gto.M(atom=''' H 0. 0. 0.9 F 0. 0.1 0.''', verbose=0) e, de = cc_scanner(mol1) self.assertAlmostEqual(finger(de), 0.2618586029073042, 5) if __name__ == "__main__": print("Full Tests for HF") unittest.main()
sunqm/pyscf
pyscf/grad/test/test_hf.py
Python
apache-2.0
3,540
[ "PySCF" ]
bff5d301bd249dd8f0647777bd5fb77943cb9ded280761a13d91b89bb7a5d3ba
# -*- 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 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(r'^users/', include("pyconve_site.users.urls", namespace="users")), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here url(r'^talks/', include("pyconve_site.talks.urls", namespace="talks")), ] + 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'), ]
pyve/pyconve-site
config/urls.py
Python
bsd-3-clause
1,310
[ "VisIt" ]
41a9d3dfb314edaf8944332639f2bd1422de2d51136f4d77511ee45a7f8196fe
#!/usr/bin/env python """ segmentation-fold can predict RNA 2D structures including K-turns. Copyright (C) 2012-2016 Youri Hoogstrate This file is part of segmentation-fold segmentation-fold 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. segmentation-fold 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 sys,argparse,textwrap,datetime,click from segmentation_fold_utils import __version__, __author__, __homepage__ from segmentation_fold_utils.FindBoxes import FindBoxes from segmentation_fold_utils.ExtractBoxedSequences import ExtractBoxedSequences from segmentation_fold_utils.XMLFile import XMLFile from segmentation_fold_utils.DBNFile import DBNFile from segmentation_fold_utils.FastaFile import FastaFile @click.version_option(__version__) @click.group() def CLI(): pass @CLI.command(name="estimate-energy",short_help="Estimates whether a certain Segment(Loop) is present and for which delta-G this transistion takes place") @click.option("--temp-dir","-t",type=click.Path(exists=True),default="/tmp",help="Ppath in which temporary conifig files will be stored (default: /tmp)") @click.option("--segmentation-fold","-s",default="segmentation-fold",help="Location of segmentatio-fold binary (default: segmentation-fold)") @click.option("--xml-file","-x", type=click.File('r'),default="/usr/local/share/segmentation-fold/segments.xml",help="Location of segments.xml (default: /usr/local/share/segmentation-fold/segments.xml)") @click.option("--threads","-T",default=2,type=int,help="Number of threads per spawned instance of segmentation-fold") @click.option("--precision","-p",default=0.05,help="Minimal difference for binary split - the smaller this value the slower. if this value equals 0, the difference is set to infinity (default: 0.05)") @click.option("--randomize","-r",default=0,type=int,help="Shuffle each sequence this many times and predict energy of shuffled sequence(s) (default: 0, 0 means disabled)") @click.option("--sequences-from-fasta-file","-f", type=click.Path(exists=True),default=None,help="Use sequences from a FASTA file instead of using the XML file that also contains the segments. In XML files you can explicitly link one Segment(Loop) to one particular sequence instead of doing n*n comparisons (default: None)") @click.argument('dbn_output_file', type=click.File('w')) def CLI_energy_estimation(temp_dir,segmentation_fold,xml_file,threads,precision,randomize,sequences_from_fasta_file,dbn_output_file): xml = XMLFile(xml_file) xml.estimate_energy(temp_dir,segmentation_fold,threads,precision,randomize,sequences_from_fasta_file,dbn_output_file) @CLI.command(name='find-boxes',short_help='Finds all occurances of two given boxes (sequence motifs) within a FASTA file (sequence headers may not contain spaces)') @click.argument('fasta_input_file', type=click.Path(exists=True)) @click.argument('bed_output_file', type=click.File('w')) @click.option('--box1','-c',default='NRUGAUG',help="Sequence of box1 (default = C-box: 'NRUGAUG')") @click.option('--box2','-d',default='CUGA',help="Sequence of box2 (default = D-box: 'CUGA')") @click.option('--forward/--no-forward',default=True,help="Search in the forward direction of the reference sequence") @click.option('--reverse/--no-reverse',default=True,help="Search in the reverse complement of the reference sequence") def CLI_extract_boxed_sequences(fasta_input_file,bed_output_file,box1,box2,forward,reverse): boxes = FindBoxes(fasta_input_file,box1,box2,forward,reverse) boxes.run(bed_output_file) @CLI.command(name='extract-boxed-sequences',short_help='Extracts boxed sequences from bed_input_file which has to be created with \'find-box\', part of this utility') @click.argument('fasta_input_file', type=click.Path(exists=True)) @click.argument('bed_input_file', type=click.File('r')) @click.argument('fasta_output_file', type=click.File('w')) @click.option('--max-inner-dist','-d',type=int, default=250,help="Maximal distance between the boxes (default=250bp)") @click.option('--bp-extension','-e',type=int, default=10,help="Extend extracted sequences with this number of bases (default: 10bp)") def CLI_extract_boxed_sequences(fasta_input_file,bed_input_file,fasta_output_file,max_inner_dist,bp_extension): sequences = ExtractBoxedSequences(fasta_input_file,bed_input_file,fasta_output_file,max_inner_dist,bp_extension) sequences.run(fasta_output_file) @CLI.command(name='add-read-counts',short_help='Annotate sequences by adding the read counts from a bam file, within a region contained in the fasta header of the dbn file') @click.argument('dbn_input_file', type=click.File('r')) @click.argument('bam_input_file', type=click.Path(exists=True)) @click.argument('dbn_output_file', type=click.File('w')) @click.option('--regex','-r', default=">.*?(chr[^:]):([0-9]+)-([0-9]+)",help="Regex to capture the targeted location in DBN file (default: '>.*?(chr[^:]):([0-9]+)-([0-9]+)' )") # possibility for more sam/bam flag requirements, e.g. multimap limits etc. def CLI_add_read_counts(dbn_input_file,bam_input_file,regex,dbn_output_file): structures = DBNFile(dbn_input_file,True)#estimate_energy_results is set to True because this only works with files produced by the estimate-energy subprogram structures.annotate_read_counts(bam_input_file,regex,dbn_output_file) @CLI.command(name='filter-annotated-entries',short_help='Split entries into two files based on whether they overlap annotations in a bed file') @click.argument('dbn_input_file', type=click.File('r')) @click.argument('bed_input_file', type=click.File('r')) @click.argument('dbn_output_file_overlapping', type=click.File('w')) @click.argument('dbn_output_file_non_overlapping', type=click.File('w')) @click.option('--regex','-r', default=">.*?(chr[^:]):([0-9]+)-([0-9]+)",help="Regex to capture the targeted location in DBN file (default: '>.*?(chr[^:]):([0-9]+)-([0-9]+)' )") def CLI_filter_annotated_entries(dbn_input_file,bed_input_file,regex,dbn_output_file_overlapping,dbn_output_file_non_overlapping): structures = DBNFile(dbn_input_file,True)#estimate_energy_results is set to True because this only works with files produced by the estimate-energy subprogram structures.filter_annotated_entries(regex,bed_input_file,dbn_output_file_overlapping,dbn_output_file_non_overlapping) @CLI.command(name='filter-by-energy',short_help='Split entries over two files based on the estimated energy') @click.argument('dbn_input_file', type=click.File('r')) @click.argument('dbn_output_file_larger_or_equal', type=click.File('w')) @click.argument('dbn_output_file_smaller', type=click.File('w')) @click.option('--energy','-e', type=float,help="Entries with transitions with energy smaller than energy (< e) or without transitions will be put into DBN_OUTPUT_FILE_LARGER_OR_EQUAL and those larger or equal (>= e) to DBN_OUTPUT_FILE_SMALLER") def CLI_filter_by_energy(dbn_input_file,dbn_output_file_larger_or_equal,dbn_output_file_smaller,energy): structures = DBNFile(dbn_input_file,True) structures.filter_by_energy(dbn_output_file_larger_or_equal,dbn_output_file_smaller,energy) @CLI.command(name='fix-fasta-headers',short_help='Replaces spaces in FASTA headers with underscores (for compatibility with pysam)') @click.argument('fasta_input_file', type=click.Path(exists=True)) @click.argument('fasta_output_file', type=click.File('w')) def CLI_fix_fasta_headers(fasta_input_file, fasta_output_file): fa = FastaFile(fasta_input_file) fa.fix_fasta_file(fasta_output_file)
yhoogstrate/segmentation-fold
scripts/energy-estimation-utility/segmentation_fold_utils/CLI.py
Python
gpl-3.0
7,998
[ "pysam" ]
02d9de1692eaab77fc2aefc1d8467052ead4a53dcc7b95665b6e25135ccc5cc4
from vtk import * reader1 = vtkXMLTreeReader() reader1.SetFileName("treetest.xml") reader1.Update() view = vtkTreeMapView() view.SetAreaSizeArrayName("size") view.SetAreaColorArrayName("level") view.SetAreaLabelArrayName("name") view.SetAreaLabelVisibility(True) view.SetAreaHoverArrayName("name") view.SetLayoutStrategyToSquarify() view.SetRepresentationFromInput(reader1.GetOutput()) # Apply a theme to the views theme = vtkViewTheme.CreateMellowTheme() view.ApplyViewTheme(theme) theme.FastDelete() view.ResetCamera() view.Render() view.GetInteractor().Start()
collects/VTK
Examples/Infovis/Python/treemap_view.py
Python
bsd-3-clause
569
[ "VTK" ]
ced25688602f418ff5a66e47cfd92a71315952284ed9a6dae5e3b091022a67cf
#!/usr/bin/python # -*- coding: utf-8 -*- # # This module is also sponsored by E.T.A.I. (www.etai.fr) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: vmware_guest short_description: Manages virtual machines in vCenter description: > This module can be used to create new virtual machines from templates or other virtual machines, manage power state of virtual machine such as power on, power off, suspend, shutdown, reboot, restart etc., modify various virtual machine components like network, disk, customization etc., rename a virtual machine and remove a virtual machine with associated components. version_added: '2.2' author: - Loic Blot (@nerzhul) <loic.blot@unix-experience.fr> - Philippe Dellaert (@pdellaert) <philippe@dellaert.org> - Abhijeet Kasurde (@Akasurde) <akasurde@redhat.com> requirements: - python >= 2.6 - PyVmomi notes: - Please make sure that the user used for vmware_guest has the correct level of privileges. - For example, following is the list of minimum privileges required by users to create virtual machines. - " DataStore > Allocate Space" - " Virtual Machine > Configuration > Add New Disk" - " Virtual Machine > Configuration > Add or Remove Device" - " Virtual Machine > Inventory > Create New" - " Network > Assign Network" - " Resource > Assign Virtual Machine to Resource Pool" - "Module may require additional privileges as well, which may be required for gathering facts - e.g. ESXi configurations." - Tested on vSphere 5.5, 6.0, 6.5 and 6.7 - Use SCSI disks instead of IDE when you want to expand online disks by specifing a SCSI controller - "For additional information please visit Ansible VMware community wiki - U(https://github.com/ansible/community/wiki/VMware)." options: state: description: - Specify the state the virtual machine should be in. - 'If C(state) is set to C(present) and virtual machine exists, ensure the virtual machine configurations conforms to task arguments.' - 'If C(state) is set to C(absent) and virtual machine exists, then the specified virtual machine is removed with its associated components.' - 'If C(state) is set to one of the following C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended) and virtual machine does not exists, then virtual machine is deployed with given parameters.' - 'If C(state) is set to C(poweredon) and virtual machine exists with powerstate other than powered on, then the specified virtual machine is powered on.' - 'If C(state) is set to C(poweredoff) and virtual machine exists with powerstate other than powered off, then the specified virtual machine is powered off.' - 'If C(state) is set to C(restarted) and virtual machine exists, then the virtual machine is restarted.' - 'If C(state) is set to C(suspended) and virtual machine exists, then the virtual machine is set to suspended mode.' - 'If C(state) is set to C(shutdownguest) and virtual machine exists, then the virtual machine is shutdown.' - 'If C(state) is set to C(rebootguest) and virtual machine exists, then the virtual machine is rebooted.' default: present choices: [ present, absent, poweredon, poweredoff, restarted, suspended, shutdownguest, rebootguest ] name: description: - Name of the virtual machine to work with. - Virtual machine names in vCenter are not necessarily unique, which may be problematic, see C(name_match). - 'If multiple virtual machines with same name exists, then C(folder) is required parameter to identify uniqueness of the virtual machine.' - This parameter is required, if C(state) is set to C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended) and virtual machine does not exists. - This parameter is case sensitive. required: yes name_match: description: - If multiple virtual machines matching the name, use the first or last found. default: 'first' choices: [ first, last ] uuid: description: - UUID of the virtual machine to manage if known, this is VMware's unique identifier. - This is required if C(name) is not supplied. - If virtual machine does not exists, then this parameter is ignored. - Please note that a supplied UUID will be ignored on virtual machine creation, as VMware creates the UUID internally. template: description: - Template or existing virtual machine used to create new virtual machine. - If this value is not set, virtual machine is created without using a template. - If the virtual machine already exists, this parameter will be ignored. - This parameter is case sensitive. - You can also specify template or VM UUID for identifying source. version_added 2.8. Use C(hw_product_uuid) from M(vmware_guest_facts) as UUID value. - From version 2.8 onwards, absolute path to virtual machine or template can be used. aliases: [ 'template_src' ] is_template: description: - Flag the instance as a template. - This will mark the given virtual machine as template. default: 'no' type: bool version_added: '2.3' folder: description: - Destination folder, absolute path to find an existing guest or create the new guest. - The folder should include the datacenter. ESX's datacenter is ha-datacenter. - This parameter is case sensitive. - This parameter is required, while deploying new virtual machine. version_added 2.5. - 'If multiple machines are found with same name, this parameter is used to identify uniqueness of the virtual machine. version_added 2.5' - 'Examples:' - ' folder: /ha-datacenter/vm' - ' folder: ha-datacenter/vm' - ' folder: /datacenter1/vm' - ' folder: datacenter1/vm' - ' folder: /datacenter1/vm/folder1' - ' folder: datacenter1/vm/folder1' - ' folder: /folder1/datacenter1/vm' - ' folder: folder1/datacenter1/vm' - ' folder: /folder1/datacenter1/vm/folder2' hardware: description: - Manage virtual machine's hardware attributes. - All parameters case sensitive. - 'Valid attributes are:' - ' - C(hotadd_cpu) (boolean): Allow virtual CPUs to be added while the virtual machine is running.' - ' - C(hotremove_cpu) (boolean): Allow virtual CPUs to be removed while the virtual machine is running. version_added: 2.5' - ' - C(hotadd_memory) (boolean): Allow memory to be added while the virtual machine is running.' - ' - C(memory_mb) (integer): Amount of memory in MB.' - ' - C(nested_virt) (bool): Enable nested virtualization. version_added: 2.5' - ' - C(num_cpus) (integer): Number of CPUs.' - ' - C(num_cpu_cores_per_socket) (integer): Number of Cores Per Socket. Value should be multiple of C(num_cpus).' - ' - C(scsi) (string): Valid values are C(buslogic), C(lsilogic), C(lsilogicsas) and C(paravirtual) (default).' - ' - C(memory_reservation) (integer): Amount of memory in MB to set resource limits for memory. version_added: 2.5' - " - C(memory_reservation_lock) (boolean): If set true, memory resource reservation for the virtual machine will always be equal to the virtual machine's memory size. version_added: 2.5" - ' - C(max_connections) (integer): Maximum number of active remote display connections for the virtual machines. version_added: 2.5.' - ' - C(mem_limit) (integer): The memory utilization of a virtual machine will not exceed this limit. Unit is MB. version_added: 2.5' - ' - C(mem_reservation) (integer): The amount of memory resource that is guaranteed available to the virtual machine. Unit is MB. version_added: 2.5' - ' - C(cpu_limit) (integer): The CPU utilization of a virtual machine will not exceed this limit. Unit is MHz. version_added: 2.5' - ' - C(cpu_reservation) (integer): The amount of CPU resource that is guaranteed available to the virtual machine. Unit is MHz. version_added: 2.5' - ' - C(version) (integer): The Virtual machine hardware versions. Default is 10 (ESXi 5.5 and onwards). Please check VMware documentation for correct virtual machine hardware version. Incorrect hardware version may lead to failure in deployment. If hardware version is already equal to the given version then no action is taken. version_added: 2.6' - ' - C(boot_firmware) (string): Choose which firmware should be used to boot the virtual machine. Allowed values are "bios" and "efi". version_added: 2.7' - ' - C(virt_based_security) (bool): Enable Virtualization Based Security feature for Windows 10. (Support from Virtual machine hardware version 14, Guest OS Windows 10 64 bit, Windows Server 2016)' guest_id: description: - Set the guest ID. - This parameter is case sensitive. - 'Examples:' - " virtual machine with RHEL7 64 bit, will be 'rhel7_64Guest'" - " virtual machine with CensOS 64 bit, will be 'centos64Guest'" - " virtual machine with Ubuntu 64 bit, will be 'ubuntu64Guest'" - This field is required when creating a virtual machine. - > Valid values are referenced here: U(http://pubs.vmware.com/vsphere-6-5/topic/com.vmware.wssdk.apiref.doc/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html) version_added: '2.3' disk: description: - A list of disks to add. - This parameter is case sensitive. - Shrinking disks is not supported. - Removing existing disks of the virtual machine is not supported. - 'Valid attributes are:' - ' - C(size_[tb,gb,mb,kb]) (integer): Disk storage size in specified unit.' - ' - C(type) (string): Valid values are:' - ' - C(thin) thin disk' - ' - C(eagerzeroedthick) eagerzeroedthick disk, added in version 2.5' - ' Default: C(None) thick disk, no eagerzero.' - ' - C(datastore) (string): The name of datastore which will be used for the disk. If C(autoselect_datastore) is set to True, then will select the less used datastore whose name contains this "disk.datastore" string.' - ' - C(filename) (string): Existing disk image to be used. Filename must be already exists on the datastore.' - ' Specify filename string in C([datastore_name] path/to/file.vmdk) format. Added in version 2.8.' - ' - C(autoselect_datastore) (bool): select the less used datastore. "disk.datastore" and "disk.autoselect_datastore" will not be used if C(datastore) is specified outside this C(disk) configuration.' - ' - C(disk_mode) (string): Type of disk mode. Added in version 2.6' - ' - Available options are :' - ' - C(persistent): Changes are immediately and permanently written to the virtual disk. This is default.' - ' - C(independent_persistent): Same as persistent, but not affected by snapshots.' - ' - C(independent_nonpersistent): Changes to virtual disk are made to a redo log and discarded at power off, but not affected by snapshots.' cdrom: description: - A CD-ROM configuration for the virtual machine. - 'Valid attributes are:' - ' - C(type) (string): The type of CD-ROM, valid options are C(none), C(client) or C(iso). With C(none) the CD-ROM will be disconnected but present.' - ' - C(iso_path) (string): The datastore path to the ISO file to use, in the form of C([datastore1] path/to/file.iso). Required if type is set C(iso).' version_added: '2.5' resource_pool: description: - Use the given resource pool for virtual machine operation. - This parameter is case sensitive. - Resource pool should be child of the selected host parent. version_added: '2.3' wait_for_ip_address: description: - Wait until vCenter detects an IP address for the virtual machine. - This requires vmware-tools (vmtoolsd) to properly work after creation. - "vmware-tools needs to be installed on the given virtual machine in order to work with this parameter." default: 'no' type: bool wait_for_customization: description: - Wait until vCenter detects all guest customizations as successfully completed. - When enabled, the VM will automatically be powered on. default: 'no' type: bool version_added: '2.8' state_change_timeout: description: - If the C(state) is set to C(shutdownguest), by default the module will return immediately after sending the shutdown signal. - If this argument is set to a positive integer, the module will instead wait for the virtual machine to reach the poweredoff state. - The value sets a timeout in seconds for the module to wait for the state change. default: 0 version_added: '2.6' snapshot_src: description: - Name of the existing snapshot to use to create a clone of a virtual machine. - This parameter is case sensitive. - While creating linked clone using C(linked_clone) parameter, this parameter is required. version_added: '2.4' linked_clone: description: - Whether to create a linked clone from the snapshot specified. - If specified, then C(snapshot_src) is required parameter. default: 'no' type: bool version_added: '2.4' force: description: - Ignore warnings and complete the actions. - This parameter is useful while removing virtual machine which is powered on state. - 'This module reflects the VMware vCenter API and UI workflow, as such, in some cases the `force` flag will be mandatory to perform the action to ensure you are certain the action has to be taken, no matter what the consequence. This is specifically the case for removing a powered on the virtual machine when C(state) is set to C(absent).' default: 'no' type: bool datacenter: description: - Destination datacenter for the deploy operation. - This parameter is case sensitive. default: ha-datacenter cluster: description: - The cluster name where the virtual machine will run. - This is a required parameter, if C(esxi_hostname) is not set. - C(esxi_hostname) and C(cluster) are mutually exclusive parameters. - This parameter is case sensitive. version_added: '2.3' esxi_hostname: description: - The ESXi hostname where the virtual machine will run. - This is a required parameter, if C(cluster) is not set. - C(esxi_hostname) and C(cluster) are mutually exclusive parameters. - This parameter is case sensitive. annotation: description: - A note or annotation to include in the virtual machine. version_added: '2.3' customvalues: description: - Define a list of custom values to set on virtual machine. - A custom value object takes two fields C(key) and C(value). - Incorrect key and values will be ignored. version_added: '2.3' networks: description: - A list of networks (in the order of the NICs). - Removing NICs is not allowed, while reconfiguring the virtual machine. - All parameters and VMware object names are case sensetive. - 'One of the below parameters is required per entry:' - ' - C(name) (string): Name of the portgroup or distributed virtual portgroup for this interface. When specifying distributed virtual portgroup make sure given C(esxi_hostname) or C(cluster) is associated with it.' - ' - C(vlan) (integer): VLAN number for this interface.' - 'Optional parameters per entry (used for virtual hardware):' - ' - C(device_type) (string): Virtual network device (one of C(e1000), C(e1000e), C(pcnet32), C(vmxnet2), C(vmxnet3) (default), C(sriov)).' - ' - C(mac) (string): Customize MAC address.' - ' - C(dvswitch_name) (string): Name of the distributed vSwitch. This value is required if multiple distributed portgroups exists with the same name. version_added 2.7' - ' - C(start_connected) (bool): Indicates that virtual network adapter starts with associated virtual machine powers on. version_added: 2.5' - 'Optional parameters per entry (used for OS customization):' - ' - C(type) (string): Type of IP assignment (either C(dhcp) or C(static)). C(dhcp) is default.' - ' - C(ip) (string): Static IP address (implies C(type: static)).' - ' - C(netmask) (string): Static netmask required for C(ip).' - ' - C(gateway) (string): Static gateway.' - ' - C(dns_servers) (string): DNS servers for this network interface (Windows).' - ' - C(domain) (string): Domain name for this network interface (Windows).' - ' - C(wake_on_lan) (bool): Indicates if wake-on-LAN is enabled on this virtual network adapter. version_added: 2.5' - ' - C(allow_guest_control) (bool): Enables guest control over whether the connectable device is connected. version_added: 2.5' version_added: '2.3' customization: description: - Parameters for OS customization when cloning from the template or the virtual machine, or apply to the existing virtual machine directly. - Not all operating systems are supported for customization with respective vCenter version, please check VMware documentation for respective OS customization. - For supported customization operating system matrix, (see U(http://partnerweb.vmware.com/programs/guestOS/guest-os-customization-matrix.pdf)) - All parameters and VMware object names are case sensitive. - Linux based OSes requires Perl package to be installed for OS customizations. - 'Common parameters (Linux/Windows):' - ' - C(existing_vm) (bool): If set to C(True), do OS customization on the specified virtual machine directly. If set to C(False) or not specified, do OS customization when cloning from the template or the virtual machine. version_added: 2.8' - ' - C(dns_servers) (list): List of DNS servers to configure.' - ' - C(dns_suffix) (list): List of domain suffixes, also known as DNS search path (default: C(domain) parameter).' - ' - C(domain) (string): DNS domain name to use.' - ' - C(hostname) (string): Computer hostname (default: shorted C(name) parameter). Allowed characters are alphanumeric (uppercase and lowercase) and minus, rest of the characters are dropped as per RFC 952.' - 'Parameters related to Windows customization:' - ' - C(autologon) (bool): Auto logon after virtual machine customization (default: False).' - ' - C(autologoncount) (int): Number of autologon after reboot (default: 1).' - ' - C(domainadmin) (string): User used to join in AD domain (mandatory with C(joindomain)).' - ' - C(domainadminpassword) (string): Password used to join in AD domain (mandatory with C(joindomain)).' - ' - C(fullname) (string): Server owner name (default: Administrator).' - ' - C(joindomain) (string): AD domain to join (Not compatible with C(joinworkgroup)).' - ' - C(joinworkgroup) (string): Workgroup to join (Not compatible with C(joindomain), default: WORKGROUP).' - ' - C(orgname) (string): Organisation name (default: ACME).' - ' - C(password) (string): Local administrator password.' - ' - C(productid) (string): Product ID.' - ' - C(runonce) (list): List of commands to run at first user logon.' - ' - C(timezone) (int): Timezone (See U(https://msdn.microsoft.com/en-us/library/ms912391.aspx)).' version_added: '2.3' vapp_properties: description: - A list of vApp properties - 'For full list of attributes and types refer to: U(https://github.com/vmware/pyvmomi/blob/master/docs/vim/vApp/PropertyInfo.rst)' - 'Basic attributes are:' - ' - C(id) (string): Property id - required.' - ' - C(value) (string): Property value.' - ' - C(type) (string): Value type, string type by default.' - ' - C(operation): C(remove): This attribute is required only when removing properties.' version_added: '2.6' customization_spec: description: - Unique name identifying the requested customization specification. - This parameter is case sensitive. - If set, then overrides C(customization) parameter values. version_added: '2.6' datastore: description: - Specify datastore or datastore cluster to provision virtual machine. - 'This parameter takes precedence over "disk.datastore" parameter.' - 'This parameter can be used to override datastore or datastore cluster setting of the virtual machine when deployed from the template.' - Please see example for more usage. version_added: '2.7' convert: description: - Specify convert disk type while cloning template or virtual machine. choices: [ thin, thick, eagerzeroedthick ] version_added: '2.8' extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Create a virtual machine on given ESXi hostname vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no folder: /DC1/vm/ name: test_vm_0001 state: poweredon guest_id: centos64Guest # This is hostname of particular ESXi server on which user wants VM to be deployed esxi_hostname: "{{ esxi_hostname }}" disk: - size_gb: 10 type: thin datastore: datastore1 hardware: memory_mb: 512 num_cpus: 4 scsi: paravirtual networks: - name: VM Network mac: aa:bb:dd:aa:00:14 ip: 10.10.10.100 netmask: 255.255.255.0 device_type: vmxnet3 wait_for_ip_address: yes delegate_to: localhost register: deploy_vm - name: Create a virtual machine from a template vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no folder: /testvms name: testvm_2 state: poweredon template: template_el7 disk: - size_gb: 10 type: thin datastore: g73_datastore hardware: memory_mb: 512 num_cpus: 6 num_cpu_cores_per_socket: 3 scsi: paravirtual memory_reservation: 512 memory_reservation_lock: True mem_limit: 8096 mem_reservation: 4096 cpu_limit: 8096 cpu_reservation: 4096 max_connections: 5 hotadd_cpu: True hotremove_cpu: True hotadd_memory: False version: 12 # Hardware version of virtual machine boot_firmware: "efi" cdrom: type: iso iso_path: "[datastore1] livecd.iso" networks: - name: VM Network mac: aa:bb:dd:aa:00:14 wait_for_ip_address: yes delegate_to: localhost register: deploy - name: Clone a virtual machine from Windows template and customize vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: datacenter1 cluster: cluster name: testvm-2 template: template_windows networks: - name: VM Network ip: 192.168.1.100 netmask: 255.255.255.0 gateway: 192.168.1.1 mac: aa:bb:dd:aa:00:14 domain: my_domain dns_servers: - 192.168.1.1 - 192.168.1.2 - vlan: 1234 type: dhcp customization: autologon: yes dns_servers: - 192.168.1.1 - 192.168.1.2 domain: my_domain password: new_vm_password runonce: - powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP delegate_to: localhost - name: Clone a virtual machine from Linux template and customize vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: "{{ datacenter }}" state: present folder: /DC1/vm template: "{{ template }}" name: "{{ vm_name }}" cluster: DC1_C1 networks: - name: VM Network ip: 192.168.10.11 netmask: 255.255.255.0 wait_for_ip_address: True customization: domain: "{{ guest_domain }}" dns_servers: - 8.9.9.9 - 7.8.8.9 dns_suffix: - example.com - example2.com delegate_to: localhost - name: Rename a virtual machine (requires the virtual machine's uuid) vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" name: new_name state: present delegate_to: localhost - name: Remove a virtual machine by uuid vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" state: absent delegate_to: localhost - name: Manipulate vApp properties vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no name: vm_name state: present vapp_properties: - id: remoteIP category: Backup label: Backup server IP type: str value: 10.10.10.1 - id: old_property operation: remove delegate_to: localhost - name: Set powerstate of a virtual machine to poweroff by using UUID vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no uuid: "{{ vm_uuid }}" state: poweredoff delegate_to: localhost - name: Deploy a virtual machine in a datastore different from the datastore of the template vmware_guest: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" name: "{{ vm_name }}" state: present template: "{{ template_name }}" # Here datastore can be different which holds template datastore: "{{ virtual_machine_datastore }}" hardware: memory_mb: 512 num_cpus: 2 scsi: paravirtual delegate_to: localhost ''' RETURN = r''' instance: description: metadata about the new virtual machine returned: always type: dict sample: None ''' import re import time import string HAS_PYVMOMI = False try: from pyVmomi import vim, vmodl, VmomiSupport HAS_PYVMOMI = True except ImportError: pass from random import randint from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_text, to_native from ansible.module_utils.vmware import (find_obj, gather_vm_facts, get_all_objs, compile_folder_path_for_object, serialize_spec, vmware_argument_spec, set_vm_power_state, PyVmomi, find_dvs_by_name, find_dvspg_by_name, wait_for_vm_ip, wait_for_task, TaskError) class PyVmomiDeviceHelper(object): """ This class is a helper to create easily VMWare Objects for PyVmomiHelper """ def __init__(self, module): self.module = module self.next_disk_unit_number = 0 self.scsi_device_type = { 'lsilogic': vim.vm.device.VirtualLsiLogicController, 'paravirtual': vim.vm.device.ParaVirtualSCSIController, 'buslogic': vim.vm.device.VirtualBusLogicController, 'lsilogicsas': vim.vm.device.VirtualLsiLogicSASController, } def create_scsi_controller(self, scsi_type): scsi_ctl = vim.vm.device.VirtualDeviceSpec() scsi_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add scsi_device = self.scsi_device_type.get(scsi_type, vim.vm.device.ParaVirtualSCSIController) scsi_ctl.device = scsi_device() scsi_ctl.device.busNumber = 0 # While creating a new SCSI controller, temporary key value # should be unique negative integers scsi_ctl.device.key = -randint(1000, 9999) scsi_ctl.device.hotAddRemove = True scsi_ctl.device.sharedBus = 'noSharing' scsi_ctl.device.scsiCtlrUnitNumber = 7 return scsi_ctl def is_scsi_controller(self, device): return isinstance(device, tuple(self.scsi_device_type.values())) @staticmethod def create_ide_controller(): ide_ctl = vim.vm.device.VirtualDeviceSpec() ide_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add ide_ctl.device = vim.vm.device.VirtualIDEController() ide_ctl.device.deviceInfo = vim.Description() # While creating a new IDE controller, temporary key value # should be unique negative integers ide_ctl.device.key = -randint(200, 299) ide_ctl.device.busNumber = 0 return ide_ctl @staticmethod def create_cdrom(ide_ctl, cdrom_type, iso_path=None): cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add cdrom_spec.device = vim.vm.device.VirtualCdrom() cdrom_spec.device.controllerKey = ide_ctl.device.key cdrom_spec.device.key = -1 cdrom_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() cdrom_spec.device.connectable.allowGuestControl = True cdrom_spec.device.connectable.startConnected = (cdrom_type != "none") if cdrom_type in ["none", "client"]: cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo() elif cdrom_type == "iso": cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path) return cdrom_spec @staticmethod def is_equal_cdrom(vm_obj, cdrom_device, cdrom_type, iso_path): if cdrom_type == "none": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and cdrom_device.connectable.allowGuestControl and not cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or not cdrom_device.connectable.connected)) elif cdrom_type == "client": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and cdrom_device.connectable.allowGuestControl and cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected)) elif cdrom_type == "iso": return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.IsoBackingInfo) and cdrom_device.backing.fileName == iso_path and cdrom_device.connectable.allowGuestControl and cdrom_device.connectable.startConnected and (vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected)) def create_scsi_disk(self, scsi_ctl, disk_index=None): diskspec = vim.vm.device.VirtualDeviceSpec() diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add diskspec.device = vim.vm.device.VirtualDisk() diskspec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() diskspec.device.controllerKey = scsi_ctl.device.key if self.next_disk_unit_number == 7: raise AssertionError() if disk_index == 7: raise AssertionError() """ Configure disk unit number. """ if disk_index is not None: diskspec.device.unitNumber = disk_index self.next_disk_unit_number = disk_index + 1 else: diskspec.device.unitNumber = self.next_disk_unit_number self.next_disk_unit_number += 1 # unit number 7 is reserved to SCSI controller, increase next index if self.next_disk_unit_number == 7: self.next_disk_unit_number += 1 return diskspec def get_device(self, device_type, name): nic_dict = dict(pcnet32=vim.vm.device.VirtualPCNet32(), vmxnet2=vim.vm.device.VirtualVmxnet2(), vmxnet3=vim.vm.device.VirtualVmxnet3(), e1000=vim.vm.device.VirtualE1000(), e1000e=vim.vm.device.VirtualE1000e(), sriov=vim.vm.device.VirtualSriovEthernetCard(), ) if device_type in nic_dict: return nic_dict[device_type] else: self.module.fail_json(msg='Invalid device_type "%s"' ' for network "%s"' % (device_type, name)) def create_nic(self, device_type, device_label, device_infos): nic = vim.vm.device.VirtualDeviceSpec() nic.device = self.get_device(device_type, device_infos['name']) nic.device.wakeOnLanEnabled = bool(device_infos.get('wake_on_lan', True)) nic.device.deviceInfo = vim.Description() nic.device.deviceInfo.label = device_label nic.device.deviceInfo.summary = device_infos['name'] nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() nic.device.connectable.startConnected = bool(device_infos.get('start_connected', True)) nic.device.connectable.allowGuestControl = bool(device_infos.get('allow_guest_control', True)) nic.device.connectable.connected = True if 'mac' in device_infos and self.is_valid_mac_addr(device_infos['mac']): nic.device.addressType = 'manual' nic.device.macAddress = device_infos['mac'] else: nic.device.addressType = 'generated' return nic @staticmethod def is_valid_mac_addr(mac_addr): """ Function to validate MAC address for given string Args: mac_addr: string to validate as MAC address Returns: (Boolean) True if string is valid MAC address, otherwise False """ mac_addr_regex = re.compile('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$') return bool(mac_addr_regex.match(mac_addr)) def integer_value(self, input_value, name): """ Function to return int value for given input, else return error Args: input_value: Input value to retrive int value from name: Name of the Input value (used to build error message) Returns: (int) if integer value can be obtained, otherwise will send a error message. """ if isinstance(input_value, int): return input_value elif isinstance(input_value, str) and input_value.isdigit(): return int(input_value) else: self.module.fail_json(msg='"%s" attribute should be an' ' integer value.' % name) class PyVmomiCache(object): """ This class caches references to objects which are requested multiples times but not modified """ def __init__(self, content, dc_name=None): self.content = content self.dc_name = dc_name self.networks = {} self.clusters = {} self.esx_hosts = {} self.parent_datacenters = {} def find_obj(self, content, types, name, confine_to_datacenter=True): """ Wrapper around find_obj to set datacenter context """ result = find_obj(content, types, name) if result and confine_to_datacenter: if to_text(self.get_parent_datacenter(result).name) != to_text(self.dc_name): result = None objects = self.get_all_objs(content, types, confine_to_datacenter=True) for obj in objects: if name is None or to_text(obj.name) == to_text(name): return obj return result def get_all_objs(self, content, types, confine_to_datacenter=True): """ Wrapper around get_all_objs to set datacenter context """ objects = get_all_objs(content, types) if confine_to_datacenter: if hasattr(objects, 'items'): # resource pools come back as a dictionary # make a copy tmpobjs = objects.copy() for k, v in objects.items(): parent_dc = self.get_parent_datacenter(k) if parent_dc.name != self.dc_name: tmpobjs.pop(k, None) objects = tmpobjs else: # everything else should be a list objects = [x for x in objects if self.get_parent_datacenter(x).name == self.dc_name] return objects def get_network(self, network): if network not in self.networks: self.networks[network] = self.find_obj(self.content, [vim.Network], network) return self.networks[network] def get_cluster(self, cluster): if cluster not in self.clusters: self.clusters[cluster] = self.find_obj(self.content, [vim.ClusterComputeResource], cluster) return self.clusters[cluster] def get_esx_host(self, host): if host not in self.esx_hosts: self.esx_hosts[host] = self.find_obj(self.content, [vim.HostSystem], host) return self.esx_hosts[host] def get_parent_datacenter(self, obj): """ Walk the parent tree to find the objects datacenter """ if isinstance(obj, vim.Datacenter): return obj if obj in self.parent_datacenters: return self.parent_datacenters[obj] datacenter = None while True: if not hasattr(obj, 'parent'): break obj = obj.parent if isinstance(obj, vim.Datacenter): datacenter = obj break self.parent_datacenters[obj] = datacenter return datacenter class PyVmomiHelper(PyVmomi): def __init__(self, module): super(PyVmomiHelper, self).__init__(module) self.device_helper = PyVmomiDeviceHelper(self.module) self.configspec = None self.change_detected = False # a change was detected and needs to be applied through reconfiguration self.change_applied = False # a change was applied meaning at least one task succeeded self.customspec = None self.cache = PyVmomiCache(self.content, dc_name=self.params['datacenter']) def gather_facts(self, vm): return gather_vm_facts(self.content, vm) def remove_vm(self, vm): # https://www.vmware.com/support/developer/converter-sdk/conv60_apireference/vim.ManagedEntity.html#destroy if vm.summary.runtime.powerState.lower() == 'poweredon': self.module.fail_json(msg="Virtual machine %s found in 'powered on' state, " "please use 'force' parameter to remove or poweroff VM " "and try removing VM again." % vm.name) task = vm.Destroy() self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'destroy'} else: return {'changed': self.change_applied, 'failed': False} def configure_guestid(self, vm_obj, vm_creation=False): # guest_id is not required when using templates if self.params['template'] and not self.params['guest_id']: return # guest_id is only mandatory on VM creation if vm_creation and self.params['guest_id'] is None: self.module.fail_json(msg="guest_id attribute is mandatory for VM creation") if self.params['guest_id'] and \ (vm_obj is None or self.params['guest_id'].lower() != vm_obj.summary.config.guestId.lower()): self.change_detected = True self.configspec.guestId = self.params['guest_id'] def configure_resource_alloc_info(self, vm_obj): """ Function to configure resource allocation information about virtual machine :param vm_obj: VM object in case of reconfigure, None in case of deploy :return: None """ rai_change_detected = False memory_allocation = vim.ResourceAllocationInfo() cpu_allocation = vim.ResourceAllocationInfo() if 'hardware' in self.params: if 'mem_limit' in self.params['hardware']: mem_limit = None try: mem_limit = int(self.params['hardware'].get('mem_limit')) except ValueError: self.module.fail_json(msg="hardware.mem_limit attribute should be an integer value.") memory_allocation.limit = mem_limit if vm_obj is None or memory_allocation.limit != vm_obj.config.memoryAllocation.limit: rai_change_detected = True if 'mem_reservation' in self.params['hardware']: mem_reservation = None try: mem_reservation = int(self.params['hardware'].get('mem_reservation')) except ValueError: self.module.fail_json(msg="hardware.mem_reservation should be an integer value.") memory_allocation.reservation = mem_reservation if vm_obj is None or \ memory_allocation.reservation != vm_obj.config.memoryAllocation.reservation: rai_change_detected = True if 'cpu_limit' in self.params['hardware']: cpu_limit = None try: cpu_limit = int(self.params['hardware'].get('cpu_limit')) except ValueError: self.module.fail_json(msg="hardware.cpu_limit attribute should be an integer value.") cpu_allocation.limit = cpu_limit if vm_obj is None or cpu_allocation.limit != vm_obj.config.cpuAllocation.limit: rai_change_detected = True if 'cpu_reservation' in self.params['hardware']: cpu_reservation = None try: cpu_reservation = int(self.params['hardware'].get('cpu_reservation')) except ValueError: self.module.fail_json(msg="hardware.cpu_reservation should be an integer value.") cpu_allocation.reservation = cpu_reservation if vm_obj is None or \ cpu_allocation.reservation != vm_obj.config.cpuAllocation.reservation: rai_change_detected = True if rai_change_detected: self.configspec.memoryAllocation = memory_allocation self.configspec.cpuAllocation = cpu_allocation self.change_detected = True def configure_cpu_and_memory(self, vm_obj, vm_creation=False): # set cpu/memory/etc if 'hardware' in self.params: if 'num_cpus' in self.params['hardware']: try: num_cpus = int(self.params['hardware']['num_cpus']) except ValueError: self.module.fail_json(msg="hardware.num_cpus attribute should be an integer value.") # check VM power state and cpu hot-add/hot-remove state before re-config VM if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: if not vm_obj.config.cpuHotRemoveEnabled and num_cpus < vm_obj.config.hardware.numCPU: self.module.fail_json(msg="Configured cpu number is less than the cpu number of the VM, " "cpuHotRemove is not enabled") if not vm_obj.config.cpuHotAddEnabled and num_cpus > vm_obj.config.hardware.numCPU: self.module.fail_json(msg="Configured cpu number is more than the cpu number of the VM, " "cpuHotAdd is not enabled") if 'num_cpu_cores_per_socket' in self.params['hardware']: try: num_cpu_cores_per_socket = int(self.params['hardware']['num_cpu_cores_per_socket']) except ValueError: self.module.fail_json(msg="hardware.num_cpu_cores_per_socket attribute " "should be an integer value.") if num_cpus % num_cpu_cores_per_socket != 0: self.module.fail_json(msg="hardware.num_cpus attribute should be a multiple " "of hardware.num_cpu_cores_per_socket") self.configspec.numCoresPerSocket = num_cpu_cores_per_socket if vm_obj is None or self.configspec.numCoresPerSocket != vm_obj.config.hardware.numCoresPerSocket: self.change_detected = True self.configspec.numCPUs = num_cpus if vm_obj is None or self.configspec.numCPUs != vm_obj.config.hardware.numCPU: self.change_detected = True # num_cpu is mandatory for VM creation elif vm_creation and not self.params['template']: self.module.fail_json(msg="hardware.num_cpus attribute is mandatory for VM creation") if 'memory_mb' in self.params['hardware']: try: memory_mb = int(self.params['hardware']['memory_mb']) except ValueError: self.module.fail_json(msg="Failed to parse hardware.memory_mb value." " Please refer the documentation and provide" " correct value.") # check VM power state and memory hotadd state before re-config VM if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: if vm_obj.config.memoryHotAddEnabled and memory_mb < vm_obj.config.hardware.memoryMB: self.module.fail_json(msg="Configured memory is less than memory size of the VM, " "operation is not supported") elif not vm_obj.config.memoryHotAddEnabled and memory_mb != vm_obj.config.hardware.memoryMB: self.module.fail_json(msg="memoryHotAdd is not enabled") self.configspec.memoryMB = memory_mb if vm_obj is None or self.configspec.memoryMB != vm_obj.config.hardware.memoryMB: self.change_detected = True # memory_mb is mandatory for VM creation elif vm_creation and not self.params['template']: self.module.fail_json(msg="hardware.memory_mb attribute is mandatory for VM creation") if 'hotadd_memory' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.memoryHotAddEnabled != bool(self.params['hardware']['hotadd_memory']): self.module.fail_json(msg="Configure hotadd memory operation is not supported when VM is power on") self.configspec.memoryHotAddEnabled = bool(self.params['hardware']['hotadd_memory']) if vm_obj is None or self.configspec.memoryHotAddEnabled != vm_obj.config.memoryHotAddEnabled: self.change_detected = True if 'hotadd_cpu' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.cpuHotAddEnabled != bool(self.params['hardware']['hotadd_cpu']): self.module.fail_json(msg="Configure hotadd cpu operation is not supported when VM is power on") self.configspec.cpuHotAddEnabled = bool(self.params['hardware']['hotadd_cpu']) if vm_obj is None or self.configspec.cpuHotAddEnabled != vm_obj.config.cpuHotAddEnabled: self.change_detected = True if 'hotremove_cpu' in self.params['hardware']: if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \ vm_obj.config.cpuHotRemoveEnabled != bool(self.params['hardware']['hotremove_cpu']): self.module.fail_json(msg="Configure hotremove cpu operation is not supported when VM is power on") self.configspec.cpuHotRemoveEnabled = bool(self.params['hardware']['hotremove_cpu']) if vm_obj is None or self.configspec.cpuHotRemoveEnabled != vm_obj.config.cpuHotRemoveEnabled: self.change_detected = True if 'memory_reservation' in self.params['hardware']: memory_reservation_mb = 0 try: memory_reservation_mb = int(self.params['hardware']['memory_reservation']) except ValueError as e: self.module.fail_json(msg="Failed to set memory_reservation value." "Valid value for memory_reservation value in MB (integer): %s" % e) mem_alloc = vim.ResourceAllocationInfo() mem_alloc.reservation = memory_reservation_mb self.configspec.memoryAllocation = mem_alloc if vm_obj is None or self.configspec.memoryAllocation.reservation != vm_obj.config.memoryAllocation.reservation: self.change_detected = True if 'memory_reservation_lock' in self.params['hardware']: self.configspec.memoryReservationLockedToMax = bool(self.params['hardware']['memory_reservation_lock']) if vm_obj is None or self.configspec.memoryReservationLockedToMax != vm_obj.config.memoryReservationLockedToMax: self.change_detected = True if 'boot_firmware' in self.params['hardware']: # boot firmware re-config can cause boot issue if vm_obj is not None: return boot_firmware = self.params['hardware']['boot_firmware'].lower() if boot_firmware not in ('bios', 'efi'): self.module.fail_json(msg="hardware.boot_firmware value is invalid [%s]." " Need one of ['bios', 'efi']." % boot_firmware) self.configspec.firmware = boot_firmware self.change_detected = True def configure_cdrom(self, vm_obj): # Configure the VM CD-ROM if "cdrom" in self.params and self.params["cdrom"]: if "type" not in self.params["cdrom"] or self.params["cdrom"]["type"] not in ["none", "client", "iso"]: self.module.fail_json(msg="cdrom.type is mandatory") if self.params["cdrom"]["type"] == "iso" and ("iso_path" not in self.params["cdrom"] or not self.params["cdrom"]["iso_path"]): self.module.fail_json(msg="cdrom.iso_path is mandatory in case cdrom.type is iso") if vm_obj and vm_obj.config.template: # Changing CD-ROM settings on a template is not supported return cdrom_spec = None cdrom_device = self.get_vm_cdrom_device(vm=vm_obj) iso_path = self.params["cdrom"]["iso_path"] if "iso_path" in self.params["cdrom"] else None if cdrom_device is None: # Creating new CD-ROM ide_device = self.get_vm_ide_device(vm=vm_obj) if ide_device is None: # Creating new IDE device ide_device = self.device_helper.create_ide_controller() self.change_detected = True self.configspec.deviceChange.append(ide_device) elif len(ide_device.device) > 3: self.module.fail_json(msg="hardware.cdrom specified for a VM or template which already has 4 IDE devices of which none are a cdrom") cdrom_spec = self.device_helper.create_cdrom(ide_ctl=ide_device, cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path) if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: cdrom_spec.device.connectable.connected = (self.params["cdrom"]["type"] != "none") elif not self.device_helper.is_equal_cdrom(vm_obj=vm_obj, cdrom_device=cdrom_device, cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path): # Updating an existing CD-ROM if self.params["cdrom"]["type"] in ["client", "none"]: cdrom_device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo() elif self.params["cdrom"]["type"] == "iso": cdrom_device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path) cdrom_device.connectable = vim.vm.device.VirtualDevice.ConnectInfo() cdrom_device.connectable.allowGuestControl = True cdrom_device.connectable.startConnected = (self.params["cdrom"]["type"] != "none") if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: cdrom_device.connectable.connected = (self.params["cdrom"]["type"] != "none") cdrom_spec = vim.vm.device.VirtualDeviceSpec() cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit cdrom_spec.device = cdrom_device if cdrom_spec: self.change_detected = True self.configspec.deviceChange.append(cdrom_spec) def configure_hardware_params(self, vm_obj): """ Function to configure hardware related configuration of virtual machine Args: vm_obj: virtual machine object """ if 'hardware' in self.params: if 'max_connections' in self.params['hardware']: # maxMksConnections == max_connections self.configspec.maxMksConnections = int(self.params['hardware']['max_connections']) if vm_obj is None or self.configspec.maxMksConnections != vm_obj.config.hardware.maxMksConnections: self.change_detected = True if 'nested_virt' in self.params['hardware']: self.configspec.nestedHVEnabled = bool(self.params['hardware']['nested_virt']) if vm_obj is None or self.configspec.nestedHVEnabled != bool(vm_obj.config.nestedHVEnabled): self.change_detected = True if 'version' in self.params['hardware']: hw_version_check_failed = False temp_version = self.params['hardware'].get('version', 10) try: temp_version = int(temp_version) except ValueError: hw_version_check_failed = True if temp_version not in range(3, 15): hw_version_check_failed = True if hw_version_check_failed: self.module.fail_json(msg="Failed to set hardware.version '%s' value as valid" " values range from 3 (ESX 2.x) to 14 (ESXi 6.5 and greater)." % temp_version) # Hardware version is denoted as "vmx-10" version = "vmx-%02d" % temp_version self.configspec.version = version if vm_obj is None or self.configspec.version != vm_obj.config.version: self.change_detected = True if vm_obj is not None: # VM exists and we need to update the hardware version current_version = vm_obj.config.version # current_version = "vmx-10" version_digit = int(current_version.split("-", 1)[-1]) if temp_version < version_digit: self.module.fail_json(msg="Current hardware version '%d' which is greater than the specified" " version '%d'. Downgrading hardware version is" " not supported. Please specify version greater" " than the current version." % (version_digit, temp_version)) new_version = "vmx-%02d" % temp_version try: task = vm_obj.UpgradeVM_Task(new_version) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'upgrade'} except vim.fault.AlreadyUpgraded: # Don't fail if VM is already upgraded. pass if 'virt_based_security' in self.params['hardware']: host_version = self.select_host().summary.config.product.version if int(host_version.split('.')[0]) < 6 or (int(host_version.split('.')[0]) == 6 and int(host_version.split('.')[1]) < 7): self.module.fail_json(msg="ESXi version %s not support VBS." % host_version) guest_ids = ['windows9_64Guest', 'windows9Server64Guest'] if vm_obj is None: guestid = self.configspec.guestId else: guestid = vm_obj.summary.config.guestId if guestid not in guest_ids: self.module.fail_json(msg="Guest '%s' not support VBS." % guestid) if (vm_obj is None and int(self.configspec.version.split('-')[1]) >= 14) or \ (vm_obj and int(vm_obj.config.version.split('-')[1]) >= 14 and (vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOff)): self.configspec.flags = vim.vm.FlagInfo() self.configspec.flags.vbsEnabled = bool(self.params['hardware']['virt_based_security']) if bool(self.params['hardware']['virt_based_security']): self.configspec.flags.vvtdEnabled = True self.configspec.nestedHVEnabled = True if (vm_obj is None and self.configspec.firmware == 'efi') or \ (vm_obj and vm_obj.config.firmware == 'efi'): self.configspec.bootOptions = vim.vm.BootOptions() self.configspec.bootOptions.efiSecureBootEnabled = True else: self.module.fail_json(msg="Not support VBS when firmware is BIOS.") if vm_obj is None or self.configspec.flags.vbsEnabled != vm_obj.config.flags.vbsEnabled: self.change_detected = True def get_device_by_type(self, vm=None, type=None): if vm is None or type is None: return None for device in vm.config.hardware.device: if isinstance(device, type): return device return None def get_vm_cdrom_device(self, vm=None): return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualCdrom) def get_vm_ide_device(self, vm=None): return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualIDEController) def get_vm_network_interfaces(self, vm=None): device_list = [] if vm is None: return device_list nw_device_types = (vim.vm.device.VirtualPCNet32, vim.vm.device.VirtualVmxnet2, vim.vm.device.VirtualVmxnet3, vim.vm.device.VirtualE1000, vim.vm.device.VirtualE1000e, vim.vm.device.VirtualSriovEthernetCard) for device in vm.config.hardware.device: if isinstance(device, nw_device_types): device_list.append(device) return device_list def sanitize_network_params(self): """ Sanitize user provided network provided params Returns: A sanitized list of network params, else fails """ network_devices = list() # Clean up user data here for network in self.params['networks']: if 'name' not in network and 'vlan' not in network: self.module.fail_json(msg="Please specify at least a network name or" " a VLAN name under VM network list.") if 'name' in network and self.cache.get_network(network['name']) is None: self.module.fail_json(msg="Network '%(name)s' does not exist." % network) elif 'vlan' in network: dvps = self.cache.get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup]) for dvp in dvps: if hasattr(dvp.config.defaultPortConfig, 'vlan') and \ isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \ str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']): network['name'] = dvp.config.name break if 'dvswitch_name' in network and \ dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \ dvp.config.name == network['vlan']: network['name'] = dvp.config.name break if dvp.config.name == network['vlan']: network['name'] = dvp.config.name break else: self.module.fail_json(msg="VLAN '%(vlan)s' does not exist." % network) if 'type' in network: if network['type'] not in ['dhcp', 'static']: self.module.fail_json(msg="Network type '%(type)s' is not a valid parameter." " Valid parameters are ['dhcp', 'static']." % network) if network['type'] != 'static' and ('ip' in network or 'netmask' in network): self.module.fail_json(msg='Static IP information provided for network "%(name)s",' ' but "type" is set to "%(type)s".' % network) else: # Type is optional parameter, if user provided IP or Subnet assume # network type as 'static' if 'ip' in network or 'netmask' in network: network['type'] = 'static' else: # User wants network type as 'dhcp' network['type'] = 'dhcp' if network.get('type') == 'static': if 'ip' in network and 'netmask' not in network: self.module.fail_json(msg="'netmask' is required if 'ip' is" " specified under VM network list.") if 'ip' not in network and 'netmask' in network: self.module.fail_json(msg="'ip' is required if 'netmask' is" " specified under VM network list.") validate_device_types = ['pcnet32', 'vmxnet2', 'vmxnet3', 'e1000', 'e1000e', 'sriov'] if 'device_type' in network and network['device_type'] not in validate_device_types: self.module.fail_json(msg="Device type specified '%s' is not valid." " Please specify correct device" " type from ['%s']." % (network['device_type'], "', '".join(validate_device_types))) if 'mac' in network and not PyVmomiDeviceHelper.is_valid_mac_addr(network['mac']): self.module.fail_json(msg="Device MAC address '%s' is invalid." " Please provide correct MAC address." % network['mac']) network_devices.append(network) return network_devices def configure_network(self, vm_obj): # Ignore empty networks, this permits to keep networks when deploying a template/cloning a VM if len(self.params['networks']) == 0: return network_devices = self.sanitize_network_params() # List current device for Clone or Idempotency current_net_devices = self.get_vm_network_interfaces(vm=vm_obj) if len(network_devices) < len(current_net_devices): self.module.fail_json(msg="Given network device list is lesser than current VM device list (%d < %d). " "Removing interfaces is not allowed" % (len(network_devices), len(current_net_devices))) for key in range(0, len(network_devices)): nic_change_detected = False network_name = network_devices[key]['name'] if key < len(current_net_devices) and (vm_obj or self.params['template']): # We are editing existing network devices, this is either when # are cloning from VM or Template nic = vim.vm.device.VirtualDeviceSpec() nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit nic.device = current_net_devices[key] if ('wake_on_lan' in network_devices[key] and nic.device.wakeOnLanEnabled != network_devices[key].get('wake_on_lan')): nic.device.wakeOnLanEnabled = network_devices[key].get('wake_on_lan') nic_change_detected = True if ('start_connected' in network_devices[key] and nic.device.connectable.startConnected != network_devices[key].get('start_connected')): nic.device.connectable.startConnected = network_devices[key].get('start_connected') nic_change_detected = True if ('allow_guest_control' in network_devices[key] and nic.device.connectable.allowGuestControl != network_devices[key].get('allow_guest_control')): nic.device.connectable.allowGuestControl = network_devices[key].get('allow_guest_control') nic_change_detected = True if nic.device.deviceInfo.summary != network_name: nic.device.deviceInfo.summary = network_name nic_change_detected = True if 'device_type' in network_devices[key]: device = self.device_helper.get_device(network_devices[key]['device_type'], network_name) device_class = type(device) if not isinstance(nic.device, device_class): self.module.fail_json(msg="Changing the device type is not possible when interface is already present. " "The failing device type is %s" % network_devices[key]['device_type']) # Changing mac address has no effect when editing interface if 'mac' in network_devices[key] and nic.device.macAddress != current_net_devices[key].macAddress: self.module.fail_json(msg="Changing MAC address has not effect when interface is already present. " "The failing new MAC address is %s" % nic.device.macAddress) else: # Default device type is vmxnet3, VMWare best practice device_type = network_devices[key].get('device_type', 'vmxnet3') nic = self.device_helper.create_nic(device_type, 'Network Adapter %s' % (key + 1), network_devices[key]) nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add nic_change_detected = True if hasattr(self.cache.get_network(network_name), 'portKeys'): # VDS switch pg_obj = None if 'dvswitch_name' in network_devices[key]: dvs_name = network_devices[key]['dvswitch_name'] dvs_obj = find_dvs_by_name(self.content, dvs_name) if dvs_obj is None: self.module.fail_json(msg="Unable to find distributed virtual switch %s" % dvs_name) pg_obj = find_dvspg_by_name(dvs_obj, network_name) if pg_obj is None: self.module.fail_json(msg="Unable to find distributed port group %s" % network_name) else: pg_obj = self.cache.find_obj(self.content, [vim.dvs.DistributedVirtualPortgroup], network_name) if (nic.device.backing and (not hasattr(nic.device.backing, 'port') or (nic.device.backing.port.portgroupKey != pg_obj.key or nic.device.backing.port.switchUuid != pg_obj.config.distributedVirtualSwitch.uuid))): nic_change_detected = True dvs_port_connection = vim.dvs.PortConnection() dvs_port_connection.portgroupKey = pg_obj.key # If user specifies distributed port group without associating to the hostsystem on which # virtual machine is going to be deployed then we get error. We can infer that there is no # association between given distributed port group and host system. host_system = self.params.get('esxi_hostname') if host_system and host_system not in [host.config.host.name for host in pg_obj.config.distributedVirtualSwitch.config.host]: self.module.fail_json(msg="It seems that host system '%s' is not associated with distributed" " virtual portgroup '%s'. Please make sure host system is associated" " with given distributed virtual portgroup" % (host_system, pg_obj.name)) # TODO: (akasurde) There is no way to find association between resource pool and distributed virtual portgroup # For now, check if we are able to find distributed virtual switch if not pg_obj.config.distributedVirtualSwitch: self.module.fail_json(msg="Failed to find distributed virtual switch which is associated with" " distributed virtual portgroup '%s'. Make sure hostsystem is associated with" " the given distributed virtual portgroup." % pg_obj.name) dvs_port_connection.switchUuid = pg_obj.config.distributedVirtualSwitch.uuid nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo() nic.device.backing.port = dvs_port_connection elif isinstance(self.cache.get_network(network_name), vim.OpaqueNetwork): # NSX-T Logical Switch nic.device.backing = vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo() network_id = self.cache.get_network(network_name).summary.opaqueNetworkId nic.device.backing.opaqueNetworkType = 'nsx.LogicalSwitch' nic.device.backing.opaqueNetworkId = network_id nic.device.deviceInfo.summary = 'nsx.LogicalSwitch: %s' % network_id else: # vSwitch if not isinstance(nic.device.backing, vim.vm.device.VirtualEthernetCard.NetworkBackingInfo): nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo() nic_change_detected = True net_obj = self.cache.get_network(network_name) if nic.device.backing.network != net_obj: nic.device.backing.network = net_obj nic_change_detected = True if nic.device.backing.deviceName != network_name: nic.device.backing.deviceName = network_name nic_change_detected = True if nic_change_detected: self.configspec.deviceChange.append(nic) self.change_detected = True def configure_vapp_properties(self, vm_obj): if len(self.params['vapp_properties']) == 0: return for x in self.params['vapp_properties']: if not x.get('id'): self.module.fail_json(msg="id is required to set vApp property") new_vmconfig_spec = vim.vApp.VmConfigSpec() # This is primarily for vcsim/integration tests, unset vAppConfig was not seen on my deployments orig_spec = vm_obj.config.vAppConfig if vm_obj.config.vAppConfig else new_vmconfig_spec vapp_properties_current = dict((x.id, x) for x in orig_spec.property) vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties']) # each property must have a unique key # init key counter with max value + 1 all_keys = [x.key for x in orig_spec.property] new_property_index = max(all_keys) + 1 if all_keys else 0 for property_id, property_spec in vapp_properties_to_change.items(): is_property_changed = False new_vapp_property_spec = vim.vApp.PropertySpec() if property_id in vapp_properties_current: if property_spec.get('operation') == 'remove': new_vapp_property_spec.operation = 'remove' new_vapp_property_spec.removeKey = vapp_properties_current[property_id].key is_property_changed = True else: # this is 'edit' branch new_vapp_property_spec.operation = 'edit' new_vapp_property_spec.info = vapp_properties_current[property_id] try: for property_name, property_value in property_spec.items(): if property_name == 'operation': # operation is not an info object property # if set to anything other than 'remove' we don't fail continue # Updating attributes only if needed if getattr(new_vapp_property_spec.info, property_name) != property_value: setattr(new_vapp_property_spec.info, property_name, property_value) is_property_changed = True except Exception as e: self.module.fail_json(msg="Failed to set vApp property field='%s' and value='%s'. Error: %s" % (property_name, property_value, to_text(e))) else: if property_spec.get('operation') == 'remove': # attemp to delete non-existent property continue # this is add new property branch new_vapp_property_spec.operation = 'add' property_info = vim.vApp.PropertyInfo() property_info.classId = property_spec.get('classId') property_info.instanceId = property_spec.get('instanceId') property_info.id = property_spec.get('id') property_info.category = property_spec.get('category') property_info.label = property_spec.get('label') property_info.type = property_spec.get('type', 'string') property_info.userConfigurable = property_spec.get('userConfigurable', True) property_info.defaultValue = property_spec.get('defaultValue') property_info.value = property_spec.get('value', '') property_info.description = property_spec.get('description') new_vapp_property_spec.info = property_info new_vapp_property_spec.info.key = new_property_index new_property_index += 1 is_property_changed = True if is_property_changed: new_vmconfig_spec.property.append(new_vapp_property_spec) if new_vmconfig_spec.property: self.configspec.vAppConfig = new_vmconfig_spec self.change_detected = True def customize_customvalues(self, vm_obj, config_spec): if len(self.params['customvalues']) == 0: return vm_custom_spec = config_spec vm_custom_spec.extraConfig = [] changed = False facts = self.gather_facts(vm_obj) for kv in self.params['customvalues']: if 'key' not in kv or 'value' not in kv: self.module.exit_json(msg="customvalues items required both 'key' and 'value fields.") # If kv is not kv fetched from facts, change it if kv['key'] not in facts['customvalues'] or facts['customvalues'][kv['key']] != kv['value']: option = vim.option.OptionValue() option.key = kv['key'] option.value = kv['value'] vm_custom_spec.extraConfig.append(option) changed = True if changed: self.change_detected = True def customize_vm(self, vm_obj): # User specified customization specification custom_spec_name = self.params.get('customization_spec') if custom_spec_name: cc_mgr = self.content.customizationSpecManager if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name): temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name) self.customspec = temp_spec.spec return else: self.module.fail_json(msg="Unable to find customization specification" " '%s' in given configuration." % custom_spec_name) # Network settings adaptermaps = [] for network in self.params['networks']: guest_map = vim.vm.customization.AdapterMapping() guest_map.adapter = vim.vm.customization.IPSettings() if 'ip' in network and 'netmask' in network: guest_map.adapter.ip = vim.vm.customization.FixedIp() guest_map.adapter.ip.ipAddress = str(network['ip']) guest_map.adapter.subnetMask = str(network['netmask']) elif 'type' in network and network['type'] == 'dhcp': guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator() if 'gateway' in network: guest_map.adapter.gateway = network['gateway'] # On Windows, DNS domain and DNS servers can be set by network interface # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html if 'domain' in network: guest_map.adapter.dnsDomain = network['domain'] elif 'domain' in self.params['customization']: guest_map.adapter.dnsDomain = self.params['customization']['domain'] if 'dns_servers' in network: guest_map.adapter.dnsServerList = network['dns_servers'] elif 'dns_servers' in self.params['customization']: guest_map.adapter.dnsServerList = self.params['customization']['dns_servers'] adaptermaps.append(guest_map) # Global DNS settings globalip = vim.vm.customization.GlobalIPSettings() if 'dns_servers' in self.params['customization']: globalip.dnsServerList = self.params['customization']['dns_servers'] # TODO: Maybe list the different domains from the interfaces here by default ? if 'dns_suffix' in self.params['customization']: dns_suffix = self.params['customization']['dns_suffix'] if isinstance(dns_suffix, list): globalip.dnsSuffixList = " ".join(dns_suffix) else: globalip.dnsSuffixList = dns_suffix elif 'domain' in self.params['customization']: globalip.dnsSuffixList = self.params['customization']['domain'] if self.params['guest_id']: guest_id = self.params['guest_id'] else: guest_id = vm_obj.summary.config.guestId # For windows guest OS, use SysPrep # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail if 'win' in guest_id: ident = vim.vm.customization.Sysprep() ident.userData = vim.vm.customization.UserData() # Setting hostName, orgName and fullName is mandatory, so we set some default when missing ident.userData.computerName = vim.vm.customization.FixedName() # computer name will be truncated to 15 characters if using VM name default_name = self.params['name'].translate(None, string.punctuation) ident.userData.computerName.name = str(self.params['customization'].get('hostname', default_name[0:15])) ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator')) ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME')) if 'productid' in self.params['customization']: ident.userData.productId = str(self.params['customization']['productid']) ident.guiUnattended = vim.vm.customization.GuiUnattended() if 'autologon' in self.params['customization']: ident.guiUnattended.autoLogon = self.params['customization']['autologon'] ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1) if 'timezone' in self.params['customization']: # Check if timezone value is a int before proceeding. ident.guiUnattended.timeZone = self.device_helper.integer_value( self.params['customization']['timezone'], 'customization.timezone') ident.identification = vim.vm.customization.Identification() if self.params['customization'].get('password', '') != '': ident.guiUnattended.password = vim.vm.customization.Password() ident.guiUnattended.password.value = str(self.params['customization']['password']) ident.guiUnattended.password.plainText = True if 'joindomain' in self.params['customization']: if 'domainadmin' not in self.params['customization'] or 'domainadminpassword' not in self.params['customization']: self.module.fail_json(msg="'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use " "joindomain feature") ident.identification.domainAdmin = str(self.params['customization']['domainadmin']) ident.identification.joinDomain = str(self.params['customization']['joindomain']) ident.identification.domainAdminPassword = vim.vm.customization.Password() ident.identification.domainAdminPassword.value = str(self.params['customization']['domainadminpassword']) ident.identification.domainAdminPassword.plainText = True elif 'joinworkgroup' in self.params['customization']: ident.identification.joinWorkgroup = str(self.params['customization']['joinworkgroup']) if 'runonce' in self.params['customization']: ident.guiRunOnce = vim.vm.customization.GuiRunOnce() ident.guiRunOnce.commandList = self.params['customization']['runonce'] else: # FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail! # For Linux guest OS, use LinuxPrep # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html ident = vim.vm.customization.LinuxPrep() # TODO: Maybe add domain from interface if missing ? if 'domain' in self.params['customization']: ident.domain = str(self.params['customization']['domain']) ident.hostName = vim.vm.customization.FixedName() hostname = str(self.params['customization'].get('hostname', self.params['name'].split('.')[0])) # Remove all characters except alphanumeric and minus which is allowed by RFC 952 valid_hostname = re.sub(r"[^a-zA-Z0-9\-]", "", hostname) ident.hostName.name = valid_hostname self.customspec = vim.vm.customization.Specification() self.customspec.nicSettingMap = adaptermaps self.customspec.globalIPSettings = globalip self.customspec.identity = ident def get_vm_scsi_controller(self, vm_obj): # If vm_obj doesn't exist there is no SCSI controller to find if vm_obj is None: return None for device in vm_obj.config.hardware.device: if self.device_helper.is_scsi_controller(device): scsi_ctl = vim.vm.device.VirtualDeviceSpec() scsi_ctl.device = device return scsi_ctl return None def get_configured_disk_size(self, expected_disk_spec): # what size is it? if [x for x in expected_disk_spec.keys() if x.startswith('size_') or x == 'size']: # size, size_tb, size_gb, size_mb, size_kb if 'size' in expected_disk_spec: size_regex = re.compile(r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])') disk_size_m = size_regex.match(expected_disk_spec['size']) try: if disk_size_m: expected = disk_size_m.group(1) unit = disk_size_m.group(2) else: raise ValueError if re.match(r'\d+\.\d+', expected): # We found float value in string, let's typecast it expected = float(expected) else: # We found int value in string, let's typecast it expected = int(expected) if not expected or not unit: raise ValueError except (TypeError, ValueError, NameError): # Common failure self.module.fail_json(msg="Failed to parse disk size please review value" " provided using documentation.") else: param = [x for x in expected_disk_spec.keys() if x.startswith('size_')][0] unit = param.split('_')[-1].lower() expected = [x[1] for x in expected_disk_spec.items() if x[0].startswith('size_')][0] expected = int(expected) disk_units = dict(tb=3, gb=2, mb=1, kb=0) if unit in disk_units: unit = unit.lower() return expected * (1024 ** disk_units[unit]) else: self.module.fail_json(msg="%s is not a supported unit for disk size." " Supported units are ['%s']." % (unit, "', '".join(disk_units.keys()))) # No size found but disk, fail self.module.fail_json( msg="No size, size_kb, size_mb, size_gb or size_tb attribute found into disk configuration") def find_vmdk(self, vmdk_path): """ Takes a vsphere datastore path in the format [datastore_name] path/to/file.vmdk Returns vsphere file object or raises RuntimeError """ datastore_name, vmdk_fullpath, vmdk_filename, vmdk_folder = self.vmdk_disk_path_split(vmdk_path) datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) if datastore is None: self.module.fail_json(msg="Failed to find the datastore %s" % datastore_name) return self.find_vmdk_file(datastore, vmdk_fullpath, vmdk_filename, vmdk_folder) def add_existing_vmdk(self, vm_obj, expected_disk_spec, diskspec, scsi_ctl): """ Adds vmdk file described by expected_disk_spec['filename'], retrieves the file information and adds the correct spec to self.configspec.deviceChange. """ filename = expected_disk_spec['filename'] # if this is a new disk, or the disk file names are different if (vm_obj and diskspec.device.backing.fileName != filename) or vm_obj is None: vmdk_file = self.find_vmdk(expected_disk_spec['filename']) diskspec.device.backing.fileName = expected_disk_spec['filename'] diskspec.device.capacityInKB = VmomiSupport.vmodlTypes['long'](vmdk_file.fileSize / 1024) diskspec.device.key = -1 self.change_detected = True self.configspec.deviceChange.append(diskspec) def configure_disks(self, vm_obj): # Ignore empty disk list, this permits to keep disks when deploying a template/cloning a VM if len(self.params['disk']) == 0: return scsi_ctl = self.get_vm_scsi_controller(vm_obj) # Create scsi controller only if we are deploying a new VM, not a template or reconfiguring if vm_obj is None or scsi_ctl is None: scsi_ctl = self.device_helper.create_scsi_controller(self.get_scsi_type()) self.change_detected = True self.configspec.deviceChange.append(scsi_ctl) disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] \ if vm_obj is not None else None if disks is not None and self.params.get('disk') and len(self.params.get('disk')) < len(disks): self.module.fail_json(msg="Provided disks configuration has less disks than " "the target object (%d vs %d)" % (len(self.params.get('disk')), len(disks))) disk_index = 0 for expected_disk_spec in self.params.get('disk'): disk_modified = False # If we are manipulating and existing objects which has disks and disk_index is in disks if vm_obj is not None and disks is not None and disk_index < len(disks): diskspec = vim.vm.device.VirtualDeviceSpec() # set the operation to edit so that it knows to keep other settings diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit diskspec.device = disks[disk_index] else: diskspec = self.device_helper.create_scsi_disk(scsi_ctl, disk_index) disk_modified = True # increment index for next disk search disk_index += 1 # index 7 is reserved to SCSI controller if disk_index == 7: disk_index += 1 if 'disk_mode' in expected_disk_spec: disk_mode = expected_disk_spec.get('disk_mode', 'persistent').lower() valid_disk_mode = ['persistent', 'independent_persistent', 'independent_nonpersistent'] if disk_mode not in valid_disk_mode: self.module.fail_json(msg="disk_mode specified is not valid." " Should be one of ['%s']" % "', '".join(valid_disk_mode)) if (vm_obj and diskspec.device.backing.diskMode != disk_mode) or (vm_obj is None): diskspec.device.backing.diskMode = disk_mode disk_modified = True else: diskspec.device.backing.diskMode = "persistent" # is it thin? if 'type' in expected_disk_spec: disk_type = expected_disk_spec.get('type', '').lower() if disk_type == 'thin': diskspec.device.backing.thinProvisioned = True elif disk_type == 'eagerzeroedthick': diskspec.device.backing.eagerlyScrub = True if 'filename' in expected_disk_spec and expected_disk_spec['filename'] is not None: self.add_existing_vmdk(vm_obj, expected_disk_spec, diskspec, scsi_ctl) continue elif vm_obj is None: # We are creating new VM diskspec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create # which datastore? if expected_disk_spec.get('datastore'): # TODO: This is already handled by the relocation spec, # but it needs to eventually be handled for all the # other disks defined pass kb = self.get_configured_disk_size(expected_disk_spec) # VMWare doesn't allow to reduce disk sizes if kb < diskspec.device.capacityInKB: self.module.fail_json( msg="Given disk size is smaller than found (%d < %d). Reducing disks is not allowed." % (kb, diskspec.device.capacityInKB)) if kb != diskspec.device.capacityInKB or disk_modified: diskspec.device.capacityInKB = kb self.configspec.deviceChange.append(diskspec) self.change_detected = True def select_host(self): hostsystem = self.cache.get_esx_host(self.params['esxi_hostname']) if not hostsystem: self.module.fail_json(msg='Failed to find ESX host "%(esxi_hostname)s"' % self.params) if hostsystem.runtime.connectionState != 'connected' or hostsystem.runtime.inMaintenanceMode: self.module.fail_json(msg='ESXi "%(esxi_hostname)s" is in invalid state or in maintenance mode.' % self.params) return hostsystem def autoselect_datastore(self): datastore = None datastores = self.cache.get_all_objs(self.content, [vim.Datastore]) if datastores is None or len(datastores) == 0: self.module.fail_json(msg="Unable to find a datastore list when autoselecting") datastore_freespace = 0 for ds in datastores: if ds.summary.freeSpace > datastore_freespace: datastore = ds datastore_freespace = ds.summary.freeSpace return datastore def get_recommended_datastore(self, datastore_cluster_obj=None): """ Function to return Storage DRS recommended datastore from datastore cluster Args: datastore_cluster_obj: datastore cluster managed object Returns: Name of recommended datastore from the given datastore cluster """ if datastore_cluster_obj is None: return None # Check if Datastore Cluster provided by user is SDRS ready sdrs_status = datastore_cluster_obj.podStorageDrsEntry.storageDrsConfig.podConfig.enabled if sdrs_status: # We can get storage recommendation only if SDRS is enabled on given datastorage cluster pod_sel_spec = vim.storageDrs.PodSelectionSpec() pod_sel_spec.storagePod = datastore_cluster_obj storage_spec = vim.storageDrs.StoragePlacementSpec() storage_spec.podSelectionSpec = pod_sel_spec storage_spec.type = 'create' try: rec = self.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec) rec_action = rec.recommendations[0].action[0] return rec_action.destination.name except Exception: # There is some error so we fall back to general workflow pass datastore = None datastore_freespace = 0 for ds in datastore_cluster_obj.childEntity: if isinstance(ds, vim.Datastore) and ds.summary.freeSpace > datastore_freespace: # If datastore field is provided, filter destination datastores datastore = ds datastore_freespace = ds.summary.freeSpace if datastore: return datastore.name return None def select_datastore(self, vm_obj=None): datastore = None datastore_name = None if len(self.params['disk']) != 0: # TODO: really use the datastore for newly created disks if 'autoselect_datastore' in self.params['disk'][0] and self.params['disk'][0]['autoselect_datastore']: datastores = self.cache.get_all_objs(self.content, [vim.Datastore]) datastores = [x for x in datastores if self.cache.get_parent_datacenter(x).name == self.params['datacenter']] if datastores is None or len(datastores) == 0: self.module.fail_json(msg="Unable to find a datastore list when autoselecting") datastore_freespace = 0 for ds in datastores: if (ds.summary.freeSpace > datastore_freespace) or (ds.summary.freeSpace == datastore_freespace and not datastore): # If datastore field is provided, filter destination datastores if 'datastore' in self.params['disk'][0] and \ isinstance(self.params['disk'][0]['datastore'], str) and \ ds.name.find(self.params['disk'][0]['datastore']) < 0: continue datastore = ds datastore_name = datastore.name datastore_freespace = ds.summary.freeSpace elif 'datastore' in self.params['disk'][0]: datastore_name = self.params['disk'][0]['datastore'] # Check if user has provided datastore cluster first datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name) if datastore_cluster: # If user specified datastore cluster so get recommended datastore datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster) # Check if get_recommended_datastore or user specified datastore exists or not datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) else: self.module.fail_json(msg="Either datastore or autoselect_datastore should be provided to select datastore") if not datastore and self.params['template']: # use the template's existing DS disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] if disks: datastore = disks[0].backing.datastore datastore_name = datastore.name # validation if datastore: dc = self.cache.get_parent_datacenter(datastore) if dc.name != self.params['datacenter']: datastore = self.autoselect_datastore() datastore_name = datastore.name if not datastore: if len(self.params['disk']) != 0 or self.params['template'] is None: self.module.fail_json(msg="Unable to find the datastore with given parameters." " This could mean, %s is a non-existent virtual machine and module tried to" " deploy it as new virtual machine with no disk. Please specify disks parameter" " or specify template to clone from." % self.params['name']) self.module.fail_json(msg="Failed to find a matching datastore") return datastore, datastore_name def obj_has_parent(self, obj, parent): if obj is None and parent is None: raise AssertionError() current_parent = obj while True: if current_parent.name == parent.name: return True # Check if we have reached till root folder moid = current_parent._moId if moid in ['group-d1', 'ha-folder-root']: return False current_parent = current_parent.parent if current_parent is None: return False def get_scsi_type(self): disk_controller_type = "paravirtual" # set cpu/memory/etc if 'hardware' in self.params: if 'scsi' in self.params['hardware']: if self.params['hardware']['scsi'] in ['buslogic', 'paravirtual', 'lsilogic', 'lsilogicsas']: disk_controller_type = self.params['hardware']['scsi'] else: self.module.fail_json(msg="hardware.scsi attribute should be 'paravirtual' or 'lsilogic'") return disk_controller_type def find_folder(self, searchpath): """ Walk inventory objects one position of the searchpath at a time """ # split the searchpath so we can iterate through it paths = [x.replace('/', '') for x in searchpath.split('/')] paths_total = len(paths) - 1 position = 0 # recursive walk while looking for next element in searchpath root = self.content.rootFolder while root and position <= paths_total: change = False if hasattr(root, 'childEntity'): for child in root.childEntity: if child.name == paths[position]: root = child position += 1 change = True break elif isinstance(root, vim.Datacenter): if hasattr(root, 'vmFolder'): if root.vmFolder.name == paths[position]: root = root.vmFolder position += 1 change = True else: root = None if not change: root = None return root def get_resource_pool(self, cluster=None, host=None, resource_pool=None): """ Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given """ cluster_name = cluster or self.params.get('cluster', None) host_name = host or self.params.get('esxi_hostname', None) resource_pool_name = resource_pool or self.params.get('resource_pool', None) # get the datacenter object datacenter = find_obj(self.content, [vim.Datacenter], self.params['datacenter']) if not datacenter: self.module.fail_json(msg='Unable to find datacenter "%s"' % self.params['datacenter']) # if cluster is given, get the cluster object if cluster_name: cluster = find_obj(self.content, [vim.ComputeResource], cluster_name, folder=datacenter) if not cluster: self.module.fail_json(msg='Unable to find cluster "%s"' % cluster_name) # if host is given, get the cluster object using the host elif host_name: host = find_obj(self.content, [vim.HostSystem], host_name, folder=datacenter) if not host: self.module.fail_json(msg='Unable to find host "%s"' % host_name) cluster = host.parent else: cluster = None # get resource pools limiting search to cluster or datacenter resource_pool = find_obj(self.content, [vim.ResourcePool], resource_pool_name, folder=cluster or datacenter) if not resource_pool: if resource_pool_name: self.module.fail_json(msg='Unable to find resource_pool "%s"' % resource_pool_name) else: self.module.fail_json(msg='Unable to find resource pool, need esxi_hostname, resource_pool, or cluster') return resource_pool def deploy_vm(self): # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/clone_vm.py # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.CloneSpec.html # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.ConfigSpec.html # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html # FIXME: # - static IPs self.folder = self.params.get('folder', None) if self.folder is None: self.module.fail_json(msg="Folder is required parameter while deploying new virtual machine") # Prepend / if it was missing from the folder path, also strip trailing slashes if not self.folder.startswith('/'): self.folder = '/%(folder)s' % self.params self.folder = self.folder.rstrip('/') datacenter = self.cache.find_obj(self.content, [vim.Datacenter], self.params['datacenter']) if datacenter is None: self.module.fail_json(msg='No datacenter named %(datacenter)s was found' % self.params) dcpath = compile_folder_path_for_object(datacenter) # Nested folder does not have trailing / if not dcpath.endswith('/'): dcpath += '/' # Check for full path first in case it was already supplied if (self.folder.startswith(dcpath + self.params['datacenter'] + '/vm') or self.folder.startswith(dcpath + '/' + self.params['datacenter'] + '/vm')): fullpath = self.folder elif self.folder.startswith('/vm/') or self.folder == '/vm': fullpath = "%s%s%s" % (dcpath, self.params['datacenter'], self.folder) elif self.folder.startswith('/'): fullpath = "%s%s/vm%s" % (dcpath, self.params['datacenter'], self.folder) else: fullpath = "%s%s/vm/%s" % (dcpath, self.params['datacenter'], self.folder) f_obj = self.content.searchIndex.FindByInventoryPath(fullpath) # abort if no strategy was successful if f_obj is None: # Add some debugging values in failure. details = { 'datacenter': datacenter.name, 'datacenter_path': dcpath, 'folder': self.folder, 'full_search_path': fullpath, } self.module.fail_json(msg='No folder %s matched in the search path : %s' % (self.folder, fullpath), details=details) destfolder = f_obj if self.params['template']: vm_obj = self.get_vm_or_template(template_name=self.params['template']) if vm_obj is None: self.module.fail_json(msg="Could not find a template named %(template)s" % self.params) else: vm_obj = None # always get a resource_pool resource_pool = self.get_resource_pool() # set the destination datastore for VM & disks if self.params['datastore']: # Give precedence to datastore value provided by user # User may want to deploy VM to specific datastore. datastore_name = self.params['datastore'] # Check if user has provided datastore cluster first datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name) if datastore_cluster: # If user specified datastore cluster so get recommended datastore datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster) # Check if get_recommended_datastore or user specified datastore exists or not datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name) else: (datastore, datastore_name) = self.select_datastore(vm_obj) self.configspec = vim.vm.ConfigSpec() self.configspec.deviceChange = [] self.configure_guestid(vm_obj=vm_obj, vm_creation=True) self.configure_cpu_and_memory(vm_obj=vm_obj, vm_creation=True) self.configure_hardware_params(vm_obj=vm_obj) self.configure_resource_alloc_info(vm_obj=vm_obj) self.configure_disks(vm_obj=vm_obj) self.configure_network(vm_obj=vm_obj) self.configure_cdrom(vm_obj=vm_obj) # Find if we need network customizations (find keys in dictionary that requires customizations) network_changes = False for nw in self.params['networks']: for key in nw: # We don't need customizations for these keys if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'): network_changes = True break if len(self.params['customization']) > 0 or network_changes or self.params.get('customization_spec') is not None: self.customize_vm(vm_obj=vm_obj) clonespec = None clone_method = None try: if self.params['template']: # create the relocation spec relospec = vim.vm.RelocateSpec() # Only select specific host when ESXi hostname is provided if self.params['esxi_hostname']: relospec.host = self.select_host() relospec.datastore = datastore # Convert disk present in template if is set if self.params['convert']: for device in vm_obj.config.hardware.device: if hasattr(device.backing, 'fileName'): disk_locator = vim.vm.RelocateSpec.DiskLocator() disk_locator.diskBackingInfo = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() if self.params['convert'] in ['thin']: disk_locator.diskBackingInfo.thinProvisioned = True if self.params['convert'] in ['eagerzeroedthick']: disk_locator.diskBackingInfo.eagerlyScrub = True if self.params['convert'] in ['thick']: disk_locator.diskBackingInfo.diskMode = "persistent" disk_locator.diskId = device.key disk_locator.datastore = datastore relospec.disk.append(disk_locator) # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html # > pool: For a clone operation from a template to a virtual machine, this argument is required. relospec.pool = resource_pool linked_clone = self.params.get('linked_clone') snapshot_src = self.params.get('snapshot_src', None) if linked_clone: if snapshot_src is not None: relospec.diskMoveType = vim.vm.RelocateSpec.DiskMoveOptions.createNewChildDiskBacking else: self.module.fail_json(msg="Parameter 'linked_src' and 'snapshot_src' are" " required together for linked clone operation.") clonespec = vim.vm.CloneSpec(template=self.params['is_template'], location=relospec) if self.customspec: clonespec.customization = self.customspec if snapshot_src is not None: if vm_obj.snapshot is None: self.module.fail_json(msg="No snapshots present for virtual machine or template [%(template)s]" % self.params) snapshot = self.get_snapshots_by_name_recursively(snapshots=vm_obj.snapshot.rootSnapshotList, snapname=snapshot_src) if len(snapshot) != 1: self.module.fail_json(msg='virtual machine "%(template)s" does not contain' ' snapshot named "%(snapshot_src)s"' % self.params) clonespec.snapshot = snapshot[0].snapshot clonespec.config = self.configspec clone_method = 'Clone' try: task = vm_obj.Clone(folder=destfolder, name=self.params['name'], spec=clonespec) except vim.fault.NoPermission as e: self.module.fail_json(msg="Failed to clone virtual machine %s to folder %s " "due to permission issue: %s" % (self.params['name'], destfolder, to_native(e.msg))) self.change_detected = True else: # ConfigSpec require name for VM creation self.configspec.name = self.params['name'] self.configspec.files = vim.vm.FileInfo(logDirectory=None, snapshotDirectory=None, suspendDirectory=None, vmPathName="[" + datastore_name + "]") clone_method = 'CreateVM_Task' try: task = destfolder.CreateVM_Task(config=self.configspec, pool=resource_pool) except vmodl.fault.InvalidRequest as e: self.module.fail_json(msg="Failed to create virtual machine due to invalid configuration " "parameter %s" % to_native(e.msg)) except vim.fault.RestrictedVersion as e: self.module.fail_json(msg="Failed to create virtual machine due to " "product versioning restrictions: %s" % to_native(e.msg)) self.change_detected = True self.wait_for_task(task) except TypeError as e: self.module.fail_json(msg="TypeError was returned, please ensure to give correct inputs. %s" % to_text(e)) if task.info.state == 'error': # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2021361 # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2173 # provide these to the user for debugging clonespec_json = serialize_spec(clonespec) configspec_json = serialize_spec(self.configspec) kwargs = { 'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'clonespec': clonespec_json, 'configspec': configspec_json, 'clone_method': clone_method } return kwargs else: # set annotation vm = task.info.result if self.params['annotation']: annotation_spec = vim.vm.ConfigSpec() annotation_spec.annotation = str(self.params['annotation']) task = vm.ReconfigVM_Task(annotation_spec) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'annotation'} if self.params['customvalues']: vm_custom_spec = vim.vm.ConfigSpec() self.customize_customvalues(vm_obj=vm, config_spec=vm_custom_spec) task = vm.ReconfigVM_Task(vm_custom_spec) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'customvalues'} if self.params['wait_for_ip_address'] or self.params['wait_for_customization'] or self.params['state'] in ['poweredon', 'restarted']: set_vm_power_state(self.content, vm, 'poweredon', force=False) if self.params['wait_for_ip_address']: self.wait_for_vm_ip(vm) if self.params['wait_for_customization']: is_customization_ok = self.wait_for_customization(vm) if not is_customization_ok: vm_facts = self.gather_facts(vm) return {'changed': self.change_applied, 'failed': True, 'instance': vm_facts, 'op': 'customization'} vm_facts = self.gather_facts(vm) return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts} def get_snapshots_by_name_recursively(self, snapshots, snapname): snap_obj = [] for snapshot in snapshots: if snapshot.name == snapname: snap_obj.append(snapshot) else: snap_obj = snap_obj + self.get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname) return snap_obj def reconfigure_vm(self): self.configspec = vim.vm.ConfigSpec() self.configspec.deviceChange = [] self.configure_guestid(vm_obj=self.current_vm_obj) self.configure_cpu_and_memory(vm_obj=self.current_vm_obj) self.configure_hardware_params(vm_obj=self.current_vm_obj) self.configure_disks(vm_obj=self.current_vm_obj) self.configure_network(vm_obj=self.current_vm_obj) self.configure_cdrom(vm_obj=self.current_vm_obj) self.customize_customvalues(vm_obj=self.current_vm_obj, config_spec=self.configspec) self.configure_resource_alloc_info(vm_obj=self.current_vm_obj) self.configure_vapp_properties(vm_obj=self.current_vm_obj) if self.params['annotation'] and self.current_vm_obj.config.annotation != self.params['annotation']: self.configspec.annotation = str(self.params['annotation']) self.change_detected = True relospec = vim.vm.RelocateSpec() if self.params['resource_pool']: relospec.pool = self.get_resource_pool() if relospec.pool != self.current_vm_obj.resourcePool: task = self.current_vm_obj.RelocateVM_Task(spec=relospec) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'relocate'} # Only send VMWare task if we see a modification if self.change_detected: task = None try: task = self.current_vm_obj.ReconfigVM_Task(spec=self.configspec) except vim.fault.RestrictedVersion as e: self.module.fail_json(msg="Failed to reconfigure virtual machine due to" " product versioning restrictions: %s" % to_native(e.msg)) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'reconfig'} # Rename VM if self.params['uuid'] and self.params['name'] and self.params['name'] != self.current_vm_obj.config.name: task = self.current_vm_obj.Rename_Task(self.params['name']) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'rename'} # Mark VM as Template if self.params['is_template'] and not self.current_vm_obj.config.template: try: self.current_vm_obj.MarkAsTemplate() self.change_applied = True except vmodl.fault.NotSupported as e: self.module.fail_json(msg="Failed to mark virtual machine [%s] " "as template: %s" % (self.params['name'], e.msg)) # Mark Template as VM elif not self.params['is_template'] and self.current_vm_obj.config.template: resource_pool = self.get_resource_pool() kwargs = dict(pool=resource_pool) if self.params.get('esxi_hostname', None): host_system_obj = self.select_host() kwargs.update(host=host_system_obj) try: self.current_vm_obj.MarkAsVirtualMachine(**kwargs) self.change_applied = True except vim.fault.InvalidState as invalid_state: self.module.fail_json(msg="Virtual machine is not marked" " as template : %s" % to_native(invalid_state.msg)) except vim.fault.InvalidDatastore as invalid_ds: self.module.fail_json(msg="Converting template to virtual machine" " operation cannot be performed on the" " target datastores: %s" % to_native(invalid_ds.msg)) except vim.fault.CannotAccessVmComponent as cannot_access: self.module.fail_json(msg="Failed to convert template to virtual machine" " as operation unable access virtual machine" " component: %s" % to_native(cannot_access.msg)) except vmodl.fault.InvalidArgument as invalid_argument: self.module.fail_json(msg="Failed to convert template to virtual machine" " due to : %s" % to_native(invalid_argument.msg)) except Exception as generic_exc: self.module.fail_json(msg="Failed to convert template to virtual machine" " due to generic error : %s" % to_native(generic_exc)) # Automatically update VMWare UUID when converting template to VM. # This avoids an interactive prompt during VM startup. uuid_action = [x for x in self.current_vm_obj.config.extraConfig if x.key == "uuid.action"] if not uuid_action: uuid_action_opt = vim.option.OptionValue() uuid_action_opt.key = "uuid.action" uuid_action_opt.value = "create" self.configspec.extraConfig.append(uuid_action_opt) self.change_detected = True # add customize existing VM after VM re-configure if 'existing_vm' in self.params['customization'] and self.params['customization']['existing_vm']: if self.current_vm_obj.config.template: self.module.fail_json(msg="VM is template, not support guest OS customization.") if self.current_vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff: self.module.fail_json(msg="VM is not in poweroff state, can not do guest OS customization.") cus_result = self.customize_exist_vm() if cus_result['failed']: return cus_result vm_facts = self.gather_facts(self.current_vm_obj) return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts} def customize_exist_vm(self): task = None # Find if we need network customizations (find keys in dictionary that requires customizations) network_changes = False for nw in self.params['networks']: for key in nw: # We don't need customizations for these keys if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'): network_changes = True break if len(self.params['customization']) > 1 or network_changes or self.params.get('customization_spec'): self.customize_vm(vm_obj=self.current_vm_obj) try: task = self.current_vm_obj.CustomizeVM_Task(self.customspec) except vim.fault.CustomizationFault as e: self.module.fail_json(msg="Failed to customization virtual machine due to CustomizationFault: %s" % to_native(e.msg)) except vim.fault.RuntimeFault as e: self.module.fail_json(msg="failed to customization virtual machine due to RuntimeFault: %s" % to_native(e.msg)) except Exception as e: self.module.fail_json(msg="failed to customization virtual machine due to fault: %s" % to_native(e.msg)) self.wait_for_task(task) if task.info.state == 'error': return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'customize_exist'} if self.params['wait_for_customization']: set_vm_power_state(self.content, self.current_vm_obj, 'poweredon', force=False) is_customization_ok = self.wait_for_customization(self.current_vm_obj) if not is_customization_ok: return {'changed': self.change_applied, 'failed': True, 'op': 'wait_for_customize_exist'} return {'changed': self.change_applied, 'failed': False} def wait_for_task(self, task, poll_interval=1): """ Wait for a VMware task to complete. Terminal states are 'error' and 'success'. Inputs: - task: the task to wait for - poll_interval: polling interval to check the task, in seconds Modifies: - self.change_applied """ # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.Task.html # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.TaskInfo.html # https://github.com/virtdevninja/pyvmomi-community-samples/blob/master/samples/tools/tasks.py while task.info.state not in ['error', 'success']: time.sleep(poll_interval) self.change_applied = self.change_applied or task.info.state == 'success' def wait_for_vm_ip(self, vm, poll=100, sleep=5): ips = None facts = {} thispoll = 0 while not ips and thispoll <= poll: newvm = self.get_vm() facts = self.gather_facts(newvm) if facts['ipv4'] or facts['ipv6']: ips = True else: time.sleep(sleep) thispoll += 1 return facts def get_vm_events(self, vm, eventTypeIdList): byEntity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self") filterSpec = vim.event.EventFilterSpec(entity=byEntity, eventTypeId=eventTypeIdList) eventManager = self.content.eventManager return eventManager.QueryEvent(filterSpec) def wait_for_customization(self, vm, poll=10000, sleep=10): thispoll = 0 while thispoll <= poll: eventStarted = self.get_vm_events(vm, ['CustomizationStartedEvent']) if len(eventStarted): thispoll = 0 while thispoll <= poll: eventsFinishedResult = self.get_vm_events(vm, ['CustomizationSucceeded', 'CustomizationFailed']) if len(eventsFinishedResult): if not isinstance(eventsFinishedResult[0], vim.event.CustomizationSucceeded): self.module.fail_json(msg='Customization failed with error {0}:\n{1}'.format( eventsFinishedResult[0]._wsdlName, eventsFinishedResult[0].fullFormattedMessage)) return False break else: time.sleep(sleep) thispoll += 1 return True else: time.sleep(sleep) thispoll += 1 self.module.fail_json('waiting for customizations timed out.') return False def main(): argument_spec = vmware_argument_spec() argument_spec.update( state=dict(type='str', default='present', choices=['absent', 'poweredoff', 'poweredon', 'present', 'rebootguest', 'restarted', 'shutdownguest', 'suspended']), template=dict(type='str', aliases=['template_src']), is_template=dict(type='bool', default=False), annotation=dict(type='str', aliases=['notes']), customvalues=dict(type='list', default=[]), name=dict(type='str'), name_match=dict(type='str', choices=['first', 'last'], default='first'), uuid=dict(type='str'), folder=dict(type='str'), guest_id=dict(type='str'), disk=dict(type='list', default=[]), cdrom=dict(type='dict', default={}), hardware=dict(type='dict', default={}), force=dict(type='bool', default=False), datacenter=dict(type='str', default='ha-datacenter'), esxi_hostname=dict(type='str'), cluster=dict(type='str'), wait_for_ip_address=dict(type='bool', default=False), state_change_timeout=dict(type='int', default=0), snapshot_src=dict(type='str'), linked_clone=dict(type='bool', default=False), networks=dict(type='list', default=[]), resource_pool=dict(type='str'), customization=dict(type='dict', default={}, no_log=True), customization_spec=dict(type='str', default=None), wait_for_customization=dict(type='bool', default=False), vapp_properties=dict(type='list', default=[]), datastore=dict(type='str'), convert=dict(type='str', choices=['thin', 'thick', 'eagerzeroedthick']), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[ ['cluster', 'esxi_hostname'], ], required_one_of=[ ['name', 'uuid'], ], ) result = {'failed': False, 'changed': False} pyv = PyVmomiHelper(module) # Check if the VM exists before continuing vm = pyv.get_vm() # VM already exists if vm: if module.params['state'] == 'absent': # destroy it if module.check_mode: result.update( vm_name=vm.name, changed=True, current_powerstate=vm.summary.runtime.powerState.lower(), desired_operation='remove_vm', ) module.exit_json(**result) if module.params['force']: # has to be poweredoff first set_vm_power_state(pyv.content, vm, 'poweredoff', module.params['force']) result = pyv.remove_vm(vm) elif module.params['state'] == 'present': if module.check_mode: result.update( vm_name=vm.name, changed=True, desired_operation='reconfigure_vm', ) module.exit_json(**result) result = pyv.reconfigure_vm() elif module.params['state'] in ['poweredon', 'poweredoff', 'restarted', 'suspended', 'shutdownguest', 'rebootguest']: if module.check_mode: result.update( vm_name=vm.name, changed=True, current_powerstate=vm.summary.runtime.powerState.lower(), desired_operation='set_vm_power_state', ) module.exit_json(**result) # set powerstate tmp_result = set_vm_power_state(pyv.content, vm, module.params['state'], module.params['force'], module.params['state_change_timeout']) if tmp_result['changed']: result["changed"] = True if module.params['state'] in ['poweredon', 'restarted', 'rebootguest'] and module.params['wait_for_ip_address']: wait_result = wait_for_vm_ip(pyv.content, vm) if not wait_result: module.fail_json(msg='Waiting for IP address timed out') tmp_result['instance'] = wait_result if not tmp_result["failed"]: result["failed"] = False result['instance'] = tmp_result['instance'] else: # This should not happen raise AssertionError() # VM doesn't exist else: if module.params['state'] in ['poweredon', 'poweredoff', 'present', 'restarted', 'suspended']: if module.check_mode: result.update( changed=True, desired_operation='deploy_vm', ) module.exit_json(**result) result = pyv.deploy_vm() if result['failed']: module.fail_json(msg='Failed to create a virtual machine : %s' % result['msg']) if result['failed']: module.fail_json(**result) else: module.exit_json(**result) if __name__ == '__main__': main()
EvanK/ansible
lib/ansible/modules/cloud/vmware/vmware_guest.py
Python
gpl-3.0
134,112
[ "VisIt" ]
35f136c4f5f72c91b51c982e3f504204e7a37bd9635476ee5fd7c1a75e938c84
"""Functions to plot epochs data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # Stefan Repplinger <stefan.repplinger@ovgu.de> # Daniel McCloy <dan@mccloy.info> # # License: Simplified BSD from collections import Counter from copy import deepcopy import warnings import numpy as np from .raw import _setup_channel_selections from ..defaults import _handle_default from ..utils import verbose, logger, warn, fill_doc, _check_option from ..io.meas_info import create_info, _validate_type from ..io.pick import (_get_channel_types, _picks_to_idx, _DATA_CH_TYPES_SPLIT, _VALID_CHANNEL_TYPES) from .utils import (tight_layout, _setup_vmin_vmax, plt_show, _check_cov, _handle_precompute, _compute_scalings, DraggableColorbar, _setup_cmap, _handle_decim, _set_title_multiple_electrodes, _make_combine_callable, _set_window_title, _make_event_color_dict, _get_channel_plotting_order) @fill_doc def plot_epochs_image(epochs, picks=None, sigma=0., vmin=None, vmax=None, colorbar=True, order=None, show=True, units=None, scalings=None, cmap=None, fig=None, axes=None, overlay_times=None, combine=None, group_by=None, evoked=True, ts_args=None, title=None, clear=False): """Plot Event Related Potential / Fields image. Parameters ---------- epochs : instance of Epochs The epochs. %(picks_good_data)s ``picks`` interacts with ``group_by`` and ``combine`` to determine the number of figures generated; see Notes. sigma : float The standard deviation of a Gaussian smoothing window applied along the epochs axis of the image. If 0, no smoothing is applied. Defaults to 0. vmin : None | float | callable The min value in the image (and the ER[P/F]). The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers. If vmin is None and multiple plots are returned, the limit is equalized within channel types. Hint: to specify the lower limit of the data, use ``vmin=lambda data: data.min()``. vmax : None | float | callable The max value in the image (and the ER[P/F]). The unit is µV for EEG channels, fT for magnetometers and fT/cm for gradiometers. If vmin is None and multiple plots are returned, the limit is equalized within channel types. colorbar : bool Display or not a colorbar. order : None | array of int | callable If not ``None``, order is used to reorder the epochs along the y-axis of the image. If it is an array of :class:`int`, its length should match the number of good epochs. If it is a callable it should accept two positional parameters (``times`` and ``data``, where ``data.shape == (len(good_epochs), len(times))``) and return an :class:`array <numpy.ndarray>` of indices that will sort ``data`` along its first axis. show : bool Show figure if True. units : dict | None The units of the channel types used for axes labels. If None, defaults to ``units=dict(eeg='µV', grad='fT/cm', mag='fT')``. scalings : dict | None The scalings of the channel types to be applied for plotting. If None, defaults to ``scalings=dict(eeg=1e6, grad=1e13, mag=1e15, eog=1e6)``. cmap : None | colormap | (colormap, bool) | 'interactive' Colormap. If tuple, the first value indicates the colormap to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the scale. Up and down arrows can be used to change the colormap. If 'interactive', translates to ('RdBu_r', True). If None, "RdBu_r" is used, unless the data is all positive, in which case "Reds" is used. fig : Figure | None :class:`~matplotlib.figure.Figure` instance to draw the image to. Figure must contain the correct number of axes for drawing the epochs image, the evoked response, and a colorbar (depending on values of ``evoked`` and ``colorbar``). If ``None`` a new figure is created. Defaults to ``None``. axes : list of Axes | dict of list of Axes | None List of :class:`~matplotlib.axes.Axes` objects in which to draw the image, evoked response, and colorbar (in that order). Length of list must be 1, 2, or 3 (depending on values of ``colorbar`` and ``evoked`` parameters). If a :class:`dict`, each entry must be a list of Axes objects with the same constraints as above. If both ``axes`` and ``group_by`` are dicts, their keys must match. Providing non-``None`` values for both ``fig`` and ``axes`` results in an error. Defaults to ``None``. overlay_times : array_like, shape (n_epochs,) | None Times (in seconds) at which to draw a line on the corresponding row of the image (e.g., a reaction time associated with each epoch). Note that ``overlay_times`` should be ordered to correspond with the :class:`~mne.Epochs` object (i.e., ``overlay_times[0]`` corresponds to ``epochs[0]``, etc). %(combine)s If callable, the callable must accept one positional input (data of shape ``(n_epochs, n_channels, n_times)``) and return an :class:`array <numpy.ndarray>` of shape ``(n_epochs, n_times)``. For example:: combine = lambda data: np.median(data, axis=1) If ``combine`` is ``None``, channels are combined by computing GFP, unless ``group_by`` is also ``None`` and ``picks`` is a list of specific channels (not channel types), in which case no combining is performed and each channel gets its own figure. See Notes for further details. Defaults to ``None``. group_by : None | dict Specifies which channels are aggregated into a single figure, with aggregation method determined by the ``combine`` parameter. If not ``None``, one :class:`~matplotlib.figure.Figure` is made per dict entry; the dict key will be used as the figure title and the dict values must be lists of picks (either channel names or integer indices of ``epochs.ch_names``). For example:: group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8]) Note that within a dict entry all channels must have the same type. ``group_by`` interacts with ``picks`` and ``combine`` to determine the number of figures generated; see Notes. Defaults to ``None``. evoked : bool Draw the ER[P/F] below the image or not. ts_args : None | dict Arguments passed to a call to `~mne.viz.plot_compare_evokeds` to style the evoked plot below the image. Defaults to an empty dictionary, meaning `~mne.viz.plot_compare_evokeds` will be called with default parameters. title : None | str If :class:`str`, will be plotted as figure title. Otherwise, the title will indicate channel(s) or channel type being plotted. Defaults to ``None``. clear : bool Whether to clear the axes before plotting (if ``fig`` or ``axes`` are provided). Defaults to ``False``. Returns ------- figs : list of Figure One figure per channel, channel type, or group, depending on values of ``picks``, ``group_by``, and ``combine``. See Notes. Notes ----- You can control how channels are aggregated into one figure or plotted in separate figures through a combination of the ``picks``, ``group_by``, and ``combine`` parameters. If ``group_by`` is a :class:`dict`, the result is one :class:`~matplotlib.figure.Figure` per dictionary key (for any valid values of ``picks`` and ``combine``). If ``group_by`` is ``None``, the number and content of the figures generated depends on the values of ``picks`` and ``combine``, as summarized in this table: .. cssclass:: table-bordered .. rst-class:: midvalign +----------+----------------------------+------------+-------------------+ | group_by | picks | combine | result | +==========+============================+============+===================+ | | None, int, list of int, | None, | | | dict | ch_name, list of ch_names, | string, or | 1 figure per | | | ch_type, list of ch_types | callable | dict key | +----------+----------------------------+------------+-------------------+ | | None, | None, | | | | ch_type, | string, or | 1 figure per | | | list of ch_types | callable | ch_type | | None +----------------------------+------------+-------------------+ | | int, | None | 1 figure per pick | | | ch_name, +------------+-------------------+ | | list of int, | string or | 1 figure | | | list of ch_names | callable | | +----------+----------------------------+------------+-------------------+ """ from scipy.ndimage import gaussian_filter1d from .. import EpochsArray _validate_type(group_by, (dict, None), 'group_by') units = _handle_default('units', units) scalings = _handle_default('scalings', scalings) if set(units) != set(scalings): raise ValueError('Scalings and units must have the same keys.') # is picks a channel type (or None)? picks, picked_types = _picks_to_idx(epochs.info, picks, return_kind=True) ch_types = _get_channel_types(epochs.info, picks) # `combine` defaults to 'gfp' unless picks are specific channels and # there was no group_by passed combine_given = combine is not None if combine is None and (group_by is not None or picked_types): combine = 'gfp' # convert `combine` into callable (if None or str) combine_func = _make_combine_callable(combine) # handle ts_args (params for the evoked time series) ts_args = dict() if ts_args is None else ts_args manual_ylims = 'ylim' in ts_args if combine is not None: ts_args['show_sensors'] = False vlines = [0] if (epochs.times[0] < 0 < epochs.times[-1]) else [] ts_defaults = dict(colors={'cond': 'k'}, title='', show=False, truncate_yaxis=False, truncate_xaxis=False, vlines=vlines, legend=False) ts_defaults.update(**ts_args) ts_args = ts_defaults.copy() # construct a group_by dict if one wasn't supplied if group_by is None: if picked_types: # one fig per ch_type group_by = {ch_type: picks[np.array(ch_types) == ch_type] for ch_type in set(ch_types) if ch_type in _DATA_CH_TYPES_SPLIT} elif combine is None: # one fig per pick group_by = {epochs.ch_names[pick]: [pick] for pick in picks} else: # one fig to rule them all ch_names = np.array(epochs.ch_names)[picks].tolist() key = _set_title_multiple_electrodes(None, combine, ch_names) group_by = {key: picks} else: group_by = deepcopy(group_by) # check for heterogeneous sensor type combinations / "combining" 1 channel for this_group, these_picks in group_by.items(): this_ch_type = np.array(ch_types)[np.in1d(picks, these_picks)] if len(set(this_ch_type)) > 1: types = ', '.join(set(this_ch_type)) raise ValueError('Cannot combine sensors of different types; "{}" ' 'contains types {}.'.format(this_group, types)) # now we know they're all the same type... group_by[this_group] = dict(picks=these_picks, ch_type=this_ch_type[0], title=title) # are they trying to combine a single channel? if len(these_picks) < 2 and combine_given: warn('Only one channel in group "{}"; cannot combine by method ' '"{}".'.format(this_group, combine)) # check for compatible `fig` / `axes`; instantiate figs if needed; add # fig(s) and axes into group_by group_by = _validate_fig_and_axes(fig, axes, group_by, evoked, colorbar, clear=clear) # prepare images in advance to get consistent vmin/vmax. # At the same time, create a subsetted epochs object for each group data = epochs.get_data() vmin_vmax = {ch_type: dict(images=list(), norm=list()) for ch_type in set(ch_types)} for this_group, this_group_dict in group_by.items(): these_picks = this_group_dict['picks'] this_ch_type = this_group_dict['ch_type'] this_ch_info = [epochs.info['chs'][n] for n in these_picks] these_ch_names = np.array(epochs.info['ch_names'])[these_picks] this_data = data[:, these_picks] # create subsetted epochs object this_info = create_info(sfreq=epochs.info['sfreq'], ch_names=list(these_ch_names), ch_types=[this_ch_type] * len(these_picks)) with this_info._unlock(): this_info['chs'] = this_ch_info this_epochs = EpochsArray(this_data, this_info, tmin=epochs.times[0]) # apply scalings (only to image, not epochs object), combine channels this_image = combine_func(this_data * scalings[this_ch_type]) # handle `order`. NB: this can potentially yield different orderings # in each figure! this_image, _overlay_times = _order_epochs(this_image, epochs.times, order, overlay_times) this_norm = np.all(this_image > 0) # apply smoothing if sigma > 0.: this_image = gaussian_filter1d(this_image, sigma=sigma, axis=0, mode='nearest') # update the group_by and vmin_vmax dicts group_by[this_group].update(image=this_image, epochs=this_epochs, norm=this_norm) vmin_vmax[this_ch_type]['images'].append(this_image) vmin_vmax[this_ch_type]['norm'].append(this_norm) # compute overall vmin/vmax for images for ch_type, this_vmin_vmax_dict in vmin_vmax.items(): image_list = this_vmin_vmax_dict['images'] image_stack = np.stack(image_list) norm = all(this_vmin_vmax_dict['norm']) vmin_vmax[ch_type] = _setup_vmin_vmax(image_stack, vmin, vmax, norm) del image_stack, vmin, vmax # prepare to plot auto_ylims = {ch_type: [0., 0.] for ch_type in set(ch_types)} # plot for this_group, this_group_dict in group_by.items(): this_ch_type = this_group_dict['ch_type'] this_axes_dict = this_group_dict['axes'] vmin, vmax = vmin_vmax[this_ch_type] # plot title if this_group_dict['title'] is None: title = _handle_default('titles').get(this_group, this_group) if isinstance(combine, str) and len(title): _comb = combine.upper() if combine == 'gfp' else combine _comb = 'std. dev.' if _comb == 'std' else _comb title += f' ({_comb})' # plot the image this_fig = _plot_epochs_image( this_group_dict['image'], epochs=this_group_dict['epochs'], picks=picks, colorbar=colorbar, vmin=vmin, vmax=vmax, cmap=cmap, style_axes=True, norm=this_group_dict['norm'], unit=units[this_ch_type], ax=this_axes_dict, show=False, title=title, combine=combine, combine_given=combine_given, overlay_times=_overlay_times, evoked=evoked, ts_args=ts_args) group_by[this_group].update(fig=this_fig) # detect ylims across figures if evoked and not manual_ylims: # ensure get_ylim works properly this_axes_dict['evoked'].figure.canvas.draw_idle() this_bot, this_top = this_axes_dict['evoked'].get_ylim() this_min = min(this_bot, this_top) this_max = max(this_bot, this_top) curr_min, curr_max = auto_ylims[ch_type] auto_ylims[this_ch_type] = [min(curr_min, this_min), max(curr_max, this_max)] # equalize ylims across figures (does not adjust ticks) if evoked: for this_group_dict in group_by.values(): ax = this_group_dict['axes']['evoked'] ch_type = this_group_dict['ch_type'] if not manual_ylims: args = auto_ylims[ch_type] if 'invert_y' in ts_args: args = args[::-1] ax.set_ylim(*args) plt_show(show) # impose deterministic order of returned objects return_order = np.array(sorted(group_by)) are_ch_types = np.in1d(return_order, _VALID_CHANNEL_TYPES) if any(are_ch_types): return_order = np.concatenate((return_order[are_ch_types], return_order[~are_ch_types])) return [group_by[group]['fig'] for group in return_order] def _validate_fig_and_axes(fig, axes, group_by, evoked, colorbar, clear=False): """Check user-provided fig/axes compatibility with plot_epochs_image.""" from matplotlib.pyplot import figure, Axes, subplot2grid n_axes = 1 + int(evoked) + int(colorbar) ax_names = ('image', 'evoked', 'colorbar') ax_names = np.array(ax_names)[np.where([True, evoked, colorbar])] prefix = 'Since evoked={} and colorbar={}, '.format(evoked, colorbar) # got both fig and axes if fig is not None and axes is not None: raise ValueError('At least one of "fig" or "axes" must be None; got ' 'fig={}, axes={}.'.format(fig, axes)) # got fig=None and axes=None: make fig(s) and axes if fig is None and axes is None: axes = dict() colspan = 9 if colorbar else 10 rowspan = 2 if evoked else 3 shape = (3, 10) for this_group in group_by: this_fig = figure() _set_window_title(this_fig, this_group) subplot2grid(shape, (0, 0), colspan=colspan, rowspan=rowspan, fig=this_fig) if evoked: subplot2grid(shape, (2, 0), colspan=colspan, rowspan=1, fig=this_fig) if colorbar: subplot2grid(shape, (0, 9), colspan=1, rowspan=rowspan, fig=this_fig) axes[this_group] = this_fig.axes # got a Figure instance if fig is not None: # If we're re-plotting into a fig made by a previous call to # `plot_image`, be forgiving of presence/absence of sensor inset axis. if len(fig.axes) not in (n_axes, n_axes + 1): raise ValueError('{}"fig" must contain {} axes, got {}.' ''.format(prefix, n_axes, len(fig.axes))) if len(list(group_by)) != 1: raise ValueError('When "fig" is not None, "group_by" can only ' 'have one group (got {}: {}).' .format(len(group_by), ', '.join(group_by))) key = list(group_by)[0] if clear: # necessary if re-plotting into previous figure _ = [ax.clear() for ax in fig.axes] if len(fig.axes) > n_axes: # get rid of sensor inset fig.axes[-1].remove() _set_window_title(fig, key) axes = {key: fig.axes} # got an Axes instance, be forgiving (if evoked and colorbar are False) if isinstance(axes, Axes): axes = [axes] # got an ndarray; be forgiving if isinstance(axes, np.ndarray): axes = axes.ravel().tolist() # got a list of axes, make it a dict if isinstance(axes, list): if len(axes) != n_axes: raise ValueError('{}"axes" must be length {}, got {}.' ''.format(prefix, n_axes, len(axes))) # for list of axes to work, must be only one group if len(list(group_by)) != 1: raise ValueError('When axes is a list, can only plot one group ' '(got {} groups: {}).' .format(len(group_by), ', '.join(group_by))) key = list(group_by)[0] axes = {key: axes} # got a dict of lists of axes, make it dict of dicts if isinstance(axes, dict): # in theory a user could pass a dict of axes but *NOT* pass a group_by # dict, but that is forbidden in the docstring so it shouldn't happen. # The next test could fail in that case because we've constructed a # group_by dict and the user won't have known what keys we chose. if set(axes) != set(group_by): raise ValueError('If "axes" is a dict its keys ({}) must match ' 'the keys in "group_by" ({}).' .format(list(axes), list(group_by))) for this_group, this_axes_list in axes.items(): if len(this_axes_list) != n_axes: raise ValueError('{}each value in "axes" must be a list of {} ' 'axes, got {}.'.format(prefix, n_axes, len(this_axes_list))) # NB: next line assumes all axes in each list are in same figure group_by[this_group]['fig'] = this_axes_list[0].get_figure() group_by[this_group]['axes'] = {key: axis for key, axis in zip(ax_names, this_axes_list)} return group_by def _order_epochs(data, times, order=None, overlay_times=None): """Sort epochs image data (2D). Helper for plot_epochs_image.""" n_epochs = len(data) if overlay_times is not None: if len(overlay_times) != n_epochs: raise ValueError( f'size of overlay_times parameter ({len(overlay_times)}) does ' f'not match the number of epochs ({n_epochs}).') overlay_times = np.array(overlay_times) times_min = np.min(overlay_times) times_max = np.max(overlay_times) if (times_min < times[0]) or (times_max > times[-1]): warn('Some values in overlay_times fall outside of the epochs ' f'time interval (between {times[0]} s and {times[-1]} s)') if callable(order): order = order(times, data) if order is not None: if len(order) != n_epochs: raise ValueError(f'If order is a {type(order).__name__}, its ' f'length ({len(order)}) must match the length of ' f'the data ({n_epochs}).') order = np.array(order) data = data[order] if overlay_times is not None: overlay_times = overlay_times[order] return data, overlay_times def _plot_epochs_image(image, style_axes=True, epochs=None, picks=None, vmin=None, vmax=None, colorbar=False, show=False, unit=None, cmap=None, ax=None, overlay_times=None, title=None, evoked=False, ts_args=None, combine=None, combine_given=False, norm=False): """Plot epochs image. Helper function for plot_epochs_image.""" from matplotlib.ticker import AutoLocator if cmap is None: cmap = 'Reds' if norm else 'RdBu_r' tmin = epochs.times[0] tmax = epochs.times[-1] ax_im = ax['image'] fig = ax_im.get_figure() # draw the image cmap = _setup_cmap(cmap, norm=norm) n_epochs = len(image) extent = [tmin, tmax, 0, n_epochs] im = ax_im.imshow(image, vmin=vmin, vmax=vmax, cmap=cmap[0], aspect='auto', origin='lower', interpolation='nearest', extent=extent) # optional things if style_axes: ax_im.set_title(title) ax_im.set_ylabel('Epochs') if not evoked: ax_im.set_xlabel('Time (s)') ax_im.axis('auto') ax_im.axis('tight') ax_im.axvline(0, color='k', linewidth=1, linestyle='--') if overlay_times is not None: ax_im.plot(overlay_times, 0.5 + np.arange(n_epochs), 'k', linewidth=2) ax_im.set_xlim(tmin, tmax) # draw the evoked if evoked: from . import plot_compare_evokeds pass_combine = (combine if combine_given else None) _picks = [0] if len(picks) == 1 else None # prevent applying GFP plot_compare_evokeds({'cond': list(epochs.iter_evoked(copy=False))}, picks=_picks, axes=ax['evoked'], combine=pass_combine, **ts_args) ax['evoked'].set_xlim(tmin, tmax) ax['evoked'].lines[0].set_clip_on(True) ax['evoked'].collections[0].set_clip_on(True) ax['evoked'].get_shared_x_axes().join(ax['evoked'], ax_im) # fix the axes for proper updating during interactivity loc = ax_im.xaxis.get_major_locator() ax['evoked'].xaxis.set_major_locator(loc) ax['evoked'].yaxis.set_major_locator(AutoLocator()) # draw the colorbar if colorbar: from matplotlib.pyplot import colorbar as cbar this_colorbar = cbar(im, cax=ax['colorbar']) this_colorbar.ax.set_ylabel(unit, rotation=270, labelpad=12) if cmap[1]: ax_im.CB = DraggableColorbar(this_colorbar, im) with warnings.catch_warnings(record=True): warnings.simplefilter('ignore') tight_layout(fig=fig) # finish plt_show(show) return fig def plot_drop_log(drop_log, threshold=0, n_max_plot=20, subject=None, color='lightgray', width=0.8, ignore=('IGNORED',), show=True): """Show the channel stats based on a drop_log from Epochs. Parameters ---------- drop_log : list of list Epoch drop log from Epochs.drop_log. threshold : float The percentage threshold to use to decide whether or not to plot. Default is zero (always plot). n_max_plot : int Maximum number of channels to show stats for. subject : str | None The subject name to use in the title of the plot. If ``None``, do not display a subject name. .. versionchanged:: 0.23 Added support for ``None``. .. versionchanged:: 1.0 Defaults to ``None``. color : tuple | str Color to use for the bars. width : float Width of the bars. ignore : list The drop reasons to ignore. show : bool Show figure if True. Returns ------- fig : instance of matplotlib.figure.Figure The figure. """ import matplotlib.pyplot as plt from ..epochs import _drop_log_stats percent = _drop_log_stats(drop_log, ignore) if percent < threshold: logger.info('Percent dropped epochs < supplied threshold; not ' 'plotting drop log.') return absolute = len([x for x in drop_log if len(x) if not any(y in ignore for y in x)]) n_epochs_before_drop = len([x for x in drop_log if not any(y in ignore for y in x)]) scores = Counter([ch for d in drop_log for ch in d if ch not in ignore]) ch_names = np.array(list(scores.keys())) counts = np.array(list(scores.values())) # init figure, handle easy case (no drops) fig, ax = plt.subplots() title = (f'{absolute} of {n_epochs_before_drop} epochs removed ' f'({percent:.1f}%)') if subject is not None: title = f'{subject}: {title}' ax.set_title(title) if len(ch_names) == 0: ax.text(0.5, 0.5, 'No drops', ha='center', fontsize=14) return fig # count epochs that aren't fully caught by `ignore` n_used = sum([any(ch not in ignore for ch in d) or len(d) == 0 for d in drop_log]) # calc plot values n_bars = min(n_max_plot, len(ch_names)) x = np.arange(n_bars) y = 100 * counts / n_used order = np.flipud(np.argsort(y)) ax.bar(x, y[order[:n_bars]], color=color, width=width, align='center') ax.set_xticks(x) ax.set_xticklabels(ch_names[order[:n_bars]], rotation=45, size=10, horizontalalignment='right') ax.set_ylabel('% of epochs removed') ax.grid(axis='y') tight_layout(pad=1, fig=fig) plt_show(show) return fig @fill_doc def plot_epochs(epochs, picks=None, scalings=None, n_epochs=20, n_channels=20, title=None, events=None, event_color=None, order=None, show=True, block=False, decim='auto', noise_cov=None, butterfly=False, show_scrollbars=True, show_scalebars=True, epoch_colors=None, event_id=None, group_by='type', precompute=None, use_opengl=None, *, theme='auto'): """Visualize epochs. Bad epochs can be marked with a left click on top of the epoch. Bad channels can be selected by clicking the channel name on the left side of the main axes. Calling this function drops all the selected bad epochs as well as bad epochs marked beforehand with rejection parameters. Parameters ---------- epochs : instance of Epochs The epochs object. %(picks_good_data)s %(scalings)s n_epochs : int The number of epochs per view. Defaults to 20. n_channels : int The number of channels per view. Defaults to 20. title : str | None The title of the window. If None, epochs name will be displayed. Defaults to None. events : None | array, shape (n_events, 3) Events to show with vertical bars. You can use `~mne.viz.plot_events` as a legend for the colors. By default, the coloring scheme is the same. Defaults to ``None``. .. warning:: If the epochs have been resampled, the events no longer align with the data. .. versionadded:: 0.14.0 %(event_color)s Defaults to ``None``. order : array of str | None Order in which to plot channel types. .. versionadded:: 0.18.0 show : bool Show figure if True. Defaults to True. block : bool Whether to halt program execution until the figure is closed. Useful for rejecting bad trials on the fly by clicking on an epoch. Defaults to False. decim : int | 'auto' Amount to decimate the data during display for speed purposes. You should only decimate if the data are sufficiently low-passed, otherwise aliasing can occur. The 'auto' mode (default) uses the decimation that results in a sampling rate at least three times larger than ``info['lowpass']`` (e.g., a 40 Hz lowpass will result in at least a 120 Hz displayed sample rate). .. versionadded:: 0.15.0 noise_cov : instance of Covariance | str | None Noise covariance used to whiten the data while plotting. Whitened data channels are scaled by ``scalings['whitened']``, and their channel names are shown in italic. Can be a string to load a covariance from disk. See also :meth:`mne.Evoked.plot_white` for additional inspection of noise covariance properties when whitening evoked data. For data processed with SSS, the effective dependence between magnetometers and gradiometers may introduce differences in scaling, consider using :meth:`mne.Evoked.plot_white`. .. versionadded:: 0.16.0 butterfly : bool Whether to directly call the butterfly view. .. versionadded:: 0.18.0 %(show_scrollbars)s %(show_scalebars)s .. versionadded:: 0.24.0 epoch_colors : list of (n_epochs) list (of n_channels) | None Colors to use for individual epochs. If None, use default colors. event_id : dict | None Dictionary of event labels (e.g. 'aud_l') as keys and associated event integers as values. Useful when ``events`` contains event numbers not present in ``epochs.event_id`` (e.g., because of event subselection). Values in ``event_id`` will take precedence over those in ``epochs.event_id`` when there are overlapping keys. .. versionadded:: 0.20 %(group_by_browse)s %(precompute)s %(use_opengl)s %(theme_pg)s .. versionadded:: 1.0 Returns ------- fig : instance of matplotlib.figure.Figure The figure. Notes ----- The arrow keys (up/down/left/right) can be used to navigate between channels and epochs and the scaling can be adjusted with - and + (or =) keys, but this depends on the backend matplotlib is configured to use (e.g., mpl.use(``TkAgg``) should work). Full screen mode can be toggled with f11 key. The amount of epochs and channels per view can be adjusted with home/end and page down/page up keys. ``h`` key plots a histogram of peak-to-peak values along with the used rejection thresholds. Butterfly plot can be toggled with ``b`` key. Left mouse click adds a vertical line to the plot. Click 'help' button at bottom left corner of the plotter to view all the options. .. versionadded:: 0.10.0 """ from ._figure import _get_browser epochs.drop_bad() info = epochs.info.copy() sfreq = info['sfreq'] projs = info['projs'] projs_on = np.full_like(projs, epochs.proj, dtype=bool) if not epochs.proj: with info._unlock(): info['projs'] = list() # handle defaults / check arg validity color = _handle_default('color', None) scalings = _compute_scalings(scalings, epochs) scalings = _handle_default('scalings_plot_raw', scalings) if scalings['whitened'] == 'auto': scalings['whitened'] = 1. units = _handle_default('units', None) unit_scalings = _handle_default('scalings', None) decim, picks_data = _handle_decim(epochs.info.copy(), decim, None) noise_cov = _check_cov(noise_cov, epochs.info) event_id_rev = {v: k for k, v in (event_id or {}).items()} _check_option('group_by', group_by, ('selection', 'position', 'original', 'type')) # validate epoch_colors _validate_type(epoch_colors, (list, None), 'epoch_colors') if epoch_colors is not None: if len(epoch_colors) != len(epochs.events): msg = ('epoch_colors must have length equal to the number of ' f'epochs ({len(epochs)}); got length {len(epoch_colors)}.') raise ValueError(msg) for ix, this_colors in enumerate(epoch_colors): _validate_type(this_colors, list, f'epoch_colors[{ix}]') if len(this_colors) != len(epochs.ch_names): msg = (f'epoch colors for epoch {ix} has length ' f'{len(this_colors)}, expected {len(epochs.ch_names)}.') raise ValueError(msg) # handle time dimension n_epochs = min(n_epochs, len(epochs)) n_times = len(epochs) * len(epochs.times) duration = n_epochs * len(epochs.times) / sfreq # NB: this includes start and end of data: boundary_times = np.arange(len(epochs) + 1) * len(epochs.times) / sfreq # events if events is not None: event_nums = events[:, 2] event_samps = events[:, 0] epoch_n_samps = len(epochs.times) # handle overlapping epochs (each event may show up in multiple places) boundaries = (epochs.events[:, [0]] + np.array([-1, 1]) * epochs.time_as_index(0)) in_bounds = np.logical_and(boundaries[:, [0]] <= event_samps, event_samps < boundaries[:, [1]]) event_ixs = [np.nonzero(a)[0] for a in in_bounds.T] warned = False event_times = list() event_numbers = list() for samp, num, _ixs in zip(event_samps, event_nums, event_ixs): relevant_epoch_events = epochs.events[:, 0][_ixs] if len(relevant_epoch_events) > 1 and not warned: logger.info('You seem to have overlapping epochs. Some event ' 'lines may be duplicated in the plot.') warned = True offsets = samp - relevant_epoch_events + epochs.time_as_index(0) this_event_times = (_ixs * epoch_n_samps + offsets) / sfreq event_times.extend(this_event_times) event_numbers.extend([num] * len(_ixs)) event_nums = np.array(event_numbers) event_times = np.array(event_times) else: event_nums = None event_times = None event_color_dict = _make_event_color_dict(event_color, events, event_id) # determine trace order picks = _picks_to_idx(info, picks) n_channels = min(n_channels, len(picks)) ch_names = np.array(epochs.ch_names) ch_types = np.array(epochs.get_channel_types()) order = _get_channel_plotting_order(order, ch_types, picks) selections = None if group_by in ('selection', 'position'): selections = _setup_channel_selections(epochs, group_by, order) order = np.concatenate(list(selections.values())) default_selection = list(selections)[0] n_channels = len(selections[default_selection]) # generate window title if title is None: title = epochs._name if title is None or len(title) == 0: title = 'Epochs' elif not isinstance(title, str): raise TypeError(f'title must be None or a string, got a {type(title)}') precompute = _handle_precompute(precompute) params = dict(inst=epochs, info=info, n_epochs=n_epochs, # channels and channel order ch_names=ch_names, ch_types=ch_types, ch_order=order, picks=order[:n_channels], n_channels=n_channels, picks_data=picks_data, group_by=group_by, ch_selections=selections, # time t_start=0, duration=duration, n_times=n_times, first_time=0, time_format='float', decim=decim, boundary_times=boundary_times, # events event_id_rev=event_id_rev, event_color_dict=event_color_dict, event_nums=event_nums, event_times=event_times, # preprocessing projs=projs, projs_on=projs_on, apply_proj=epochs.proj, remove_dc=True, filter_coefs=None, filter_bounds=None, noise_cov=noise_cov, use_noise_cov=noise_cov is not None, # scalings scalings=scalings, units=units, unit_scalings=unit_scalings, # colors ch_color_bad='lightgray', ch_color_dict=color, epoch_color_bad=(1, 0, 0), epoch_colors=epoch_colors, # display butterfly=butterfly, clipping=None, scrollbars_visible=show_scrollbars, scalebars_visible=show_scalebars, window_title=title, xlabel='Epoch number', # pyqtgraph-specific precompute=precompute, use_opengl=use_opengl) fig = _get_browser(show=show, block=block, **params) return fig @verbose def plot_epochs_psd(epochs, fmin=0, fmax=np.inf, tmin=None, tmax=None, proj=False, bandwidth=None, adaptive=False, low_bias=True, normalization='length', picks=None, ax=None, color='black', xscale='linear', area_mode='std', area_alpha=0.33, dB=True, estimate='auto', show=True, n_jobs=1, average=False, line_alpha=None, spatial_colors=True, sphere=None, exclude='bads', verbose=None): """%(plot_psd_doc)s. Parameters ---------- epochs : instance of Epochs The epochs object. fmin : float Start frequency to consider. fmax : float End frequency to consider. tmin : float | None Start time to consider. tmax : float | None End time to consider. proj : bool Apply projection. bandwidth : float The bandwidth of the multi taper windowing function in Hz. The default value is a window half-bandwidth of 4. adaptive : bool Use adaptive weights to combine the tapered spectra into PSD (slow, use n_jobs >> 1 to speed up computation). low_bias : bool Only use tapers with more than 90%% spectral concentration within bandwidth. %(normalization)s %(picks_plot_psd_good_data)s ax : instance of Axes | None Axes to plot into. If None, axes will be created. %(color_plot_psd)s %(xscale_plot_psd)s %(area_mode_plot_psd)s %(area_alpha_plot_psd)s %(dB_plot_psd)s %(estimate_plot_psd)s %(show)s %(n_jobs)s %(average_plot_psd)s %(line_alpha_plot_psd)s %(spatial_colors_plot_psd)s %(sphere_topomap_auto)s exclude : list of str | 'bads' Channels names to exclude from being shown. If 'bads', the bad channels are excluded. Pass an empty list to plot all channels (including channels marked "bad", if any). .. versionadded:: 0.24.0 %(verbose)s Returns ------- fig : instance of Figure Figure with frequency spectra of the data channels. """ from ._mpl_figure import _psd_figure # generate figure # epochs always use multitaper, not Welch, so no need to allow "window" # param above fig = _psd_figure( inst=epochs, proj=proj, picks=picks, axes=ax, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, sphere=sphere, xscale=xscale, dB=dB, average=average, estimate=estimate, area_mode=area_mode, line_alpha=line_alpha, area_alpha=area_alpha, color=color, spatial_colors=spatial_colors, n_jobs=n_jobs, bandwidth=bandwidth, adaptive=adaptive, low_bias=low_bias, normalization=normalization, window='hamming', exclude=exclude) plt_show(show) return fig
mne-tools/mne-python
mne/viz/epochs.py
Python
bsd-3-clause
43,604
[ "Gaussian" ]
a058fecdd970a7abb85d7796b6559ad950e6f2732459006e80df3994ef157383
#------------------------------------------------------------------------------ # pycparser: c-to-c.py # # Example of using pycparser.c_generator, serving as a simplistic translator # from C to AST and back to C. # # Copyright (C) 2008-2012, Eli Bendersky # License: BSD #------------------------------------------------------------------------------ from __future__ import print_function import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py # sys.path.extend(['.', '..']) from pycparser import parse_file, c_parser, c_generator def translate_to_c(filename): ast = parse_file(filename, use_cpp=True) ast.show() generator = c_generator.CGenerator() print(generator.visit(ast)) def zz_test_translate(): # internal use src = r''' void f(char * restrict joe){} int main(void) { unsigned int long k = 4; int p = - - k; return 0; } ''' parser = c_parser.CParser() ast = parser.parse(src) ast.show() generator = c_generator.CGenerator() print(generator.visit(ast)) # tracing the generator for debugging #~ import trace #~ tr = trace.Trace(countcallers=1) #~ tr.runfunc(generator.visit, ast) #~ tr.results().write_results() #------------------------------------------------------------------------------ if __name__ == "__main__": #zz_test_translate() if len(sys.argv) > 1: translate_to_c(sys.argv[1]) else: translate_to_c("c_files/c_stub.c") print("Please provide a filename as argument")
songjiguo/interface-code-generator
examples/c-to-c.py
Python
bsd-3-clause
1,579
[ "VisIt" ]
c0684a1d0494eacd4b5bcb4242e1980c2a6d6d9e16796d5afca530e6c6ae9c44
import click from parsec.cli import pass_context, json_loads from parsec.decorators import custom_exception, text_output @click.command('update_quota') @click.argument("quota_id", type=str) @click.option( "--name", help="Name for the new quota. This must be unique within a Galaxy instance.", type=str ) @click.option( "--description", help="Quota description. If you supply this parameter, but not the name, an error will be thrown.", type=str ) @click.option( "--amount", help="Quota size (E.g. ``10000MB``, ``99 gb``, ``0.2T``, ``unlimited``)", type=str ) @click.option( "--operation", help="One of (``+``, ``-``, ``=``). If you wish to change this value, you must also provide the ``amount``, otherwise it will not take effect.", type=str ) @click.option( "--default", help="Whether or not this is a default quota. Valid values are ``no``, ``unregistered``, ``registered``. Calling this method with ``default=\"no\"`` on a non-default quota will throw an error. Not passing this parameter is equivalent to passing ``no``.", default="no", show_default=True, type=str ) @click.option( "--in_users", help="A list of user IDs or user emails.", type=str, multiple=True ) @click.option( "--in_groups", help="A list of group IDs or names.", type=str, multiple=True ) @pass_context @custom_exception @text_output def cli(ctx, quota_id, name="", description="", amount="", operation="", default="no", in_users="", in_groups=""): """Update an existing quota Output: A semicolon separated list of changes to the quota. For example:: "Quota 'Testing-A' has been renamed to 'Testing-B'; Quota 'Testing-e' is now '-100.0 GB'; Quota 'Testing-B' is now the default for unregistered users" """ return ctx.gi.quotas.update_quota(quota_id, name=name, description=description, amount=amount, operation=operation, default=default, in_users=in_users, in_groups=in_groups)
galaxy-iuc/parsec
parsec/commands/quotas/update_quota.py
Python
apache-2.0
1,997
[ "Galaxy" ]
b2ae0e23d53c25e8982157c931d45a6b284418645e05a362e3fbb0eefba3ae3f
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Tiger Soldier # # This file is part of OSD Lyrics. # # OSD Lyrics 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. # # OSD Lyrics 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 OSD Lyrics. If not, see <http://www.gnu.org/licenses/>. #/ import logging import xml.etree.ElementTree as xet import sys import dbus import dbus.exceptions import dbus.service import glib from .property import Property # Use the default encoding in ElementTree.tostring under Python 2, but prefer # Unicode under Python 3 to obtain a 'str', not 'bytes' instance. # TODO: remove once we have fully migrated to Python 3 INTROSPECT_ENCODING = 'unicode' if sys.version_info >= (3, 0) else 'us-ascii' class ObjectTypeCls(dbus.service.Object.__class__): def __init__(cls, name, bases, dct): property_dict = {} for k, v in dct.items(): if isinstance(v, Property): property_dict.setdefault(v.interface, {})[v.__name__] = v property_table = getattr(cls, '_dbus_property_table', {}) for base in bases: if hasattr(base, '_dbus_property_table'): modulename = base.__module__ + '.' + base.__name__ for interface, props in base._dbus_property_table[modulename].items(): clsprops = property_dict.setdefault(interface, {}) clsprops.update(props) cls._dbus_property_table = property_table property_table[cls.__module__ + '.' + cls.__name__] = property_dict super(ObjectTypeCls, cls).__init__(name, bases, dct) ObjectType = ObjectTypeCls('ObjectType', (dbus.service.Object, ), {}) class Object(ObjectType): """ DBus object wrapper which provides DBus property support """ # __metaclass__ = ObjectType def __init__(self, conn=None, object_path=None, bus_name=None): """ Either conn or bus_name is required; object_path is also required. Arguments: - `conn`: (dbus.connection.Connection or None) - The connection on which to export this object. If None, use the Bus associated with the given bus_name. If there is no bus_name either, the object is not initially available on any Connection. For backwards compatibility, if an instance of dbus.service.BusName is passed as the first parameter, this is equivalent to passing its associated Bus as conn, and passing the BusName itself as bus_name. - `object_path`: (str or None) - A D-Bus object path at which to make this Object available immediately. If this is not None, a conn or bus_name must also be provided. - `bus_name`: (dbus.service.BusName or None) - Represents a well-known name claimed by this process. A reference to the BusName object will be held by this Object, preventing the name from being released during this Object's lifetime (unless it's released manually). """ dbus.service.Object.__init__(self, conn=conn, object_path=object_path, bus_name=bus_name) self._changed_props = {} self._prop_change_timer = None def _prop_changed_timeout_cb(self): self._prop_change_timer = None changed_props = {} for k, v in self._changed_props.items(): iface = getattr(self.__class__, k).interface changed_props.setdefault(iface, {'changed': {}, 'invalidated': []}) if v: changed_props[iface]['changed'][k] = getattr(self, k) else: changed_props[iface]['invalidated'].append(k) self._changed_props = {} for k, v in changed_props.items(): self.PropertiesChanged(k, v['changed'], v['invalidated']) return False def _property_set(self, prop_name, emit_with_value): """ Callback for properties when a new value is set This method is called by properties of type osdlyrics.dbus.Property Arguments: - `prop_name`: - `changed`: """ self._changed_props[prop_name] = emit_with_value if not self._prop_change_timer: self._prop_change_timer = glib.idle_add(self._prop_changed_timeout_cb) @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v') def Get(self, iface_name, prop_name): """ DBus property getter Arguments: - `iface_name`: - `prop_name`: """ prop = getattr(self.__class__, prop_name, None) if isinstance(prop, Property) and \ (len(iface_name) == 0 or prop.interface == iface_name): return getattr(self, prop_name) raise dbus.exceptions.DBusException('No property of %s.%s' % (iface_name, prop_name)) @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='') def Set(self, iface_name, prop_name, value): """ DBus property setter Arguments: - `iface_name`: - `prop_name`: - `value`: """ prop = getattr(self.__class__, prop_name, None) if isinstance(prop, Property) and \ (len(iface_name) == 0 or prop.interface == iface_name): prop.dbus_set(self, value) else: raise dbus.exceptions.DBusException('No property of %s.%s' % (iface_name, prop_name)) @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}') def GetAll(self, iface_name): """ List all DBus properties Arguments: - `iface_name`: """ ret = {} property_dict = self._dbus_property_table[self.__class__.__module__ + '.' + self.__class__.__name__] if iface_name != '' and iface_name in property_dict: for prop_name, prop in property_dict[iface_name].iteritems(): if prop.readable: ret[prop_name] = prop.__get__(self) elif iface_name == '': for prop_list in property_dict.itervalues(): for prop_name, prop in prop_list.iteritems(): if prop.readable: ret[prop_name] = prop.__get__(self) return ret @dbus.service.signal(dbus_interface=dbus.PROPERTIES_IFACE, signature='sa{sv}as') def PropertiesChanged(self, iface_name, changed_props, invalidated_props): logging.debug('%s changed: %s invalidated: %s', iface_name, changed_props, invalidated_props) pass @dbus.service.method(dbus.service.INTROSPECTABLE_IFACE, in_signature='', out_signature='s', path_keyword='object_path', connection_keyword='connection') def Introspect(self, object_path, connection): """ Patch for dbus.service.Object to add property introspection data """ xml = dbus.service.Object.Introspect(self, object_path, connection) property_dict = self._dbus_property_table[self.__class__.__module__ + '.' + self.__class__.__name__] if property_dict == {}: return xml node = xet.XML(xml) iface_list = node.findall('interface') appended_iface = set() for iface in iface_list: iface_name = iface.get('name') if iface_name in property_dict: for prop_name, prop in property_dict[iface_name].iteritems(): iface.append(_property2element(prop)) appended_iface.add(iface_name) for iface_name, prop_list in property_dict.iteritems(): if iface_name in appended_iface: continue iface = xet.Element('interface', name=iface_name) for prop in prop_list.itervalues(): iface.append(_property2element(prop)) node.append(iface) return '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"\n "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">\n' + \ xet.tostring(node, encoding=INTROSPECT_ENCODING) def property(type_signature, dbus_interface, emit_change=True, readable=True, writeable=True): """ Decorator to define dbus properties as a class member. To use this decorator, define your class and member as below:: class Obj(osdlyrics.dbusext.service.Object): def __init__(*args, **kwargs): osdlyrics.dbusext.service.Object.__init__(*args, **kwargs) self._x = 0 @osdlyrics.dbusext.service.property( type_signature='i', dbus_interface='org.example.Interface') def x(self): return self._x @x.setter def x(self, value): if self._x != value: self._x = value return True else: return False You can use the dbus property member as a property of python Arguments: - `type_signature`: (string) The D-Bus type signature of the property - `dbus_interface`: (string) The D-Bus interface of the property - `emit_change`: (boolean or string) Whether to emit change with `PropertiesChanged` D-Bus signal when the property is set. Possible values are boolean value True or False, or a string 'invalidates'. - `readable`: Whether the property is able to visit with `Get` D-Bus method. - `writeable`: Whether the property is able to write with `Set` D-Bus method. A property is writeable only when `writeable` is set to True and a setter function is set. """ def dec_handler(fget): """ Arguments: - `fget`: getter function """ return Property(type_signature=type_signature, dbus_interface=dbus_interface, emit_change=emit_change, name=fget.__name__, readable=readable, writeable=writeable, fget=fget) return dec_handler def _property2element(prop): """ Convert an osdlyrics.dbusext.service.Property object to an xml.etree.ElementTree.ElementTree object. """ access = '' if prop.readable: access += 'read' if prop.writeable and (callable(prop._fset) or callable(prop._dbusset)): access += 'write' elem = xet.Element('property', name=prop.__name__, type=prop.type_signature, access=access) if prop.emit_change != 'true': annotation = xet.Element('annotation', name='org.freedesktop.DBus.Property.EmitsChangedSignal', value=prop.emit_change) elem.append(annotation) return elem def test(): BUS_NAME = 'org.example.test' IFACE = 'org.example.test' PATH = '/org/example/test' DEFAULT_VALUE = 'default value of x' class TestObj(Object): def __init__(self, loop): Object.__init__(self, conn=dbus.SessionBus(), object_path=PATH) self._loop = loop self._foo = DEFAULT_VALUE self._bar = 'yes' self._baz = 'baz' @property(type_signature='s', dbus_interface=IFACE) def foo(self): return self._foo @foo.setter def foo(self, value): if value != self._foo: self._foo = value return True else: return False @property(type_signature='s', dbus_interface='another.iface', readable=False, writeable=True, emit_change='invalidates') def bar(self): return self._bar @bar.setter def bar(self, value): self._bar = value @property(type_signature='s', dbus_interface='another.iface') def baz(self): return self._baz @baz.dbus_setter def baz(self, value): self._baz = value return True @baz.setter def baz(self, value): raise Exception('Shouldn\'t be called') @dbus.service.method(dbus_interface=IFACE, in_signature='', out_signature='') def Quit(self): self._loop.quit() def get_reply_handler(expected_value): def handler(value): if value != expected_value: logging.warning('Get failed, expect %s but %s got', expected_value, value) else: logging.debug('Get succesful') return handler def get_all_reply_handler(expected_dict): def handler(value): for k, v in value.iteritems(): if not k in expected_dict: logging.warning('GetAll: unexpected key %s', k) elif v != expected_dict[k]: logging.warning('GetAll: expected value of key %s is %s but %s got', k, expected_dict[k], v) for k in expected_dict.iterkeys(): if not k in value: logging.warning('GetAll: missing key %s', k) logging.debug('GetAll finished') return handler def set_reply_handler(): logging.debug('Set succeed') def error_handler(e): logging.error('Error %s', e) def introspect_reply_handler(xml): # print xml pass def msg_handler(msg): def handler(*args, **kwargs): logging.debug(msg) return handler def test_timeout(): proxy = conn.get_object(BUS_NAME, PATH) proxy.GetAll('', reply_handler=get_all_reply_handler({'foo': DEFAULT_VALUE, 'baz': 'baz'}), error_handler=error_handler) proxy.GetAll('another.iface', reply_handler=get_all_reply_handler({'baz': 'baz'}), error_handler=error_handler) proxy.Get('', 'foo', reply_handler=get_reply_handler(DEFAULT_VALUE), error_handler=error_handler) proxy.Set('', 'foo', 'new value of x', reply_handler=set_reply_handler, error_handler=error_handler) proxy.Get('', 'foo', reply_handler=get_reply_handler('new value of x'), error_handler=error_handler) proxy.Introspect(reply_handler=introspect_reply_handler, error_handler=error_handler) proxy.Set('another.iface', 'foo', 'should not success', reply_handler=msg_handler('Set error, should raise an error'), error_handler=msg_handler('Set succesful, an expected exception')) proxy.Set('another.iface', 'baz', 'new value of baz', reply_handler=set_reply_handler, error_handler=error_handler) proxy.Get('another.iface', 'baz', reply_handler=get_reply_handler('new value of baz'), error_handler=error_handler) proxy.Set('another.iface', 'bar', 'new value of bar', reply_handler=set_reply_handler, error_handler=error_handler) proxy.Get('another.iface', 'bar', reply_handler=get_reply_handler('new value of bar'), error_handler=error_handler) return False class TestObjSub(TestObj): def __init__(self, loop): TestObj.__init__(self, loop) import glib from dbus.mainloop.glib import DBusGMainLoop loop = glib.MainLoop() dbus_mainloop = DBusGMainLoop() conn = dbus.SessionBus(mainloop=dbus_mainloop) bus_name = dbus.service.BusName(BUS_NAME, conn) testobj = TestObjSub(loop) glib.timeout_add(100, test_timeout) loop.run() if __name__ == '__main__': test()
lenoch/osdlyrics
python/dbusext/service.py
Python
gpl-3.0
16,811
[ "VisIt" ]
2fe1f42ef6a9e96a7494bbe8d66afe258f7ef7e4d30b794bccff6dd4939cc758
#!/bin/env python3 import matplotlib.pyplot as plt import numpy as np from netCDF4 import Dataset import argparse from mpl_toolkits.basemap import Basemap import datetime from matplotlib.colors import LinearSegmentedColormap import matplotlib.patches as mpatches import matplotlib.lines as mlines parser = argparse.ArgumentParser() parser.add_argument('-d', '--dataset', required=True, help='NETCDF Datafile') parser.add_argument('-s', '--subsample', required=False, help='Subsample dataset') args = parser.parse_args() netdata = args.dataset sub = args.subsample particle_data = Dataset(netdata, 'r') nps = particle_data.dimensions['nps'] # print ("Number of particles:", len(nps)) # time = particle_data.variables['time'][:] #' print(time.shape) ipos = particle_data.variables['ipos'][:] #' print ("x location of particles loaded!", len(ipos)) #' jpos = particle_data.variables['jpos'][:] #' wfact = particle_data.variables['wfact'][:] #' print(wfact) print ("y location of particles loaded!") #' print ("Length of X/Y dimensions:", len (ipos), len(jpos)) print ("Everything loaded! Now time to plot....") # The length of the x and y positions of the particles - 1 to make it plot onto a map #ipossy = len(ipos) - 1 ipossy = len(ipos) / 2 #jpossy = len(jpos) - 1 jpossy = len(jpos) / 2 # Save file name date_string = datetime.datetime.now().strftime("%d-%m-%Y-%H:%M") named = str(len(ipos) / 2 ) fig = plt.figure(figsize=(180,120)) #ax = fig.add_subplot(111) m = Basemap(projection='lcc',resolution='i',lat_0=44, lon_0=0, llcrnrlon= -18, urcrnrlon=15, urcrnrlat=64, llcrnrlat=44) #m.etopo() m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') m.drawparallels(np.arange(-90.,120.,2.), labels=[False,True,True,False]) m.drawmeridians(np.arange(0.,420.,2.), labels=[True,False,False,True]) x, y = m(ipos[ipossy,:], jpos[jpossy,:]) # Sets the size of the hexagons gridsize = 200 cus_colour = 0 if cus_colour == 1: cdict = {'red': ( (0.0, 1.0, 1.0), (1.0, 0.9, 1.0) ), 'green':( (0.0, 1.0, 1.0), (1.0, 0.03, 0.0) ), 'blue': ( (0.0, 1.0, 1.0), (1.0, 0.16, 0.0) ) } custom_map = LinearSegmentedColormap('custom_map', cdict) plt.register_cmap(cmap=custom_map) plt.hexbin(x,y, gridsize=gridsize, mincnt=1, vmax=50, cmap='custom_map') # mincnt allows us to only plot where there are one or more values in a cell! if cus_colour == 0: plt.hexbin(x,y, gridsize=gridsize, mincnt=1, vmax=12, alpha=0.8) #m.plot(ipos[ipossy, x], jpos[ipossy, x], 'bo', alpha=0.5, latlon=True) for x in range(0,len(nps), 6001): m.plot(ipos[0, x], jpos[0, x],'pink', latlon=True, marker = "*", markersize=20) #red_patch = mpatches.Patch(label='Number of particles: ' + len(nps)) #plt.legend(label='Number of particles: ' + str(len(nps))) #red_patch = mpatches.Patch(color='white', label='Total number of particles: ' + str(len(nps))) #plt.legend(handles=[red_patch]) blue_line = mlines.Line2D([], [], color='Pink', marker='*', markersize=15, label='Particle Spawn Locations \n Number of particles: ' + str(len(nps))) plt.legend(handles=[blue_line]) cb = plt.colorbar() cb.set_label('Number of Particles') #plt.clf() #plt.imshow(heatmap) #plt.imshow(heatmap, extent=extent) #plt.savefig(date_string + '_' + named) plt.show()
abstractwisdom/Age-Tracer
Hex.py
Python
gpl-3.0
3,449
[ "NetCDF" ]
9a1f49a7f29d6d8a682fb362b414282f2d5fa1e1935cd9e9cdb707913bd9252a
""" A helper file to produce GROMACS metadata based on the type of computation """ data_keys = [ "defaults", "atomtypes", "nonbond_params", "moleculetype", "atoms", "bonds", "pairs", "angles", "dihedrals", "system", "molecules" ] # Units based GROMACS unit styles (http://lammps.sandia.gov/doc/units.html) #units = { # "[length]": "nanometer", # "[mass]": "u", # "[time]": "picosecond", # "[charge]": "e", # "[temperature]": "kelvin", # "[energy]": "(kilojoules * mol ** -1)", # "[force]": "(kilojoules * mol ** -1 nanometer ** -1)", # "[pressure]": "bar", # "[velocity]": "(nanometer picosecond** -1)", # "[dipole]": "e * nanometer", # "[electric field]": "(kilojoules * mol ** -1 * nanometer ** -1 * e ** -1)", # "[electric potential]": "(kilojoules * mol ** -1 * e ** -1)", # } bond_styles = { "harmonic": { "order": 2, "units": { "K": "0.5 * kilojoules * mol ** -1 * nanometer ** -2", "R0": "nanometer" }, "gmx_type": 6, }, "fourth_power": { "order": 2, "form": "fourth_power", "units": { "K": "kilojoules * mol ** -1 * nanometer ** -4", "R0": "nanometer" }, "gmx_type": 2, }, "morse": { "order": 2, "form": "morse", "units": { "D": "kilojoules * mol ** -1", "alpha": "nanometer ** -1", "R0": "nanometer", }, "gmx_type": 3, }, "cubic_bond": { "order": 2, "form": "cubic_bond", "units": { "K": "kilojoules * mol ** -1 * nanometer ** -2", "K_cub": "nanometer ** -1", "R0": "nanometer", }, "gmx_type": 4, }, "fene": { "order": 2, "form": "fene", "units": { "K": "kilojoules * mol ** -1 * nanometer ** -2", "R0": "nanometer", "epsilon": "kilojoules * mol ** -1", # Note that this is always zero in GMX! "sigma": "nanometer", # Note that this is always zero in GMX! }, "gmx_type": 7, }, } #angles not included: # bond bond cross term # bond angle cross term angle_styles = { "harmonic": { "order": 2, "units": { "K": "0.5 * kilojoules * mol ** -1 * radian ** -2", "theta0": "degree" }, }, "cosine": { "order": 2, "units": { "K": "0.5 * kilojoules * mol ** -1 * radian ** -2", "theta0": "degree" }, }, "restricted": { "order": 2, "form": "restricted", "units": { "K": "kilojoules * mol ** -1", "theta0": "degree", }, }, "urey-bradley": { "order": 2, "units": { "K": "0.5 * kilojoules * mol ** -1 ** radian ** -2", "theta0": "degree", "K_ub": "0.5 * kilojoules * mol ** -1 ** nanometer ** -2", "R_ub": "nanometer", }, }, "quartic": { "order": 2, "form": "quartic_gmx", "units": { "K0": "kilojoules * mol", "K1": "kilojoules * mol ** -1", "K2": "kilojoules * mol ** -2", "K3": "kilojoules * mol ** -3", "K4": "kilojoules * mol ** -4", "theta0": "degree", }, }, } dihedral_styles = { "charmm": { "order": 4, "form": "charmmfsw", "units": { "K": "kilojoules * mol ** -1", "n": "count", "d": "degree" }, }, "ryckaert-bellemans": { "order": 4, "form": "A_0 + A_1 * (cos(phi)) + A_2 * (cos(phi)) ** 2 + A_3 * (cos(phi)) ** 3 + A_4 * (cos(phi)) ** (4) + A_5 * cos(phi)) ** (5)", "units": { "A_0": "kilojoules * mol ** -1", "A_1": "kilojoules * mol ** -1", "A_2": "kilojoules * mol ** -1", "A_3": "kilojoules * mol ** -1", "A_4": "kilojoules * mol ** -1", "A_5": "kilojoules * mol ** -1", }, }, "opls": { "order": 4, "form": "opls", "units": { "K_1": "kilojoules * mol ** -1", "K_2": "kilojoules * mol ** -1", "K_3": "kilojoules * mol ** -1", "K_4": "kilojoules * mol ** -1", }, }, "restricted": { "order": 4, "form": "restricted", "units": { "K": "kilojoules * mol ** -1", "phi0": "degree", }, }, } improper_styles = { "harmonic": { "order": 4, "units": { "K": "0.5 * kilojoules * mol ** -1", "chi0": "degree", }, }, "periodic": { "order": 4, "form": "charmmfsw", "units": { "K": "kilojoules * mol ** -1", "n": "count", "d": "degree" }, }, } term_data = {} term_data[2] = bond_styles term_data[3] = angle_styles term_data[4] = dihedral_styles
dgasmith/EEX_scratch
eex/translators/gromacs/gromacs_metadata.py
Python
bsd-3-clause
5,090
[ "CHARMM", "Gromacs", "LAMMPS" ]
42807cd2839db376330326ebfe98e8646045d9be8e545a1e22b1e2480a5f28e8
"""Bravais.py - class for generating Bravais lattices etc. This is a base class for numerous classes setting up pieces of crystal. """ import math import numpy as np from ase.atoms import Atoms import ase.data class Bravais: """Bravais lattice factory. This is a base class for the objects producing various lattices (SC, FCC, ...). """ # The following methods are NOT defined here, but must be defined # in classes inhering from Bravais: # get_lattice_constant # make_crystal_basis # The following class attributes are NOT defined here, but must be defined # in classes inhering from Bravais: # int_basis # inverse_basis other = {0:(1,2), 1:(2,0), 2:(0,1)} # For Bravais lattices with a basis, set the basis here. Leave as # None if no basis is present. bravais_basis = None # If more than one type of element appear in the crystal, give the # order here. For example, if two elements appear in a 3:1 ratio, # bravais_basis could contain four vectors, and element_basis # could be (0,0,1,0) - the third atom in the basis is different # from the other three. Leave as None if all atoms are of the # same type. element_basis = None # How small numbers should be considered zero in the unit cell? chop_tolerance = 1e-10 def __call__(self, symbol, directions=(None,None,None), miller=(None,None,None), size=(1,1,1), latticeconstant=None, pbc=True, align=True, debug=0): "Create a lattice." self.size = size self.pbc = pbc self.debug = debug self.process_element(symbol) self.find_directions(directions, miller) if self.debug: self.print_directions_and_miller() self.convert_to_natural_basis() if self.debug >= 2: self.print_directions_and_miller(" (natural basis)") if latticeconstant is None: if self.element_basis is None: self.latticeconstant = self.get_lattice_constant() else: raise ValueError,\ "A lattice constant must be specified for a compound" else: self.latticeconstant = latticeconstant if self.debug: print "Expected number of atoms in unit cell:", self.calc_num_atoms() if self.debug >= 2: print "Bravais lattice basis:", self.bravais_basis if self.bravais_basis is not None: print " ... in natural basis:", self.natural_bravais_basis self.make_crystal_basis() self.make_unit_cell() if align: self.align() return self.make_list_of_atoms() def align(self): "Align the first axis along x-axis and the second in the x-y plane." degree = 180/np.pi if self.debug >= 2: print "Basis before alignment:" print self.basis if self.basis[0][0]**2 + self.basis[0][2]**2 < 0.01 * self.basis[0][1]**2: # First basis vector along y axis - rotate 90 deg along z t = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]], np.float) self.basis = np.dot(self.basis, t) transf = t if self.debug >= 2: print "Rotating -90 degrees around z axis for numerical stability." print self.basis else: transf = np.identity(3, np.float) assert abs(np.linalg.det(transf) - 1) < 1e-6 # Rotate first basis vector into xy plane theta = math.atan2(self.basis[0,2], self.basis[0,0]) t = np.array([[np.cos(theta), 0, -np.sin(theta)], [ 0, 1, 0 ], [np.sin(theta), 0, np.cos(theta) ]]) self.basis = np.dot(self.basis, t) transf = np.dot(transf, t) if self.debug >= 2: print "Rotating %f degrees around y axis." % (-theta*degree,) print self.basis assert abs(np.linalg.det(transf) - 1) < 1e-6 # Rotate first basis vector to point along x axis theta = math.atan2(self.basis[0,1], self.basis[0,0]) t = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [ 0, 0, 1]]) self.basis = np.dot(self.basis, t) transf = np.dot(transf, t) if self.debug >= 2: print "Rotating %f degrees around z axis." % (-theta*degree,) print self.basis assert abs(np.linalg.det(transf) - 1) < 1e-6 # Rotate second basis vector into xy plane theta = math.atan2(self.basis[1,2], self.basis[1,1]) t = np.array([[1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)]]) self.basis = np.dot(self.basis, t) transf = np.dot(transf, t) if self.debug >= 2: print "Rotating %f degrees around x axis." % (-theta*degree,) print self.basis assert abs(np.linalg.det(transf) - 1) < 1e-6 # Now we better rotate the atoms as well self.atoms = np.dot(self.atoms, transf) # ... and rotate miller_basis self.miller_basis = np.dot(self.miller_basis, transf) def make_list_of_atoms(self): "Repeat the unit cell." nrep = self.size[0] * self.size[1] * self.size[2] if nrep <= 0: raise ValueError, "Cannot create a non-positive number of unit cells" # Now the unit cells must be merged. a2 = [] e2 = [] for i in xrange(self.size[0]): offset = self.basis[0] * i a2.append(self.atoms + offset[np.newaxis,:]) e2.append(self.elements) atoms = np.concatenate(a2) elements = np.concatenate(e2) a2 = [] e2 = [] for j in xrange(self.size[1]): offset = self.basis[1] * j a2.append(atoms + offset[np.newaxis,:]) e2.append(elements) atoms = np.concatenate(a2) elements = np.concatenate(e2) a2 = [] e2 = [] for k in xrange(self.size[2]): offset = self.basis[2] * k a2.append(atoms + offset[np.newaxis,:]) e2.append(elements) atoms = np.concatenate(a2) elements = np.concatenate(e2) del a2, e2 assert len(atoms) == nrep * len(self.atoms) basis = np.array([[self.size[0],0,0], [0,self.size[1],0], [0,0,self.size[2]]]) basis = np.dot(basis, self.basis) # Tiny elements should be replaced by zero. The cutoff is # determined by chop_tolerance which is a class attribute. basis = np.where(np.abs(basis) < self.chop_tolerance, 0.0, basis) # None should be replaced, and memory should be freed. lattice = Lattice(positions=atoms, cell=basis, numbers=elements, pbc=self.pbc) lattice.millerbasis = self.miller_basis # Add info for lattice.surface.AddAdsorbate lattice._addsorbate_info_size = np.array(self.size[:2]) return lattice def process_element(self, element): "Extract atomic number from element" # The types that can be elements: integers and strings if self.element_basis is None: if isinstance(element, type("string")): self.atomicnumber = ase.data.atomic_numbers[element] elif isinstance(element, int): self.atomicnumber = element else: raise TypeError("The symbol argument must be a string or an atomic number.") else: atomicnumber = [] try: if len(element) != max(self.element_basis) + 1: oops = True else: oops = False except TypeError: oops = True if oops: raise TypeError( ("The symbol argument must be a sequence of length %d" +" (one for each kind of lattice position") % (max(self.element_basis)+1,)) for e in element: if isinstance(e, type("string")): atomicnumber.append(ase.data.atomic_numbers[e]) elif isinstance(element, int): atomicnumber.append(e) else: raise TypeError("The symbols argument must be a sequence of strings or atomic numbers.") self.atomicnumber = [atomicnumber[i] for i in self.element_basis] assert len(self.atomicnumber) == len(self.bravais_basis) def convert_to_natural_basis(self): "Convert directions and miller indices to the natural basis." self.directions = np.dot(self.directions, self.inverse_basis) if self.bravais_basis is not None: self.natural_bravais_basis = np.dot(self.bravais_basis, self.inverse_basis) for i in (0,1,2): self.directions[i] = reduceindex(self.directions[i]) for i in (0,1,2): (j,k) = self.other[i] self.miller[i] = reduceindex(self.handedness * cross(self.directions[j], self.directions[k])) def calc_num_atoms(self): v = int(round(abs(np.linalg.det(self.directions)))) if self.bravais_basis is None: return v else: return v * len(self.bravais_basis) def make_unit_cell(self): "Make the unit cell." # Make three loops, and find the positions in the integral # lattice. Each time a position is found, the atom is placed # in the real unit cell by put_atom(). self.natoms = self.calc_num_atoms() self.nput = 0 self.atoms = np.zeros((self.natoms,3), np.float) self.elements = np.zeros(self.natoms, np.int) self.farpoint = farpoint = sum(self.directions) #printprogress = self.debug and (len(self.atoms) > 250) percent = 0 # Find the radius of the sphere containing the whole system sqrad = 0 for i in (0,1): for j in (0,1): for k in (0,1): vect = (i * self.directions[0] + j * self.directions[1] + k * self.directions[2]) if np.dot(vect,vect) > sqrad: sqrad = np.dot(vect,vect) del i,j,k # Loop along first crystal axis (i) for (istart, istep) in ((0,1), (-1,-1)): i = istart icont = True while icont: nj = 0 for (jstart, jstep) in ((0,1), (-1,-1)): j = jstart jcont = True while jcont: nk = 0 for (kstart, kstep) in ((0,1), (-1,-1)): k = kstart #print "Starting line i=%d, j=%d, k=%d, step=(%d,%d,%d)" % (i,j,k,istep,jstep,kstep) kcont = True while kcont: # Now (i,j,k) loops over Z^3, except that # the loops can be cut off when we get outside # the unit cell. point = np.array((i,j,k)) if self.inside(point): self.put_atom(point) nk += 1 nj += 1 # Is k too high? if np.dot(point,point) > sqrad: assert not self.inside(point) kcont = False k += kstep # Is j too high? if i*i+j*j > sqrad: jcont = False j += jstep # Is i too high? if i*i > sqrad: icont = False i += istep #if printprogress: # perce = int(100*self.nput / len(self.atoms)) # if perce > percent + 10: # print ("%d%%" % perce), # percent = perce assert(self.nput == self.natoms) def inside(self, point): "Is a point inside the unit cell?" return (np.dot(self.miller[0], point) >= 0 and np.dot(self.miller[0], point - self.farpoint) < 0 and np.dot(self.miller[1], point) >= 0 and np.dot(self.miller[1], point - self.farpoint) < 0 and np.dot(self.miller[2], point) >= 0 and np.dot(self.miller[2], point - self.farpoint) < 0) def put_atom(self, point): "Place an atom given its integer coordinates." if self.bravais_basis is None: # No basis - just place a single atom pos = np.dot(point, self.crystal_basis) if self.debug >= 2: print ("Placing an atom at (%d,%d,%d) ~ (%.3f, %.3f, %.3f)." % (tuple(point) + tuple(pos))) self.atoms[self.nput] = pos self.elements[self.nput] = self.atomicnumber self.nput += 1 else: for i, offset in enumerate(self.natural_bravais_basis): pos = np.dot(point + offset, self.crystal_basis) if self.debug >= 2: print ("Placing an atom at (%d+%f, %d+%f, %d+%f) ~ (%.3f, %.3f, %.3f)." % (point[0], offset[0], point[1], offset[1], point[2], offset[2], pos[0], pos[1], pos[2])) self.atoms[self.nput] = pos if self.element_basis is None: self.elements[self.nput] = self.atomicnumber else: self.elements[self.nput] = self.atomicnumber[i] self.nput += 1 def find_directions(self, directions, miller): "Find missing directions and miller indices from the specified ones." directions = list(directions) miller = list(miller) # If no directions etc are specified, use a sensible default. if directions == [None, None, None] and miller == [None, None, None]: directions = [[1,0,0], [0,1,0], [0,0,1]] # Now fill in missing directions and miller indices. This is an # iterative process. change = 1 while change: change = False missing = 0 for i in (0,1,2): (j,k) = self.other[i] if directions[i] is None: missing += 1 if miller[j] is not None and miller[k] is not None: directions[i] = reduceindex(cross(miller[j], miller[k])) change = True if self.debug >= 2: print "Calculating directions[%d] from miller indices" % i if miller[i] is None: missing += 1 if directions[j] is not None and directions[k] is not None: miller[i] = reduceindex(cross(directions[j], directions[k])) change = True if self.debug >= 2: print "Calculating miller[%d] from directions" % i if missing: raise ValueError, "Specification of directions and miller indices is incomplete." # Make sure that everything is Numeric arrays self.directions = np.array(directions) self.miller = np.array(miller) # Check for left-handed coordinate system if np.linalg.det(self.directions) < 0: print "WARNING: Creating a left-handed coordinate system!" self.miller = -self.miller self.handedness = -1 else: self.handedness = 1 # Now check for consistency for i in (0,1,2): (j,k) = self.other[i] m = reduceindex(self.handedness * cross(self.directions[j], self.directions[k])) if sum(np.not_equal(m, self.miller[i])): print "ERROR: Miller index %s is inconsisten with directions %d and %d" % (i,j,k) print "Miller indices:" print str(self.miller) print "Directions:" print str(self.directions) raise ValueError, "Inconsistent specification of miller indices and directions." def print_directions_and_miller(self, txt=""): "Print direction vectors and Miller indices." print "Direction vectors of unit cell%s:" % (txt,) for i in (0,1,2): print " ", self.directions[i] print "Miller indices of surfaces%s:" % (txt,) for i in (0,1,2): print " ", self.miller[i] class MillerInfo: """Mixin class to provide information about Miller indices.""" def miller_to_direction(self, miller): """Returns the direction corresponding to a given Miller index.""" return np.dot(miller, self.millerbasis) class Lattice(Atoms, MillerInfo): """List of atoms initially containing a regular lattice of atoms. A part from the usual list of atoms methods this list of atoms type also has a method, `miller_to_direction`, used to convert from Miller indices to directions in the coordinate system of the lattice. """ pass # Helper functions def cross(a, b): """The cross product of two vectors.""" return np.array((a[1]*b[2] - b[1]*a[2], a[2]*b[0] - b[2]*a[0], a[0]*b[1] - b[0]*a[1])) def gcd(a,b): """Greatest Common Divisor of a and b.""" while a != 0: a,b = b%a,a return b def reduceindex(M): "Reduce Miller index to the lowest equivalent integers." oldM = M g = gcd(M[0], M[1]) h = gcd(g, M[2]) while h != 1: M = M/h g = gcd(M[0], M[1]) h = gcd(g, M[2]) if np.dot(oldM, M) > 0: return M else: return -M
slabanja/ase
ase/lattice/bravais.py
Python
gpl-2.0
18,737
[ "ASE", "CRYSTAL" ]
2c0dd258ab67f88bfa13f68ad6d13bfd9d5509bb5df7bfed4da5ad09b1369e03
#!/usr/bin/env python # Media Dragon - the modular media manager # Copyright (C) 2012 Brian Hrebec # # 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 3 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/>. # Plugin management and base classes import os, logging, sys import mediadragon log = logging.getLogger('mediadragon') class Plugin(): ID = None def __init__(self, name): self.name = name def desc(self): return "Plugin" def setup(self): """ Called when the plugin is first loaded """ pass def destroy(self): """ Called when the plugin is unloaded """ pass class Source(Plugin): def __init__(self, output): Plugin.__init__(self, Plugin.SOURCE) def desc(self): return "Source" def query(self, **parameters): return None class Sink(Plugin): def __init__(self): Plugin.__init__(self, Plugin.SINK) def desc(self): return "Sink" class Filter(Plugin): def __init__(self): Plugin.__init__(self, Plugin.FILTER) def desc(self): return "Filter" class PluginManager: def import_plugins(self, path): plugin_dir = os.path.realpath(path) plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")] old_path = sys.path sys.path.insert(0, plugin_dir) for f in plugin_files: print(f) try: if f != "__init__": __import__(f) except ImportError: pass sys.path = old_path def register_plugins(self): for plugin in Plugin.__subclasses__(): if plugin.ID: self._plugins[plugin.ID] = plugin def __init__(self, searchpaths): self._plugins = {} for p in searchpaths: try: self.import_plugins(p) except OSError: log.error("Plugin path not found: {}".format(p)) try: builtin_path = __import__('mediadragon.plugins').plugins.__path__ self.import_plugins(builtin_path[0]) except ImportError: log.error("Builtin plugins not found!") self.register_plugins() @property def plugins(self): return self._plugins """ Returns a list of all available plugins """ def get_plugin(self, plugin_id): return _plugins[plugin_id] """ Returns a list of all available plugins """ def load_plugin(self, plugin, plugin_name): pass
bhrebec/mediadragon
src/lib/plugin.py
Python
gpl-3.0
3,104
[ "Brian" ]
eb69684593f79cc7346bf2d489a57b9e41dc756c611b57e3337fc6e8eb0141be
"""A handy collection of functions to write different filetypes. """ # This file is part of ManipulateAggregates. # # Copyright (C) 2016 by Torsten Sachse # # ManipulateAggregates 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. # # ManipulateAggregates 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 ManipulateAggregates. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import io import logging logger = logging.getLogger(__name__) from maagbel import etab # used to transform element names and numbers try: from .p2p3IO import open, writeto, close, isbasestring, hashstring except ImportError: logger.warning("Could not import p2p3IO") class CommentError(Exception): """Raised if a comment is not valid.""" pass def print_xyz(filename, names, coordinates, width="10.6", comment=None): """Write data to an xyz-file. A comment can be added. If no comment is given, the filename will be taken as the comment. Args: filename: (string) the name of the file (will be overwritten if it exists already) or an already existing file descriptor. This way, you can print to special files like stdout or stderr. Use sys.stdout or sys.stderr for this purpose. names: (list of strings) a list of strings containing the names of the atoms. coordinates: (list of 3-element lists) contains the cartesian coordinates. width: (string) a format string that will be used to convert floats to strings. Defaults to "10.6". comment: (string) The content of the comment line as one string. Do not use newline characters. """ if isbasestring(filename): f = open(filename, "w") name = filename else: # assume file handle f = filename try: name = f.name except AttributeError: raise TypeError( "Specified file is neither a file descriptor nor a filename." ) if comment is None: comment = name else: if re.search(r"\n", comment) != None: raise CommentError( "Specified comment contains a newline, which is not supported." ) writeto(f, str(len(names)) + "\n" + comment + "\n") for i in range(0, len(names)): tempstring = ( "%s %" + width + "f %" + width + "f %" + width + "f\n" ) % (names[i], coordinates[i][0], coordinates[i][1], coordinates[i][2]) writeto(f, tempstring) if isbasestring(filename): close(f) def _gen_cols(data, cols): i = 0 l = int(len(data) // cols) while i < l: yield [data[cols * i + j] for j in (0, 1, 2)] i += 1 yield data[cols * i :] def print_dx_file( filename, counts_xyz, org_xyz, delta_x, delta_y, delta_z, data, coloumns=3, comment=None, gzipped=False, formatstring="7.6e", ): """Print a dx file. Args: filename: (string) the file name counts_xyz: (tuple of 3 ints) how many points in each of the 3 directions there are to the volumetric data org_xyz: (tuple of 3 floats) the origin of the volumetric data delta_x: (tuple of 3 floats) the Cartesian direction of the first voxel vector delta_y: (tuple of 3 floats) the Cartesian direction of the second voxel vector delta_z: (tuple of 3 floats) the Cartesian direction of the third voxel vector data: (list of floats) the volumetric data coloumns: (int) in how many coloumns the volumetric data shall be written to the file comment: (string) a comment that is added at the top of the file gzipped: (bool) whether or not to write the file in gzipped format formatstring: (string) the format to be used for floating point numbers, for instance '7.6e', the default """ if isbasestring(filename): name = filename if gzipped: try: from subprocess import Popen, PIPE process = Popen( ["gzip", "--fast", "-c", "-"], stdin=PIPE, stdout=io.open(filename, "wb"), bufsize=4096, ) f = process.stdin except ImportError: print( sys.stderr, "WARNING: cannot import gzip module, will treat %s as a non-gzipped one." % (filename), file=sys.stderr, ) gzipped = False f = io.open(filename, "wb") except OSError: print( sys.stderr, "WARNING: cannot import gzip module, will treat %s as a non-gzipped one." % (filename), file.sys.stderr, ) gzipped = False f = io.open(filename, "wb") else: f = io.open(filename, "wb") else: f = filename try: name = f.name except AttributeError: raise TypeError( "Specified file is neither a file descriptor nor a filename." ) gzipped = False if comment is None: comment = "#" + name else: if re.search("\n", comment) != None: raise CommentError( "Specified comment contains a newline, which is not supported." ) if not comment.startswith("#"): comment = "#" + comment if not comment.endswith("\n"): comment = comment + "\n" f.write(hashstring(comment)) monoformat = "%%%s" % (formatstring) tripleformat = "%%%s %%%s %%%s" % (formatstring, formatstring, formatstring) # write header f.write( hashstring( "object 1 class gridpositions counts %4i %4i %4i\n" % tuple(counts_xyz) ) ) f.write(hashstring("origin " + tripleformat % tuple(org_xyz) + "\n")) f.write(hashstring("delta " + tripleformat % tuple(delta_x) + "\n")) f.write(hashstring("delta " + tripleformat % tuple(delta_y) + "\n")) f.write(hashstring("delta " + tripleformat % tuple(delta_z) + "\n")) f.write( hashstring( "object 2 class gridconnections counts %4i %4i %4i\n" % tuple(counts_xyz) ) ) prod = 1 for p in counts_xyz: prod *= p f.write( hashstring( "object 3 class array type double rank 0 items %12i data follows\n" % (prod) ) ) # write data for entry in _gen_cols(data, coloumns): tmp = (monoformat + " ") * len(entry) + "\n" if len(entry) > 0: f.write(hashstring(tmp % tuple(entry))) # write footer f.write(hashstring('attribute "dep" string "positions"\n')) f.write(hashstring('object "regular positions regular connections" class field\n')) f.write(hashstring('component "positions" value 1\n')) f.write(hashstring('component "connections" value 2\n')) f.write(hashstring('component "data" value 3\n')) if isbasestring(filename): f.close() if gzipped: process.wait() def _line_from_element_name(element, count, x, y, z): return "%s %d %d %8.5f %8.5f %8.5f\n" % ( element, count, etab.GetAtomicNum(element), x, y, z, ) def _line_from_element_number(element, count, x, y, z): return "%s %d %d %8.5f %8.5f %8.5f\n" % ( etab.GetSymbol(element), count, element, x, y, z, ) def _orbital_section(orb, count): result = "%5d %d\n" % (count, 0) for shell in orb[1]: orbtype, prefactor, nr_primitives, primitive_data = shell result += " %s %d %.2f\n" % (orbtype, nr_primitives, prefactor) for exponent, coefficient in primitive_data: result += " %.6f %.6f\n" % (exponent, coefficient) result += "\n" return result def print_molden( filename, positions=None, pos_unit_string="Angs", element_names=True, GTO=None, MO=None, ): """Print a molden file. Args: filename: (string) the name of the file in which to save the data. positions: (list of [int,[float,float,float]] or list of [str,[float,float,float]]) Contains information about atomic positions. The first entry defines the atom via a string or an int. element_names determines which one has been provided. pos_unit_string: (string) the string that will be put at the position where a programme expects the unit declaration. Some programmes seem to expect Bohr, some others AU or (AU). element_names: (bool) if True, positions has to be a list of [int,[float,float,float]]. Otherwise it has to be a list of [char,[float,float,float]]. Input for this can be generated by the function ManipulateAggregates.collection.read.molden_positions GTO: (list of [int, [[ str,float,int,[[float,float],[float,float],...], ...] ]) Contains information about the Gaussian type orbital data. The first int specifies the number of shells in this orbital. P-type counts three times, F-type counts six times, etc. The first str declares the type of shell. The first float declares a general scaling factor for this orbital. The second int declares the number of prmitives in this shell. The [float,float] constructs define a primitive each as [exponent,prefactor]. Three dots indicate that the previous item can be repeated. Input for this can be generated by ManipulateAggregates.collection.read.molden_GTO MO: (list of [float,str,[float,...]]) Contains information about the molecular orbital coefficients. The first float declares the energy of the MO, the first str declares the spin ('alpha' or 'beta'). The following list [float,...] contains one coefficient per shell (i.e. one for each S-type shell, 3 for each P-type shell, 6 for each F-type shell, etc.). Input for this can be generated using the function ManipulateAggregates.collection.read.molden_MO """ if isbasestring(filename): f = open(filename, "w") name = filename else: # assume file handle f = filename try: name = f.name except AttributeError: raise TypeError( "Specified file is neither a file descriptor nor a filename." ) # write header writeto(f, "[Molden Format]\n[Title]\nWritten by FireDeamon\n") # write atom positions if data has been provided # data has to be in Angstroms if positions is not None: writeto(f, "[Atoms] %s\n" % (pos_unit_string)) if element_names: linefunc = _line_from_element_name else: linefunc = _line_from_element_number count = 1 for element, (x, y, z) in positions: writeto(f, linefunc(element, count, x, y, z)) count += 1 # write GTO section if it has been provided if GTO is not None: writeto(f, "[GTO]\n") count = 1 for orb in GTO: writeto(f, _orbital_section(orb, count)) count += 1 # write the MO section if it has been provided if MO is not None: writeto(f, "[MO]\n") for orb in MO: energy, spin, occupation, coefficients = orb writeto( f, " Ene= %10.4f\n Spin= %s\n Occup= %.1f\n" % (energy, spin, occupation), ) count = 1 for c in coefficients: writeto(f, " %5d %10.5f\n" % (count, c)) count += 1 if isbasestring(filename): close(f)
razziel89/ManipulateAggregates
ManipulateAggregates/collection/write.py
Python
gpl-3.0
12,663
[ "Gaussian" ]
f26c900ee8d00faa0d6b5d296b837da49425b53f8ae046d650e9dfea3cf2945e
# Copyright (C) 2017 Martin Nilsson # This file is part of the Memtran compiler. # # The Memtran compiler 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. # # The Memtran compiler 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 the Memtran compiler. If not, see http://www.gnu.org/licenses/ import util from ast import * import name_mangler from fun_dict_stuff import * # Since this pass needs context depending on where we are in the tree, it does not use the visitor stuff defined in ast.py # Returns True or False depending on success # This pass also simultaneously checks for forward usage of slots (not functions though!!! check for those later please!) def run_pass( programAST, funDict, mangledModuleName, varBlockNumberList, typeDict, directlyImportedTypesDictDict, otherImportedModulesTypeDictDict, builtInFunsDict, directlyImportedFunsDictDict, otherImportedModulesFunDictDict ): collectorAndChecker = SlotCollectorAndForwardChecker(funDict, mangledModuleName, typeDict, directlyImportedTypesDictDict, otherImportedModulesTypeDictDict, builtInFunsDict, directlyImportedFunsDictDict, otherImportedModulesFunDictDict ) return collectorAndChecker.visit(programAST) # funDictStack = [funDict] # # for statement in programAST.statements: # success = _slotcollect_statement( # statement, funDictStack, mangledModuleName, varBlockNumberList, 0, # typeDict, directlyImportedTypesDictDict, otherImportedModulesTypeDictDict, # builtInFunsDict, # directlyImportedFunsDictDict, otherImportedModulesFunDictDict, # {} # ) # if success == False: # return False # # return True # This adds slot to the funDict, and returns True or False # -- also, for identifier expressions, this simultaneously checks so that these (but not function calls) are defined before usage # (it is handy to do this simultaneously with slot collection as we thus can simply check whether the slot has already been added to the dict...) class SlotCollectorAndForwardChecker(AbstractASTVisitor): def __init__(self, funDict, mangledModuleName, typeDict, directlyImportedTypesDictDict, otherImportedModulesTypeDictDict, builtInFunsDict, directlyImportedFunsDictDict, otherImportedModulesFunDictDict ): self.funDictStack = [funDict] self.mangledModuleName = mangledModuleName self.typeDict = typeDict self.directlyImportedTypesDictDict = directlyImportedTypesDictDict self.otherImportedModulesTypeDictDict = otherImportedModulesTypeDictDict self.builtInFunsDict = builtInFunsDict self.directlyImportedFunsDictDict = directlyImportedFunsDictDict self.otherImportedModulesFunDictDict = otherImportedModulesFunDictDict self.depth = 0 self.namesIntoBlock = {} self.varBlockNumberList = [] def visit(self, node): if isinstance(node, NStatement): if isinstance(node, NRefToFunctionDeclarationWithDefinition): actual = node.funs[node.funsIndex] funcEntryList = self.funDictStack[len(self.funDictStack) - 1][actual.name.name].funEntries funcEntry = None # dummy for fentry in funcEntryList: if fentry.mangledName == actual.mangledName: funcEntry = fentry # we better find it... below code assumes != None intoNames = set([]) for param in actual.params: # add the param to the funDict: if param.name.name in funcEntry.localDict: util.log_error(param.name.lineNr, param.name.rowNr, "Name collision. #7979") # can also be with recently added lhsEntries... return False funcEntry.localDict[param.name.name] = ParamEntry(name_mangler.mangle_param_name(param.name.name), param.create_copy()) self.depth += 1 self.funDictStack.append(funcEntry.localDict) self.varBlockNumberList.append(node.blockNumberStr) ### for statement in actual.body.statements: success = self.visit(statement) if success == False: return False ### self.varBlockNumberList.pop() self.funDictStack.pop() self.depth -= 1 return True elif isinstance(node, NBlock): for nameIntoBlock, entry in self.namesIntoBlock.items(): if nameIntoBlock in self.funDictStack[len(self.funDictStack) - 1][node.blockEntryNumStr].localDict: util.log_error(0, 0, "Name collision with name into block: " + nameIntoBlock) # should already be checked for though return False else: self.funDictStack[len(self.funDictStack) - 1][node.blockEntryNumStr].localDict[nameIntoBlock] = entry self.namesIntoBlock = {} self.depth += 1 self.funDictStack.append(self.funDictStack[len(self.funDictStack) - 1][node.blockEntryNumStr].localDict) self.varBlockNumberList.append(node.blockEntryNumStr) ### success = node.visit_children(self) if success == False: return False ### self.varBlockNumberList.pop() self.funDictStack.pop() self.depth -= 1 return True elif isinstance(node, NRefToTemplateDeclarationWithDefinition): return True # we better have this here elif isinstance(node, NForStatement): intoNames = {} if not node.rangeOrNull is None: if node.rangeOrNull.counterName.name in intoNames: util.log_error(node.rangeOrNull.counterName.lineNr, node.rangeOrNull.counterName.rowNr, "Name collision.") return False else: intoNames[node.rangeOrNull.counterName.name] = NameIntoBlockEntry(node.rangeOrNull.counterType.create_copy()) for iteration in node.iterations: if iteration.itName.name in intoNames: # we call in the same way indepenently if it is an IterationOver or an IterationIn... util.log_error(iteration.itName.lineNr, iteration.itName.rowNr, "Name collision.") return False else: if iteration.itTypeOrNull is None: intoNames[iteration.itName.name] = NameIntoBlockEntry( NStructType(iteration.lineNr, iteration.rowNr, NIdentifier(iteration.lineNr, iteration.rowNr, "TYPE_UNKNOWN_AS_YET"), []) ) else: intoNames[iteration.itName.name] = NameIntoBlockEntry(iteration.itTypeOrNull.create_copy()) self.namesIntoBlock = intoNames success = node.visit_children(self) if success == False: return False return True elif isinstance(node, NNormalAssignment): # first, we check the right hand side for forward calls. # It is important that we do this _before_ we add the lhs var declarations, as we don't want recursive assignment to be possible... success = self.visit(node.value) if success == False: return False for lhsEntry in node.leftHandSide: if isinstance(lhsEntry, NVariableDeclaration): if self.depth != 0 and lhsEntry.isInternal: # we might as well check for this here util.log_error(lhsEntry.lineNr, lhsEntry.rowNr, "Local variable marked as 'internal'.") return False elif self.depth == 0 and lhsEntry.name.name in self.typeDict: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with named type.") return False elif lhsEntry.name.name in self.funDictStack[len(self.funDictStack) - 1]: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision.") # can also be with recently added lhsEntries... return False elif self.depth == 0 and lhsEntry.name.name in self.builtInFunsDict: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with built-in function.") return False elif self.depth == 0: for moduleName, directlyImportedFunsDict in self.directlyImportedFunsDictDict.items(): if lhsEntry.name.name in directlyImportedFunsDict: entry = directlyImportedFunsDict[lhsEntry.name.name] if isinstance(entry, FunListEntry): for someFunOrTemplate in entry.funEntries: if not someFunOrTemplate.signature.isInternal: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with imported function or template.") return False elif isinstance(entry, VarEntry): if not entry.isInternal: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with imported name.") return False elif isinstance(entry, BlockEntry): util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with block. SHOULD NOT HAPPEN.") return False elif isinstance(entry, ParamEntry): util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with global param...??? SHOULD NOT HAPPEN.") return False elif isinstance(entry, NameIntoBlockEntry): util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with global name into block...??? SHOULD NOT HAPPEN.") return False else: util.log_error(lhsEntry.name.lineNr, lhsEntry.name.rowNr, "Name collision with unknown entry. SHOULD NOT HAPPEN.") return False isGlobal = True if self.depth > 0: isGlobal = False mangledName = name_mangler.mangle_var_name(lhsEntry.name.name, self.mangledModuleName, isGlobal, self.varBlockNumberList) self.funDictStack[len(self.funDictStack) - 1][lhsEntry.name.name] = VarEntry(mangledName, lhsEntry.isMut, lhsEntry.isInternal, lhsEntry.theType.create_copy()) else: # lValueContainer hopefully... success = self.visit(lhsEntry) if success == False: return False return True else: return node.visit_children(self) # not completely needed for completely _all_ stmt kinds, but cannot hurt elif (isinstance(node, NProgram) or isinstance(node, NLValueContainer) or isinstance(node, NRange) or isinstance(node, NIteration) or isinstance(node, NElseIfClause) or isinstance(node, NSwitchNormalCase) or isinstance(node, NContenttypeNormalCase) ): return node.visit_children(self) elif isinstance(node, NExpression): if isinstance(node, NIdentifierExpression): # first, check the indexings! : for indexing in node.indexings: if isinstance(indexing, NArrayIndexingIndex): success = self.visit(indexing.indexExpression) if success == False: return False elif isinstance(indexing, NStructIndexingIndex): pass elif isinstance(indexing, NVariantBoxCastIndex): pass elif isinstance(indexing, NTypeClarificationIndex): pass else: util.log_error(node.lineNr, node.rowNr, "Slot collection: SHOULD NOT HAPPEN -- unknown indexing kind.") return False foundDefinition = None if node.moduleNameOrNull is None: for funDict in reversed(self.funDictStack): if node.name.name in funDict: foundDefinition = funDict[node.name.name] break if foundDefinition is None: for moduleName, directlyImportedFunsDict in self.directlyImportedFunsDictDict.items(): if node.name.name in directlyImportedFunsDict: entry = directlyImportedFunsDict[expr.name.name] if isinstance(entry, FunListEntry): for someFunOrTemplate in entry.funEntries: if not someFunOrTemplate.signature.isInternal: foundDefinition = entry break if not foundDefinition is None: break # instead of labeled break right above, which is not available elif isinstance(entry, VarEntry): if not entry.isInternal: foundDefinition = entry break else: util.log_error(node.lineNr, node.rowNr, "Undetermined definition of identifier expression. SHOULD NOT HAPPEN") return False if foundDefinition is None: if node.name.name in self.builtInFunsDict: foundDefinition = self.builtInFunsDict[node.name.name] else: if node.moduleNameOrNull in self.otherImportedModulesFunDictDict: moduleDict = self.otherImportedModulesFunDictDict[node.moduleNameOrNull] if node.name.name in moduleDict: entry = moduleDict[node.name.name] if isinstance(entry, FunListEntry): for someFunOrTemplate in entry.funEntries: if not someFunOrTemplate.signature.isInternal: foundDefinition = entry break elif isinstance(entry, VarEntry): if not entry.isInternal: foundDefinition = entry else: util.log_error(node.lineNr, node.rowNr, "Undetermined definition of module specified identifier expression. SHOULD NOT HAPPEN") return False else: util.log_error(node.lineNr, node.rowNr, "Reference to module that has not been imported.") return False if foundDefinition is None: util.log_error(node.lineNr, node.rowNr, "Usage of name that has not been declared.") return False if isinstance(foundDefinition, NameIntoBlockEntry): return True elif isinstance(foundDefinition, FunListEntry): # If we come from the name in a funcall, we can allow forward calling in some cases, # more checking needing in later passes on this though # else it is a function name used as a function type value... but which of the listed??? # we cannot check this until later when the function value has been resolved together with type checking. So return True here too... return True elif isinstance(foundDefinition, VarEntry): return True # since we found it simultaneously, it should be declared before... elif isinstance(foundDefinition, BlockEntry): util.log_error(node.lineNr, node.rowNr, "SHOULD NEVER HAPPEN: We found a block entry as the definition during slot forward usage check...") return False elif isinstance(foundDefinition, ParamEntry): return True # since we found it simultaneously, it should be declared before... else: util.log_error(node.lineNr, node.rowNr, "SHOULD NOT HAPPEN: Found an unknown kind of definition entry during slot forward usage check...") return False return True # never reached though........ elif isinstance(node, NCONTENTTYPEExpression): util.log_error( node.lineNr, node.rowNr, "STORETYPE expressions are not yet implemented, starting from slot collection pass -- for certain reasons of name-into-expression extra complexity stuff." ) return False else: return node.visit_children(self) elif isinstance(node, NIndexingIndex) or isinstance(node, NArg) or isinstance(node, NSWITCHNormalCase) or isinstance(node, NCONTENTTYPENormalCase): # last one won't happen though # we only reach these through expressions though return node.visit_children(self) else: return True
LJMNilsson/memtran
src/slot_collection.py
Python
gpl-3.0
20,038
[ "VisIt" ]
079bb47a97d5b05f5d4eeec5424676b6b8905a2b2c7ff99c90327c210d7672f7
""" A script to calculate the projection of 3D world coordinates to 2D display coordinates (pixel coordinates) for a given scene. The 2D pixel locations of objects in the image plane are related to their 3D world coordinates by a series of linear transformations. The specific transformations fall under the group known as projective transformations. This set includes pure projectivities, affine transformations, perspective transformations, and euclidean transformations. In the case of mlab (and most other computer visualization software), we deal with only the perspective and euclidean cases. An overview of Projective space can be found here: http://en.wikipedia.org/wiki/Projective_space and a thorough treatment of projective geometry can be had in the book "Multiple View Geometry in Computer Vision" by Richard Hartley. The essential thing to know for this example is that points in 3-space are related to points in 2-space through a series of multiplications of 4x4 matrices which are the perspective and euclidean transformations. The 4x4 matrices predicate the use of length 4 vectors to represent points. This representation is known as homogeneous coordinates, and while they appear foriegn at first, they truly simplify all the mathematics involved. In short, homogeneous coordinates are your friend, and you should read about them here: http://en.wikipedia.org/wiki/Homogeneous_coordinates In the normal pinhole camera model (the ideal real world model), 3D world points are related to 2D image points by the matrix termed the 'essential' matrix which is a combination of a perspective transformation and a euclidean transformation. The perspective transformation is defined by the camera intrinsics (focal length, imaging sensor offset, etc...) and the euclidean transformation is defined by the cameras position and orientation. In computer graphics, things are not so simple. This is because computer graphics have the benefit of being able to do things which are not possible in the real world: adding clipping planes, offset projection centers, arbitrary distortions, etc... Thus, a slightly different model is used. What follows is the camera/view model for OpenGL and thus, VTK. I can not guarantee that other packages follow this model. There are 4 different transformations that are applied 3D world coordinates to map them to 2D pixel coordinates. They are: the model transform, the view transform, the perspective transform, and the viewport or display transform. In OpenGL the first two transformations are concatenated to yield the modelview transform (called simply the view transform in VTK). The modelview transformation applies arbitrary scaling and distortions to the model (if they are specified) and transforms them so that the orientation is the equivalent of looking down the negative Z axis. Imagine its as if you relocate your camera to look down the negative Z axis, and then move everything in the world so that you see it now as you did before you moved the camera. The resulting coordinates are termed "eye" coordinates in OpenGL (I don't know that they have a name in VTK). The perspective transformation applies the camera perspective to the eye coordinates. This transform is what makes objects in the foreground look bigger than equivalent objects in the background. In the pinhole camera model, this transform is determined uniquely by the focal length of the camera and its position in 3-space. In Vtk/OpenGL it is determined by the frustum. A frustum is simply a pyramid with the top lopped off. The top of the pyramid (a point) is the camera location, the base of the pyramid is a plane (the far clipping plane) defined as normal to principle camera ray at distance termed the far clipping distance, the top of the frustum (where it's lopped off) is the near clipping plane, with a definition similar to that of the far clipping plane. The sides of the frustum are determined by the aspect ratio of the camera (width/height) and its field-of-view. Any points not lying within the frustum are not mapped to the screen (as they would lie outside the viewable area). The perpspective transformation has the effect of scaling everything within the frustum to fit within a cube defined in the range (-1,1)(-1,1)(-1,1) as represented by homogeneous coordinates. The last phrase there is important, the first 3 coordinates will not, in general, be within the unity range until we divide through by the last coordinate (See the wikipedia on homogeneous coordinates if this is confusing). The resulting coordinates are termed (appropriately enough) normalized view coordinates. The last transformation (the viewport transformation) takes us from normalized view coordinates to display coordinates. At this point, you may be asking yourself 'why not just go directly to display coordinates, why need normalized view coordinates at all?', the answer is that we may want to embed more than one view in a particular window, there will therefore be different transformations to take each view to an appropriate position an size in the window. The normalized view coordinates provide a nice common ground so-to-speak. At any rate, the viewport transformation simply scales and translates the X and Y coordinates of the normalized view coordinates to the appropriate pixel coordinates. We don't use the Z value in our example because we don't care about it. It is used for other various things however. That's all there is to it, pretty simple right? Right. Here is an overview: Given a set of 3D world coordinates: - Apply the modelview transformation (view transform in VTK) to get eye coordinates - Apply the perspective transformation to get normalized view coordinates - Apply the viewport transformation to get display coordinates VTK provides a nice method to retrieve a 4x4 matrix that combines the first two operations. As far as I can tell, VTK does not export a method to retrieve the 4x4 matrix representing the viewport transformation, so we are on our there to create one (no worries though, its not hard, as you will see). Now that the prelimenaries are out of the way, lets get started. """ # Author: S. Chris Colbert <sccolbert@gmail.com> # Copyright (c) 2009, S. Chris Colbert # License: BSD Style # this import is here because we need to ensure that matplotlib uses the # wx backend and having regular code outside the main block is PyTaboo. # It needs to be imported first, so that matplotlib can impose the # version of Wx it requires. import matplotlib matplotlib.use('WXAgg') import pylab as pl import numpy as np from mayavi import mlab from mayavi.core.ui.mayavi_scene import MayaviScene def get_world_to_view_matrix(mlab_scene): """returns the 4x4 matrix that is a concatenation of the modelview transform and perspective transform. Takes as input an mlab scene object.""" if not isinstance(mlab_scene, MayaviScene): raise TypeError('argument must be an instance of MayaviScene') # The VTK method needs the aspect ratio and near and far clipping planes # in order to return the proper transform. So we query the current scene # object to get the parameters we need. scene_size = tuple(mlab_scene.get_size()) clip_range = mlab_scene.camera.clipping_range aspect_ratio = float(scene_size[0])/float(scene_size[1]) # this actually just gets a vtk matrix object, we can't really do anything with it yet vtk_comb_trans_mat = mlab_scene.camera.get_composite_projection_transform_matrix( aspect_ratio, clip_range[0], clip_range[1]) # get the vtk mat as a numpy array np_comb_trans_mat = vtk_comb_trans_mat.to_array() return np_comb_trans_mat def get_view_to_display_matrix(mlab_scene): """ this function returns a 4x4 matrix that will convert normalized view coordinates to display coordinates. It's assumed that the view should take up the entire window and that the origin of the window is in the upper left corner""" if not (isinstance(mlab_scene, MayaviScene)): raise TypeError('argument must be an instance of MayaviScene') # this gets the client size of the window x, y = tuple(mlab_scene.get_size()) # normalized view coordinates have the origin in the middle of the space # so we need to scale by width and height of the display window and shift # by half width and half height. The matrix accomplishes that. view_to_disp_mat = np.array([[x/2.0, 0., 0., x/2.0], [ 0., -y/2.0, 0., y/2.0], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) return view_to_disp_mat def apply_transform_to_points(points, trans_mat): """a function that applies a 4x4 transformation matrix to an of homogeneous points. The array of points should have shape Nx4""" if not trans_mat.shape == (4, 4): raise ValueError('transform matrix must be 4x4') if not points.shape[1] == 4: raise ValueError('point array must have shape Nx4') return np.dot(trans_mat, points.T).T if __name__ == '__main__': f = mlab.figure() N = 4 # create a few points in 3-space X = np.random.random_integers(-3, 3, N) Y = np.random.random_integers(-3, 3, N) Z = np.random.random_integers(-3, 3, N) # plot the points with mlab pts = mlab.points3d(X, Y, Z) # now were going to create a single N x 4 array of our points # adding a fourth column of ones expresses the world points in # homogenous coordinates W = np.ones(X.shape) hmgns_world_coords = np.column_stack((X, Y, Z, W)) # applying the first transform will give us 'unnormalized' view # coordinates we also have to get the transform matrix for the # current scene view comb_trans_mat = get_world_to_view_matrix(f.scene) view_coords = \ apply_transform_to_points(hmgns_world_coords, comb_trans_mat) # to get normalized view coordinates, we divide through by the fourth # element norm_view_coords = view_coords / (view_coords[:, 3].reshape(-1, 1)) # the last step is to transform from normalized view coordinates to # display coordinates. view_to_disp_mat = get_view_to_display_matrix(f.scene) disp_coords = apply_transform_to_points(norm_view_coords, view_to_disp_mat) # at this point disp_coords is an Nx4 array of homogenous coordinates # where X and Y are the pixel coordinates of the X and Y 3D world # coordinates, so lets take a screenshot of mlab view and open it # with matplotlib so we can check the accuracy img = mlab.screenshot() pl.imshow(img) for i in range(N): print 'Point %d: (x, y) ' % i, disp_coords[:, 0:2][i] pl.plot([disp_coords[:, 0][i]], [disp_coords[:, 1][i]], 'ro') pl.show() # you should check that the printed coordinates correspond to the # proper points on the screen mlab.show() #EOF
liulion/mayavi
examples/mayavi/advanced_visualization/mlab_3D_to_2D.py
Python
bsd-3-clause
11,049
[ "Mayavi", "VTK" ]
fc298bb6de89724149bde835ce97cf93a0e6b87e7b3c029959fb12de130ce05f
""" .. _tut_viz_stcs: Visualize Source time courses ============================= This tutorial focuses on visualization of stcs. .. contents:: Table of Contents :local: Surface Source Estimates ------------------------ First, we get the paths for the evoked data and the time courses (stcs). """ import os import mne from mne.datasets import sample from mne.minimum_norm import apply_inverse, read_inverse_operator from mne import read_evokeds data_path = sample.data_path() sample_dir = os.path.join(data_path, 'MEG', 'sample') subjects_dir = os.path.join(data_path, 'subjects') fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' fname_stc = os.path.join(sample_dir, 'sample_audvis-meg') ############################################################################### # Then, we read the stc from file stc = mne.read_source_estimate(fname_stc, subject='sample') ############################################################################### # This is a :class:`SourceEstimate <mne.SourceEstimate>` object print(stc) ############################################################################### # The SourceEstimate object is in fact a *surface* source estimate. MNE also # supports volume-based source estimates but more on that later. # # We can plot the source estimate using the # :func:`stc.plot <mne.SourceEstimate.plot>` just as in other MNE # objects. Note that for this visualization to work, you must have ``mayavi`` # and ``pysurfer`` installed on your machine. initial_time = 0.1 brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time) ############################################################################### # # Note that here we used ``initial_time=0.1``, but we can also browse through # time using ``time_viewer=True``. # # In case ``mayavi`` is not available, we also offer a ``matplotlib`` # backend. Here we use verbose='error' to ignore a warning that not all # vertices were used in plotting. mpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time, backend='matplotlib', verbose='error') ############################################################################### # # Volume Source Estimates # ----------------------- # We can also visualize volume source estimates (used for deep structures). # # Let us load the sensor-level evoked data. We select the MEG channels # to keep things simple. evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) evoked.pick_types(meg=True, eeg=False) ############################################################################### # Then, we can load the precomputed inverse operator from a file. fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' inv = read_inverse_operator(fname_inv) src = inv['src'] ############################################################################### # The source estimate is computed using the inverse operator and the # sensor-space data. snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) stc = apply_inverse(evoked, inv, lambda2, method) stc.crop(0.0, 0.2) ############################################################################### # This time, we have a different container # (:class:`VolSourceEstimate <mne.VolSourceEstimate>`) for the source time # course. print(stc) ############################################################################### # This too comes with a convenient plot method. stc.plot(src, subject='sample', subjects_dir=subjects_dir) ############################################################################### # For this visualization, ``nilearn`` must be installed. # This visualization is interactive. Click on any of the anatomical slices # to explore the time series. Clicking on any time point will bring up the # corresponding anatomical map. # # We could visualize the source estimate on a glass brain. Unlike the previous # visualization, a glass brain does not show us one slice but what we would # see if the brain was transparent like glass. stc.plot(src, subject='sample', subjects_dir=subjects_dir, mode='glass_brain') ############################################################################### # Vector Source Estimates # ----------------------- # If we choose to use ``pick_ori='vector'`` in # :func:`apply_inverse <mne.minimum_norm.apply_inverse>` fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' inv = read_inverse_operator(fname_inv) stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector') stc.plot(subject='sample', subjects_dir=subjects_dir, initial_time=initial_time) ############################################################################### # Dipole fits # ----------- # For computing a dipole fit, we need to load the noise covariance, the BEM # solution, and the coregistration transformation files. Note that for the # other methods, these were already used to generate the inverse operator. fname_cov = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') fname_bem = os.path.join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif') fname_trans = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif') ############################################################################## # Dipoles are fit independently for each time point, so let us crop our time # series to visualize the dipole fit for the time point of interest. evoked.crop(0.1, 0.1) dip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0] ############################################################################## # Finally, we can visualize the dipole. dip.plot_locations(fname_trans, 'sample', subjects_dir)
adykstra/mne-python
tutorials/source-modeling/plot_visualize_stc.py
Python
bsd-3-clause
5,780
[ "Mayavi" ]
a001ea185cd3730d64b1f7850a4101e6f87a83e28b35ed80493eec67b49bf616
#!/usr/bin/python # # sync Remote ftp directory to local - 2015 by meigrafd - v0.74 # source: remote # target: local # # http://www.forum-raspberrypi.de/Thread-python-python-skript-ftp-sync?pid=154491#pid154491 # import time, sys, os, re, curses from datetime import datetime from ftplib import FTP #Dictionary docu: http://www.tutorialspoint.com/python/python_dictionary.htm mirrorDirectories = {} ##----- CONFIG - START ---------------------------------------- ftpHost = '151.236.12.78' ftpPort = 21 ftpUser = 'ftpuser' ftpPass = 'ftp!user' ftpTLS = False ## Verzeichnisse die gesynct werden sollen. # Format: mirrorDirectories.update({"<local>":"<remote>"}) mirrorDirectories.update({"/home/pi/music":"/music"}) mirrorDirectories.update({"/home/pi/movie":"/movie"}) # Clean out the remote directory? deleteAfterCopy = False # Skip this files/dirs/extensions skipList = ['.', '..', '.backup', '.svn', 'CVS', '.pyc', '.pyo'] ##----- CONFIG - END ------------------------------------------ ascii_Files = (".txt", ".htm", ".html") def write_pidfile_or_die(pidfile): if os.access(pidfile, os.F_OK): #if the lockfile is already there then check the PID number in the lock file with open(pidfile, 'r') as pf: pf.seek(0) old_pid = pf.readline() #Now we check the PID from lock file matches to the current process PID if os.path.exists("/proc/%s" % old_pid): print 'Error: You already have an instance of the program running.', print 'It is running as process %s' % old_pid sys.exit(1) else: print 'Lock File is there but the program is not running.', print 'Removing lock file for pid %s' % old_pid os.remove(pidfile) #Save current pid of script to file with open(pidfile, 'w') as pf: pf.write('%s' % os.getpid()) def endCurses(): curses.echo() curses.endwin() def putOut(message): try: if gV['l'] > (gV['output_max_y']-5): gV['l']=0 ; output.erase() # if gV['l'] > gV['output_max_y']: # gV['pad_pos']+=1 # pad.refresh(gV['pad_pos'], 0, 5, 5, 10, gV['output_max_x']) output.addstr(gV['l'], 0, str(message) +'\n') output.refresh() #update the display immediately gV['l']+=1 except: print message def logError(message): #putOut('ERROR: '+str(message)) print message # http://www.forum-raspberrypi.de/Thread-python-ftp-upload-wieder-aufnehmen?pid=257332#pid257332 def file_size(path, conn): file_list = dict(conn.mlsd(os.path.dirname(path))) return int(file_list.get(os.path.basename(path), dict(size="0"))["size"]) def upload(source, dest, conn, callback=None): with open(source, "rb") as inf: server_side_size = file_size(dest, conn) inf.seek(server_side_size) conn.storbinary( "STOR /tmp/ftp-remote-test-file", inf, callback=callback, rest=str(server_side_size), ) #http://code.activestate.com/recipes/499334-remove-ftp-directory-walk-equivalent/ def ftpwalk(ftp, top, topdown=True, onerror=None): """ Generator that yields tuples of (root, dirs, nondirs). """ # Make the FTP object's current directory to the top dir. ftp.cwd(top) # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.path.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: dirs, nondirs = _ftp_listdir(ftp) except os.error, err: if onerror is not None: onerror(err) return if topdown: yield top, dirs, nondirs for entry in dirs: dname = entry[0] path = os.path.join(top, dname) if entry[-1] is None: # not a link for x in ftpwalk(ftp, path, topdown, onerror): yield x if not topdown: yield top, dirs, nondirs _calmonths = dict( (x, i+1) for i, x in enumerate(('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) ) def _ftp_listdir(ftp): """ List the contents of the FTP opbject's cwd and return two tuples of (filename, size, mtime, mode, link) one for subdirectories, and one for non-directories (normal files and other stuff). If the path is a symbolic link, 'link' is set to the target of the link (note that both files and directories can be symbolic links). Note: we only parse Linux/UNIX style listings; this could easily be extended. """ dirs, nondirs = [], [] listing = [] ftp.retrlines('LIST', listing.append) for line in listing: # Parse, assuming a UNIX listing words = line.split(None, 8) if len(words) < 6: print >> sys.stderr, 'Warning: Error reading short line', line continue # Get the filename. filename = words[-1].lstrip() if filename in ('.', '..'): continue # Get the link target, if the file is a symlink. extra = None i = filename.find(" -> ") if i >= 0: # words[0] had better start with 'l'... extra = filename[i+4:] filename = filename[:i] # Get the file size. size = int(words[4]) # Get the date. year = datetime.today().year month = _calmonths[words[5]] day = int(words[6]) mo = re.match('(\d+):(\d+)', words[7]) if mo: hour, min = map(int, mo.groups()) else: mo = re.match('(\d\d\d\d)', words[7]) if mo: year = int(mo.group(1)) hour, min = 0, 0 else: raise ValueError("Could not parse time/year in line: '%s'" % line) dt = datetime(year, month, day, hour, min) mtime = time.mktime(dt.timetuple()) # Get the type and mode. mode = words[0] entry = (filename, size, mtime, mode, extra) if mode[0] == 'd': dirs.append(entry) else: nondirs.append(entry) return dirs, nondirs def connectFtp(): connected = True if ftpTLS: ftp = FTP_TLS() else: ftp = FTP() ftp.set_debuglevel(0) try: connect = ftp.connect(ftpHost, ftpPort, 10) login = ftp.login(ftpUser, ftpPass) except OSError, e: putOut('Got error: "%s"' % e) connected = False return ftp, connected def transfer(ftp, remote_file, local_file, extension): putOut("Transfering: '"+remote_file+"'") gV['received_size'] = 0 try: with open(local_file, 'wb') as lf: def callback(chunk): lf.write(chunk) gV['received_size'] += len(chunk) recsize=float(gV['received_size'])/1024 status.move(0, 0) #move cursor to (new_y, new_x) status.clrtoeol() ; status.move(1, 0) ; status.clrtoeol() status.addstr(0, 0, '{} uploading Progress:'.format(remote_file)) status.addstr(1, 0, '{0:10} kB / {1} kB'.format(round(recsize, 2), round(gV['remote_file_sizeKB'], 2))) status.refresh() #update the display immediately gV['start_time'] = time.time() if extension in ascii_Files: ftp.retrlines("RETR " + remote_file, callback) #ftp.retrlines("RETR " + remote_file, lambda s, w=outfile.write: w(s+"\n"), callback) else: ftp.retrbinary("RETR " + remote_file, callback) except Exception, e: putOut('transfer Error: %s' % (e)) if os.path.isfile(local_file): os.remove(local_file) pass return gV['end_time'] = time.time() #check size of remote and local file to verfy complete transfer local_file_size = os.path.getsize(local_file) if local_file_size == gV['remote_file_size']: transfered.update({remote_dir : remote_file}) transferTime = round(gV['end_time'] - gV['start_time'], 3) transferSpeed = round((float(gV['remote_file_sizeKB'])/1024) / transferTime, 3) putOut('File {} ({} bytes) seems to be finished.'.format(local_file, local_file_size),) putOut('Transfer took {} sec. ({} MB/s)'.format(transferTime, transferSpeed),) if deleteAfterCopy: try: ftp.delete(remote_file) putOut('Remote File Deleted.') except Exception, e: logError(e) putOut('-----') else: putOut('!! WARNING !! "{}" seems incomplete!'.format(local_file)) putOut('local: {} remote: {}'.format(local_file_size, gV['remote_file_size'])) if __name__ == '__main__': pidfile = '/var/run/ftp_sync' write_pidfile_or_die(pidfile) gV = {} #globalVar's dictionary gV['l']=0 #output line count stdscr = curses.initscr() #init curses and create window object stdscr stdscr.clear() stdscr.refresh() #update the display immediately status = stdscr.subwin(0, 0) #(begin_y, begin_x) output = stdscr.subwin(4, 0) # http://stackoverflow.com/questions/2515244/how-to-scroll-text-in-python-curses-subwindow # http://ubuntuforums.org/showthread.php?t=1384598&p=8688465#post8688465 #output.nodelay(1) gV['output_max_y'], gV['output_max_x'] = output.getmaxyx() pad = curses.newpad(gV['output_max_y'], gV['output_max_x']) gV['pad_pos'] = 0 #pad.refresh(gV['pad_pos'], 0, 5, 5, 10, gV['output_max_x']) ftp = None try: ftp, connected = connectFtp() if not connected: putOut('Cant connect to remote! Exiting Script') sys.exit(1) for key in mirrorDirectories: localDir = key remoteDir = mirrorDirectories.get(key) if not os.path.exists(localDir): putOut('Local Directory {} doesnt Exists! Skipping!'.format(localDir)) else: # cut maybe ending '/' away.. localPath = localDir.rstrip('/') remotePath = remoteDir.rstrip('/') # remove all whitespace characters (space, tab, newline, and so on) pattern = re.compile(r'\s+') localPath = re.sub(pattern, '', localPath) remotePath = re.sub(pattern, '', remotePath) # change to remote dir try: ftp.cwd(remotePath) except OSError, e: putOut('Remote Directory {} doesnt Exists! Skipping!'.format(remotePath)) continue # go through remote dir and check if it exists local.. recursive = ftpwalk(ftp, remotePath, onerror=logError) for TopPath,subDirs,Files in recursive: #putOut(TopPath) #putOut(subDirs) #putOut(Files) remote_dir = TopPath gV['local_dir'] = remote_dir.replace(remotePath, localPath, 1) # check if remote dir exists local if not os.path.isdir(gV['local_dir']): putOut('Creating new directory: {}'.format(gV['local_dir'])) os.makedirs(gV['local_dir']) if Files: transfered = {} for File in Files: #putOut(File) fileName = File[0] Basename, Extension = os.path.splitext(fileName) if Extension in skipList or Extension.endswith('~') or Extension.endswith('#') or Basename.startswith('.'): putOut("Skipping unwanted '%s'\n" % fileName) continue remote_file = remote_dir+'/'+fileName local_file = gV['local_dir']+'/'+fileName gV['remote_file_size'] = File[1] #bytes gV['remote_file_sizeKB'] = float(gV['remote_file_size'])/1024 #kBytes # check if remote file exists local and if its newer/bigger if os.path.isfile(local_file): valid=False if os.path.getsize(local_file) == gV['remote_file_size']: putOut("Skip: {} same size: l {} Vs. r {}".format(remote_file, os.path.getsize(local_file), gV['remote_file_size'])) continue else: putOut("Bigger: {} size: l {} Vs. r {}".format(remote_file, os.path.getsize(local_file), gV['remote_file_size'])) valid=True local_mtime = int(os.path.getmtime(local_file)) remote_mtime = int(File[2]) if not valid and local_mtime != remote_mtime: if local_mtime < remote_mtime: Type='remote newer' valid=True elif local_mtime > remote_mtime: Type='local newer' elif local_mtime == remote_mtime: Type='same' if valid == False: putOut("Skip: {} with {} timestamp: l {} Vs. r {}".format(remote_file, Type, local_mtime, remote_mtime)) continue # transfere.. transfer(ftp, remote_file, local_file, Extension) # clean up if deleteAfterCopy and transfered: for remotedir in sorted(transfered, reverse=True): try: ftp.rmd(remotedir) putOut('Remote Directory deleted: %s\n' % remotedir) except Exception, e: logError(e) putOut('-----') # except Exception, e: # print 'Error: %s' % (e) except (KeyboardInterrupt, SystemExit): putOut('\nQuit\n') try: ftp.close() except: pass endCurses() try: os.remove(pidfile) except: pass
meigrafd/Sample-Code
ftp_sync.py
Python
mit
12,099
[ "VisIt" ]
712f682378d9061ad506ca6b45a5220842ed0d642e3d776c9228e0cadb37ff8d
#!/usr/bin/env python3 import os import shutil from jinja2 import Environment, FileSystemLoader from subprocess import Popen, PIPE ref_map = { 'business-cards': ['http://www.ctan.org/tex-archive/macros/latex/contrib/bizcard'], 'cheatsheet': ['http://www.stdout.org/~winston/latex/'], 'ieee-1.8': [ 'http://www.ctan.org/tex-archive/macros/latex2e/contrib/IEEEtran/', 'https://code.google.com/p/mobilecps/source/browse/#svn%2Ftrunk%2Fprojects%2Fhamilton_turner%2Fpapers' ], 'cv': ['https://github.com/bamos/cv'], 'nips': ['https://nips.cc/Conferences/2015/PaperInformation/StyleFiles'], 'presentation': ['https://github.com/bamos/beamer-snippets'], 'poster': ['http://www.brian-amberg.de/uni/poster/'] } env = Environment(loader=FileSystemLoader("website-templates"), block_start_string='~{', block_end_string='}~', variable_start_string='~{{', variable_end_string='}}~') shutil.rmtree("dist", ignore_errors=True) shutil.copytree("static", "dist") shutil.copytree("latex-templates", "dist/templates") templates_dir = "dist/templates" def runCmd(cmdStr): p = Popen(cmdStr.split(), stdout=PIPE, stderr=PIPE) out = p.communicate() ret = p.poll() if ret: print("Error: Command returned nonzero: {}.".format(ret)) print("===Stdout:\n{}".format(out[0].decode())) print("===Stderr:\n{}".format(out[1].decode())) raise Exception("Command returned nonzero: {}.".format(ret)) templates = [] for d in sorted(os.listdir(templates_dir)): print("====", d) pdf = "templates/" + d + "/" + d + ".pdf" png = "templates/" + d + "/" + d + ".png" src = "https://github.com/bamos/latex-templates/tree/master/latex-templates/{}".format( d) tar = "templates/" + d + ".tar" runCmd("tar -C dist/templates -cf dist/{} {}".format(tar, d)) full_d = templates_dir + "/" + d runCmd("make -C {}".format(full_d)) if not os.path.isfile("dist/" + pdf): for f_name in os.listdir("dist/templates/" + d): if f_name.endswith(".pdf"): pdf = "templates/" + d + "/" + f_name png = "templates/" + d + "/" + f_name[0:-4] + ".png" break if not os.path.isfile("dist/" + pdf): raise Exception("Unable to find pdf.") runCmd('convert -flatten -density 300 -trim {}[0] -quality 100 -resize 600 {}'.format( "dist/" + pdf, "dist/" + png )) ref = None if d in ref_map: ref = ref_map[d] templates.append({ 'fname': d, 'pdf': pdf, 'png': png, 'tar': tar, 'src': src, 'ref': ref }) with open("dist/index.html", "w") as idx_f: idx_f.write(env.get_template("index.jinja.html").render( templates=templates ))
bamos/latex-templates
generate.py
Python
mit
2,784
[ "Brian" ]
1364ac5b50965d2d44e21339409a1f6a36ed03f236906efd8566b79452128020
from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient from WebAppDIRAC.Lib.WebHandler import WebHandler, WErr, asyncGen from DIRAC import gConfig, gLogger from DIRAC.Core.Utilities import Time import json class TransformationMonitorHandler( WebHandler ): AUTH_PROPS = "authenticated" def index( self ): pass @asyncGen def web_getSelectionData( self ): sData = self.getSessionData() callback = {} group = sData["user"]["group"] user = sData["user"]["username"] if user == "Anonymous": callback["prod"] = [["Insufficient rights"]] else: callback = {} #### tsClient = TransformationClient() result = yield self.threadTask( tsClient.getDistinctAttributeValues, "Plugin", {} ) if result["OK"]: plugin = [] if len( result["Value"] ) > 0: for i in result["Value"]: plugin.append( [str( i )] ) else: plugin.append( "Nothing to display" ) else: plugin = "Error during RPC call" callback["plugin"] = plugin #### result = yield self.threadTask( tsClient.getDistinctAttributeValues, "Status", {} ) if result["OK"]: status = [] if len( result["Value"] ) > 0: for i in result["Value"]: status.append( [str( i )] ) else: status = "Nothing to display" else: status = "Error during RPC call" callback["prodStatus"] = status #### result = yield self.threadTask( tsClient.getDistinctAttributeValues, "TransformationGroup", {} ) if result["OK"]: group = [] if len( result["Value"] ) > 0: for i in result["Value"]: group.append( [str( i )] ) else: group = "Nothing to display" else: group = "Error during RPC call" callback["transformationGroup"] = group #### result = yield self.threadTask( tsClient.getDistinctAttributeValues, "AgentType", {} ) if result["OK"]: atype = [] if len( result["Value"] ) > 0: for i in result["Value"]: atype.append( [str( i )] ) else: atype = "Nothing to display" else: atype = "Error during RPC call" callback["agentType"] = atype #### result = yield self.threadTask( tsClient.getDistinctAttributeValues, "Type", {} ) if result["OK"]: type = [] if len( result["Value"] ) > 0: for i in result["Value"]: type.append( [str( i )] ) else: type = "Nothing to display" else: type = "Error during RPC call" callback["productionType"] = type self.finish( callback ) @asyncGen def web_getTransformationData( self ): pagestart = Time.time() callback = None sData = self.getSessionData() callback = {} user = sData["user"]["username"] tsClient = TransformationClient() if user == "Anonymous": callback = {"success":"false", "error":"You are not authorised"} else: result = self.__request() result = yield self.threadTask( tsClient.getTransformationSummaryWeb, result, self.globalSort, self.pageNumber, self.numberOfJobs ) if not result["OK"]: self.finish( json.dumps( {"success":"false", "error":result["Message"]} ) ) return result = result["Value"] if not result.has_key( "TotalRecords" ): self.finish( json.dumps( {"success":"false", "result":"", "error":"Data structure is corrupted"} ) ) return if not ( result["TotalRecords"] > 0 ): self.finish( json.dumps( {"success":"false", "result":"", "error":"There were no data matching your selection"} ) ) return if not ( result.has_key( "ParameterNames" ) and result.has_key( "Records" ) ): self.finish( json.dumps( {"success":"false", "result":"", "error":"Data structure is corrupted"} ) ) return if not ( len( result["ParameterNames"] ) > 0 ): self.finish( json.dumps( {"success":"false", "result":"", "error":"ParameterNames field is missing"} ) ) return if not ( len( result["Records"] ) > 0 ): self.finish( json.dumps( {"success":"false", "Message":"There are no data to display"} ) ) return callback = [] jobs = result["Records"] head = result["ParameterNames"] headLength = len( head ) for i in jobs: tmp = {} for j in range( 0, headLength ): tmp[head[j]] = i[j] callback.append( tmp ) total = result["TotalRecords"] if "Extras" in result: gLogger.info( result["Extras"] ) extra = result["Extras"] timestamp = Time.dateTime().strftime( "%Y-%m-%d %H:%M [UTC]" ) callback = {"success":"true", "result":callback, "total":total, "extra":extra, "date":timestamp} else: callback = {"success":"true", "result":callback, "total":total, "date":None} gLogger.info( "\033[0;31m PRODUCTION SUBMIT REQUEST: \033[0m %s" % ( Time.time() - pagestart ) ) self.finish( json.dumps( callback ) ) ################################################################################ @asyncGen def web_action( self ): try: id = int( self.request.arguments[ 'id' ][-1] ) except KeyError as excp: raise WErr( 400, "Missing %s" % excp ) callback = {} if self.request.arguments["data_kind"][0] == "getLoggingInfo": callback = yield self.threadTask( self.__getLoggingInfo, id ) elif self.request.arguments["data_kind"][0] == "fileStatus": callback = yield self.threadTask( self.__transformationFileStatus, id ) elif self.request.arguments["data_kind"][0] == "fileProcessed": callback = yield self.threadTask( self.__fileRetry, id, 'proc' ) elif self.request.arguments["data_kind"][0] == "fileNotProcessed": callback = yield self.threadTask( self.__fileRetry, id, 'not' ) elif self.request.arguments["data_kind"][0] == "fileAllProcessed": callback = yield self.threadTask( self.__fileRetry, id, 'all' ) elif self.request.arguments["data_kind"][0] == "dataQuery": callback = yield self.threadTask( self.__dataQuery, id ) elif self.request.arguments["data_kind"][0] == "additionalParams": callback = yield self.threadTask( self.__additionalParams, id ) elif self.request.arguments["data_kind"][0] == "transformationDetail": callback = yield self.threadTask( self.__transformationDetail, id ) elif self.request.arguments["data_kind"][0] == "extend": callback = yield self.threadTask( self.__extendTransformation, id ) else: callback = {"success":"false", "error":"Action is unknown!!!"} self.finish( callback ) ################################################################################ @asyncGen def web_executeOperation( self ): try: cmd = self.request.arguments[ 'action' ][-1] ids = self.request.arguments["ids"][0].split( "," ) ids = [int( i ) for i in ids ] except KeyError as excp: raise WErr( 400, "Missing %s" % excp ) tsClient = TransformationClient() agentType = 'Manual' if cmd == 'clean': status = 'Cleaning' elif cmd == 'start': status = 'Active' agentType = 'Automatic' elif cmd == 'flush': status = 'Flush' agentType = 'Automatic' elif cmd == 'stop': status = 'Stopped' elif cmd == 'complete': status = 'Completed' else: self.finish( {"success":"false", "error": "Unknown action"} ) callback = [] for i in ids: try: id = int( i ) result = yield self.threadTask( tsClient.setTransformationParameter, id, 'Status', status ) if result["OK"]: resString = "ProdID: %s set to %s successfully" % ( i, cmd ) result = yield self.threadTask( tsClient.setTransformationParameter, id, 'AgentType', agentType ) if not result["OK"]: resString = "ProdID: %s failed to set to %s: %s" % ( i, cmd, result["Message"] ) else: resString = "ProdID: %s failed due the reason: %s" % ( i, result["Message"] ) except: resString = "Unable to convert given ID %s to transformation ID" % i callback.append( resString ) callback = {"success":"true", "showResult":callback} gLogger.info( cmd, ids ) self.finish( callback ) ################################################################################ def __fileRetry( self, prodid, mode ): callback = {} tsClient = TransformationClient() if mode == "proc": res = tsClient.getTransformationFilesCount( prodid, "ErrorCount", {'Status':'Processed'} ) elif mode == "not": res = tsClient.getTransformationFilesCount( prodid, "ErrorCount", {'Status':['Unused', 'Assigned', 'Failed']} ) elif mode == "all": res = tsClient.getTransformationFilesCount( prodid, "ErrorCount" ) if not res['OK']: callback = {"success":"false", "error":res["Message"]} else: resList = [] total = res['Value'].pop( 'Total' ) if total == 0: callback = {"success":"false", "error":"No files found"} else: for status in sorted( res['Value'].keys() ): count = res['Value'][status] percent = "%.1f" % ( ( count * 100.0 ) / total ) resList.append( ( status, str( count ), percent ) ) resList.append( ( 'Total', total, '-' ) ) callback = {"success":"true", "result":resList} gLogger.info( "#######", res ) return callback ################################################################################ def __dataQuery( self, prodid ): callback = {} tsClient = TransformationClient() res = tsClient.getTransformationInputDataQuery( prodid ) gLogger.info( "-= #######", res ) if not res['OK']: callback = {"success":"false", "error":res["Message"]} else: result = res["Value"] back = [] for i in sorted( result.keys() ): back.append( [i, result[i]] ) callback = {"success":"true", "result":back} return callback ################################################################################ def __additionalParams( self, prodid ): callback = {} tsClient = TransformationClient() res = tsClient.getAdditionalParameters( prodid ) if not res['OK']: callback = {"success":"false", "error":res["Message"]} else: result = res["Value"] back = [] for i in sorted( result.keys() ): back.append( [i, result[i]] ) callback = {"success":"true", "result":back} return callback ################################################################################ def __getLoggingInfo( self, id ): callback = {} tsClient = TransformationClient() result = tsClient.getTransformationLogging( id ) if result["OK"]: result = result["Value"] if len( result ) > 0: callback = [] resultUser = gConfig.getSections( "/Security/Users" ) if resultUser["OK"]: users = resultUser["Value"] dndb = {} for j in users: dndb[gConfig.getValue( "/Security/Users/%s/DN" % j )] = j else: dndb = {} for i in result: DN = i["AuthorDN"] if dndb.has_key( DN ): i["AuthorDN"] = dndb[DN] else: i["AuthorDN"] = DN # "Owner Unknown" date = Time.toString( i["MessageDate"] ) callback.append( [i["Message"], date, i["AuthorDN"]] ) callback = {"success":"true", "result":callback} else: callback = {"success":"false", "error":"Nothing to display"} else: callback = {"success":"false", "error":result["Message"]} gLogger.info( "PRODUCTION LOG:", id ) return callback ################################################################################ def __transformationFileStatus( self, id ): callback = {} tsClient = TransformationClient() res = tsClient.getTransformationFilesCount( id, "Status" ) if not res['OK']: callback = {"success":"false", "error":res["Message"]} else: resList = [] total = res['Value'].pop( 'Total' ) if total == 0: callback = {"success":"false", "error":"No files found"} else: for status in sorted( res['Value'].keys() ): count = res['Value'][status] percent = "%.1f" % ( ( count * 100.0 ) / total ) resList.append( ( status, str( count ), percent ) ) resList.append( ( 'Total', total, '-' ) ) callback = {"success":"true", "result":resList} gLogger.info( "#######", res ) return callback ################################################################################ def __transformationDetail( self, prodid ): callback = {} tsClient = TransformationClient() res = tsClient.getTransformationParameters( prodid, ['DetailedInfo'] ) if not res["OK"]: callback = {"success":"false", "error":res["Message"]} else: callback = res['Value'] if callback: callback = {"success":"true", "result":res['Value']} else: callback = {"success":"false", "error":"Production does not have parameter 'DetailedInfo'"} gLogger.info( "#######", res ) return callback ################################################################################ def __extendTransformation( self, transid ): try: tasks = int( self.request.arguments["tasks"][-1] ) except KeyError as excp: raise WErr( 400, "Missing %s" % excp ) gLogger.info( "extend %s" % transid ) tsClient = TransformationClient() gLogger.info( "extendTransformation(%s,%s)" % ( transid, tasks ) ) res = tsClient.extendTransformation( transid, tasks ) if res["OK"]: resString = "%s extended by %s successfully" % ( transid, tasks ) else: resString = "%s failed to extend: %s" % ( transid, res["Message"] ) callback = {"success":"true", "showResult":[resString], "result":resString} gLogger.info( "#######", res ) return callback ################################################################################ @asyncGen def web_showFileStatus( self ): callback = {} start = int( self.request.arguments["start"][-1] ) limit = int( self.request.arguments["limit"][-1] ) try: id = self.request.arguments[ 'transformationId' ][-1] status = self.request.arguments[ 'status' ][-1] except KeyError as excp: raise WErr( 400, "Missing %s" % excp ) tsClient = TransformationClient() result = yield self.threadTask( tsClient.getTransformationFilesSummaryWeb, {'TransformationID':id, 'Status':status}, [["FileID", "ASC"]], start, limit ) if not result['OK']: callback = {"success":"false", "error":result["Message"]} else: result = result["Value"] if result.has_key( "TotalRecords" ) and result["TotalRecords"] > 0: if result.has_key( "ParameterNames" ) and result.has_key( "Records" ): if len( result["ParameterNames"] ) > 0: if len( result["Records"] ) > 0: callback = [] jobs = result["Records"] head = result["ParameterNames"] headLength = len( head ) for i in jobs: tmp = {} for j in range( 0, headLength ): tmp[head[j]] = i[j] callback.append( tmp ) total = result["TotalRecords"] timestamp = Time.dateTime().strftime( "%Y-%m-%d %H:%M [UTC]" ) if result.has_key( "Extras" ): extra = result["Extras"] callback = {"success":"true", "result":callback, "total":total, "extra":extra, "date":timestamp} else: callback = {"success":"true", "result":callback, "total":total, "date":timestamp} else: callback = {"success":"false", "result":"", "error":"There are no data to display"} else: callback = {"success":"false", "result":"", "error":"ParameterNames field is undefined"} else: callback = {"success":"false", "result":"", "error":"Data structure is corrupted"} else: callback = {"success":"false", "result":"", "error":"There were no data matching your selection"} self.finish( callback ) ################################################################################ def web_getTier1Sites( self ): callback = {} tier1 = gConfig.getValue( "/Website/PreferredSites", [] ) if len( tier1 ) < 1: callback = { 'success' : False, 'errors' : 'No site defined in the CS!' } else: callback = { 'success' : True, 'data' : tier1} self.finish( json.dumps( callback ) ) ################################################################################ @asyncGen def web_setSite( self ): callback = {} try: transID = int( self.request.arguments[ 'TransformationId' ][-1] ) runID = int( self.request.arguments[ 'RunNumber' ][-1] ) site = self.request.arguments[ 'Site' ][-1] except KeyError as excp: raise WErr( 400, "Missing %s" % excp ) gLogger.info( "\033[0;31m setTransformationRunsSite(%s, %s, %s) \033[0m" % ( transID, runID, site ) ) tsClient = TransformationClient() result = yield self.threadTask( tsClient.setTransformationRunsSite, transID, runID, site ) if result["OK"]: callback = {"success":"true", "result":"true"} else: callback = {"success":"false", "error":result["Message"]} self.finish( callback ) ################################################################################ def __request( self ): req = {} if "limit" in self.request.arguments: self.numberOfJobs = int( self.request.arguments["limit"][-1] ) if "start" in self.request.arguments: self.pageNumber = int( self.request.arguments["start"][-1] ) else: self.pageNumber = 0 else: self.numberOfJobs = 25 self.pageNumber = 0 if 'transformationId' in self.request.arguments: prods = list( json.loads( self.request.arguments[ 'transformationId' ][-1] ) ) if len( prods ) > 0: req['TransformationID'] = prods if 'requestId' in self.request.arguments: requests = list( json.loads( self.request.arguments[ 'requestId' ][-1] ) ) if len( requests ) > 0: req['TransformationFamily'] = requests if 'TransformationFamily' in self.request.arguments: req['TransformationFamily'] = self.request.arguments[ 'TransformationFamily' ][-1] if 'agentType' in self.request.arguments: agentType = list( json.loads( self.request.arguments["agentType"][-1] ) ) if len( agentType ) > 0: req['agentType'] = agentType if 'status' in self.request.arguments: status = list( json.loads( self.request.arguments["status"][-1] ) ) if len( status ) > 0: req['Status'] = status if 'plugin' in self.request.arguments: plugin = list( json.loads( self.request.arguments["plugin"][-1] ) ) if len( plugin ) > 0: req["Plugin"] = plugin if 'type' in self.request.arguments: type = list( json.loads( self.request.arguments["type"][-1] ) ) if len( type ) > 0: req['Type'] = type if 'transformationGroup' in self.request.arguments: group = list( json.loads( self.request.arguments["transformationGroup"][-1] ) ) if len( group ) > 0: req['TransformationGroup'] = group if 'sort' in self.request.arguments: sort = json.loads( self.request.arguments['sort'][-1] ) if len( sort ) > 0: self.globalSort = [ ["TransformationFamily", "ASC"]] for i in sort : self.globalSort += [[i['property'], i['direction']]] else: self.globalSort = [["TransformationID", "DESC"]] if 'startDate' in self.request.arguments and len( self.request.arguments["startDate"][0] ) > 0: if 'startTime' in self.request.arguments and len( self.request.arguments["startTime"][0] ) > 0: req["FromDate"] = str( self.request.arguments["startDate"][0] + " " + self.request.arguments["startTime"][0] ) else: req["FromDate"] = str( self.request.arguments["startDate"][0] ) if 'endDate' in self.request.arguments and len( self.request.arguments["endDate"][0] ) > 0: if 'endTime' in self.request.arguments and len( self.request.arguments["endTime"][0] ) > 0: req["ToDate"] = str( self.request.arguments["endDate"][0] + " " + self.request.arguments["endTime"][0] ) else: req["ToDate"] = str( self.request.arguments["endDate"][0] ) if 'date' in self.request.arguments and len( self.request.arguments["date"][0] ) > 0: req["LastUpdate"] = str( self.request.arguments["date"][0] ) gLogger.info( "REQUEST:", req ) return req
atsareg/WebAppDIRAC
WebApp/handler/TransformationMonitorHandler.py
Python
gpl-3.0
21,055
[ "DIRAC" ]
c3d1987fdb465f6953d0e610833389ffc90657af78624f3d377e1cf05a5fe728
from mpi4py import MPI from scipy import optimize from scipy import linalg import glm from lib import * from mcmc_updates_serial import mh_update from fisher_weighting import * import emulate #============================================================================== # Specialized sampling routines for parallel implementation #============================================================================== def rmh_worker_variance_hyperparams(comm, variances, MPIROOT=0,): ''' Worker side of Metropolis-Hastings step for variance hyperparameters given all other parameters. Have normal likelihood, so variance likelihood has the same form as gamma distribution. Using a log-normal prior for the shape hyperparameter and gamma prior for rate hyperparameter. Proposing from normal approximation to the conditional posterior (conditional independence chain). Parameters are log-transformed. Compute sufficient statistics locally. These statistics are used to generate a proposal, evaluate the log-target ratio, and combine these on the master to execute the MH step. The resulting draw is __not__ brought back to the workers until the next synchronization. Returns None. ''' # Sufficient statistics are (sum 1/variances, sum log 1/variances, and n) precisions = 1. / variances T = np.array([np.sum(precisions), np.sum(np.log(precisions)), np.size(precisions)]) # Combine these via reduction step comm.Reduce([T, MPI.DOUBLE], None, root=MPIROOT) # All subsequent computation is handled on the master node. # Synchronization of the resulting draw is handled separately. def rmh_master_variance_hyperparams(comm, shape_prev, rate_prev, MPIROOT=0, prior_mean_log=2.65, prior_prec_log=1. / 0.652 ** 2, prior_shape=1., prior_rate=0., brent_scale=6., fallback_upper=1e4, propDf=5.): ''' Master side of Metropolis-Hastings step for variance hyperparameters given all other parameters. Have normal likelihood, so variance likelihood has the same form as gamma distribution. Using a log-normal prior for the shape hyperparameter and gamma prior for rate hyperparameter. Proposing from normal approximation to the conditional posterior (conditional independence chain). Parameters are log-transformed. Builds normal approximation based upon local data, then combines this with others on the master process. These approximations are used to generate a proposal, which is then broadcast back to the workers. The workers then evaluate the log-target ratio and combine these on the master to execute the MH step. The resulting draw is __not__ brought back to the workers until the next synchronization. Returns a 2-tuple consisting of the new (shape, rate) and a boolean indicating acceptance. ''' # Build normal approximation to posterior of transformed hyperparameters. # Aggregating local results from workers. # This assumes that rmh_worker_nbinom_hyperparams() has been called on all # workers. T, buf = np.zeros((2, 3)) comm.Reduce(buf, T, root=MPIROOT) n = T[2] shape_hat, rate_hat = map_estimator_gamma(x=None, T=T, log=True, prior_shape=prior_shape, prior_rate=prior_rate, prior_mean_log=prior_mean_log, prior_prec_log=prior_prec_log, brent_scale=brent_scale, fallback_upper=fallback_upper) theta_hat = np.log(np.array([shape_hat, rate_hat])) # Propose using a bivariate normal approximate to the joint conditional # posterior of (shape, rate) # Compute posterior information matrix for parameters info = info_posterior_gamma(shape=shape_hat, rate=rate_hat, x=None, T=T, log=True, prior_shape=prior_shape, prior_rate=prior_rate, prior_mean_log=prior_mean_log, prior_prec_log=prior_prec_log) # Cholesky decompose information matrix for bivariate draw and # density calculations U = linalg.cholesky(info, lower=False) # Propose shape and rate parameter jointly z_prop = (np.random.randn(2) / np.sqrt(np.random.gamma(shape=propDf / 2., scale=2., size=2) / propDf)) theta_prop = theta_hat + linalg.solve_triangular(U, z_prop) shape_prop, rate_prop = np.exp(theta_prop) # Demean and decorrelate previous draws theta_prev = np.log(np.array([shape_prev, rate_prev])) z_prev = np.dot(U, theta_prev - theta_hat) # Compute log-ratio of target densities. log_target_ratio = \ - n * (special.gammaln(shape_prop) - special.gammaln(shape_prev)) \ + n * (shape_prop * np.log(rate_prop) - shape_prev * np.log(rate_prev)) \ + (shape_prop - shape_prev) * T[1] \ - (rate_prop - rate_prev) * T[0] # Add log-prior ratio if prior_prec_log > 0: # Add the log-normal prior on the shape parameter log_target_ratio += (dlnorm(shape_prop, mu=prior_mean_log, sigmasq=1. / prior_prec_log, log=True) - dlnorm(shape_prev, mu=prior_mean_log, sigmasq=1. / prior_prec_log, log=True)) # Add the gamma prior on the rate parameter if prior_rate > 0: log_target_ratio += (dgamma(rate_prop, shape=prior_shape, rate=prior_rate, log=True) - dgamma(rate_prev, shape=prior_shape, rate=prior_rate, log=True)) else: log_target_ratio += np.log(rate_prop / rate_prev) * (shape_prop - 1.) # Compute log-ratio of proposal densities # These are transformed bivariate t's with equivalent covariance # matrices, so the resulting Jacobian terms cancel. We are left to # contend with the z's and the Jacobian terms resulting from # exponentiation. log_prop_ratio = -np.sum(np.log(1. + z_prop ** 2 / propDf) - np.log(1. + z_prev ** 2 / propDf)) log_prop_ratio *= (propDf + 1.) / 2. log_prop_ratio += -np.sum(theta_prop - theta_prev) # Execute MH update return mh_update( prop=(shape_prop, rate_prop), prev=(shape_prev, rate_prev), log_target_ratio=log_target_ratio, log_prop_ratio=log_prop_ratio) def rmh_worker_nbinom_hyperparams(comm, x, r_prev, p_prev, MPIROOT=0, prior_mean_log=2.65, prior_prec_log=1. / 0.652 ** 2, prior_a=1., prior_b=1., brent_scale=6., fallback_upper=10000., correct_prior=True, method='newton', coverage_prob=0.999, grid_min_spacing=0.5, cov=emulate.cov_sqexp): ''' Worker side of Metropolis-Hastings step for negative-binomial hyperparameters given all other parameters. Using a log-normal prior for the r (convolution) hyperparameter and a conditionally-conjugate beta prior for p. Proposing from normal approximation to the conditional posterior (conditional independence chain). Parameters are log- and logit-transformed. Builds normal approximation based upon local data, then combines this with others on the master process. These approximations are used to generate a proposal, which is then broadcast back to the workers. The workers then evaluate the log-target ratio and combine these on the master to execute the MH step. The resulting draw is __not__ brought back to the workers until the next synchronization. Returns None. ''' # Correct / adjust prior for distributed approximation, if requested adj = 1. if correct_prior: adj = comm.Get_size() - 1. # Setup arguments nbinom_args = dict(x=x, prior_a=prior_a, prior_b=prior_b, prior_mean_log=prior_mean_log, prior_prec_log=prior_prec_log, prior_adj=adj) # Compute posterior mode for r and p using profile log-posterior r_hat, p_hat = map_estimator_nbinom(transform=True, brent_scale=brent_scale, fallback_upper=fallback_upper, **nbinom_args) # Propose using a bivariate normal approximate to the joint conditional # posterior of (r, p) # Compute posterior information matrix for parameters info = info_posterior_nbinom(r=r_hat, p=p_hat, transform=True, **nbinom_args) # Transform point estimate theta_hat = np.log(np.array([r_hat, p_hat])) theta_hat[1] -= np.log(1. - p_hat) if method == 'emulate': # Build local emulator for score function grid_radius = emulate.approx_quantile(coverage_prob=coverage_prob, d=2, n=adj) L = linalg.solve_triangular(linalg.cholesky(info, lower=True), np.eye(2), lower=True) emulator = emulate.build_emulator( score_posterior_nbinom_vec, center=theta_hat, slope_mean=L, cov=cov, grid_min_spacing=grid_min_spacing, grid_radius=grid_radius, f_kwargs=nbinom_args) # Send emulator to master node emulate.aggregate_emulators_mpi( comm=comm, emulator=emulator, MPIROOT=MPIROOT) else: # Build necessary quantities for distributed posterior approximation z_hat = np.dot(info, theta_hat) # Condense approximation to a single vector for reduction approx = np.r_[z_hat, info[np.tril_indices(2)]] # Combine with other approximations on master. comm.Reduce([approx, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # Receive settings for refinement settings = np.zeros(2, dtype=int) comm.Bcast([settings, MPI.INT], root=MPIROOT) n_iter, final_info = settings # Newton-Raphson iterations for refinement of approximation for i in xrange(n_iter): # Receive updated estimate from master comm.Bcast([theta_hat, MPI.DOUBLE], root=MPIROOT) # Compute score and information matrix at combined estimate r_hat = np.exp(theta_hat[0]) p_hat = 1. / (1. + np.exp(-theta_hat[1])) grad = score_posterior_nbinom_vec(theta_hat, **nbinom_args).flatten() info = info_posterior_nbinom(r=r_hat, p=p_hat, transform=True, **nbinom_args) # Condense update to a single vector for reduction update = np.r_[grad, info[np.tril_indices(2)]] # Combine with other updates on master comm.Reduce([update, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # Contribute to final information matrix refinement if requested if final_info: # Receive updated estimate comm.Bcast([theta_hat, MPI.DOUBLE], root=MPIROOT) r_hat = np.exp(theta_hat[0]) p_hat = 1. / (1 + np.exp(-theta_hat[1])) info = info_posterior_nbinom(r=r_hat, p=p_hat, transform=True, **nbinom_args) # Combine informations on master comm.Reduce([info[np.tril_indices(2)], MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # Obtain proposed value of theta from master. theta_prop = np.empty(2) comm.Bcast([theta_prop, MPI.DOUBLE], root=MPIROOT) r_prop, p_prop = np.exp(theta_prop) p_prop = p_prop / (1. + p_prop) # Compute log-ratio of target densities, omitting prior. # Log-ratio of prior densities is handled on the master. # Only component is log-likelihood ratio for x. log_target_ratio = np.sum(dnbinom(x, r=r_prop, p=p_prop, log=True) - dnbinom(x, r=r_prev, p=p_prev, log=True)) # Reduce log-target ratio for MH step on master. comm.Reduce([np.array(log_target_ratio), MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # All subsequent computation is handled on the master node. # Synchronization of the resulting draw is handled separately. def rmh_master_nbinom_hyperparams(comm, r_prev, p_prev, MPIROOT=0, prior_mean_log=2.65, prior_prec_log=1. / 0.652 ** 2, prior_a=1., prior_b=1., propDf=5., method='newton', cov=emulate.cov_sqexp, n_iter_refine=10, final_info_refine=1): ''' Master side of Metropolis-Hastings step for negative-binomial hyperparameters given all other parameters. Using a log-normal prior for the r (convolution) hyperparameter and a conditionally-conjugate beta prior for p. Proposing from normal approximation to the conditional posterior (conditional independence chain). Parameters are log- and logit-transformed. Builds normal approximation based upon local data, then combines this with others on the master process. These approximations are used to generate a proposal, which is then broadcast back to the workers. The workers then evaluate the log-target ratio and combine these on the master to execute the MH step. The resulting draw is __not__ brought back to the workers until the next synchronization. Returns a 2-tuple consisting of the new (shape, rate) and a boolean indicating acceptance. ''' if method=='emulate': # Gather emulators from workers emulator = emulate.aggregate_emulators_mpi( comm=comm, emulator=None, MPIROOT=MPIROOT, info=lambda e: linalg.cho_solve((e['slope_mean'], True), np.eye(e['slope_mean'].shape[0]))) # Find root of combined approximate score function theta_hat = emulator['center'] theta_hat = optimize.fsolve( func=emulate.evaluate_emulator, x0=theta_hat, args=(emulator, cov)) # Compute Cholesky decomposition of approximate combined information # for proposal U = linalg.cholesky(emulator['info'], lower=False) elif method == 'newton': # Build normal approximation to posterior of transformed hyperparameters. # Aggregating local results from workers. # This assumes that rmh_worker_nbinom_hyperparameters() has been called # on all workers. theta_hat, prec = posterior_approx_distributed( comm=comm, dim_param=2, MPIROOT=MPIROOT) # Refine approximation with single Newton-Raphson step theta_hat, prec = refine_distributed_approx( comm=comm, est=theta_hat, prec=prec, dim_param=2, n_iter=n_iter_refine, final_info=final_info_refine, MPIROOT=MPIROOT) # Cholesky decompose precision matrix for draws and density calculations U = linalg.cholesky(prec, lower=False) else: print >> sys.stderr, "Error - method %s unknown" % method return # Propose r and p jointly z_prop = (np.random.randn(2) / np.sqrt(np.random.gamma(shape=propDf / 2., scale=2., size=2) / propDf)) theta_prop = theta_hat + linalg.solve_triangular(U, z_prop) r_prop, p_prop = np.exp(theta_prop) p_prop = p_prop / (1. + p_prop) # Demean and decorrelate previous draws theta_prev = np.log(np.array([r_prev, p_prev])) theta_prev[1] -= np.log(1. - p_prev) z_prev = np.dot(U, theta_prev - theta_hat) # Broadcast theta_prop to workers comm.Bcast([theta_prop, MPI.DOUBLE], root=MPIROOT) # Compute log-ratio of target densities. # Start by obtaining likelihood component from workers. log_target_ratio = np.array(0.) buf = np.array(0.) comm.Reduce([buf, MPI.DOUBLE], [log_target_ratio, MPI.DOUBLE], op=MPI.SUM, root=MPIROOT) if prior_prec_log > 0: # Add the log-normal prior on r log_target_ratio += (dlnorm(r_prop, mu=prior_mean_log, sigmasq=1. / prior_prec_log, log=True) - dlnorm(r_prev, mu=prior_mean_log, sigmasq=1. / prior_prec_log, log=True)) # Add the beta prior on p log_target_ratio += (dbeta(p_prop, a=prior_a, b=prior_b, log=True) - dbeta(p_prev, a=prior_a, b=prior_b, log=True)) # Compute log-ratio of proposal densities # These are transformed bivariate t's with equivalent covariance # matrices, so the resulting Jacobian terms cancel. We are left to # contend with the z's and the Jacobian terms resulting from the # exponential and logit transformations. log_prop_ratio = -np.sum(np.log(1. + z_prop ** 2 / propDf) - np.log(1. + z_prev ** 2 / propDf)) log_prop_ratio *= (propDf + 1.) / 2. log_prop_ratio += -(np.log(r_prop) - np.log(r_prev)) log_prop_ratio += -(np.log(p_prop) + np.log(1. - p_prop) - np.log(p_prev) - np.log(1. - p_prev)) # Execute MH update return mh_update(prop=(r_prop, p_prop), prev=(r_prev, p_prev), log_target_ratio=log_target_ratio, log_prop_ratio=log_prop_ratio) def rmh_worker_glm_coef(comm, b_hat, b_prev, y, X, I, family, w=1, V=None, method='newton', MPIROOT=0, coverage_prob=0.999, grid_min_spacing=0.5, cov=emulate.cov_sqexp, **kwargs): ''' Worker component of single Metropolis-Hastings step for GLM coefficients using a normal approximation to their posterior distribution. Proposes linearly-transformed vector of independent t_propDf random variables. At least one of I (the Fisher information) and V (the inverse Fisher information) must be provided. If I is provided, V is ignored. It is more efficient to provide the information matrix than the covariance matrix. Returns None. ''' # Get number of workers n_workers = comm.Get_size() - 1 # Get dimensions p = X.shape[1] if method == 'emulate': # Build local emulator for score function grid_radius = emulate.approx_quantile(coverage_prob=coverage_prob, d=p, n=n_workers) if V is None: L = linalg.solve_triangular(linalg.cholesky(I, lower=True), np.eye(p), lower=True) else: L = linalg.cholesky(V, lower=True) emulator = emulate.build_emulator( glm.score, center=b_hat, slope_mean=L, cov=cov, grid_min_spacing=grid_min_spacing, grid_radius=grid_radius, f_kwargs={'y' : y, 'X' : X, 'w' : w, 'family' : family}) # Send emulator to master node emulate.aggregate_emulators_mpi( comm=comm, emulator=emulator, MPIROOT=MPIROOT) elif method == 'newton': # Build necessary quantities for distributed posterior approximation z_hat = np.dot(I, b_hat) # Condense approximation to a single vector for reduction approx = np.r_[z_hat, I[np.tril_indices(p)]] # Combine with other approximations on master. comm.Reduce([approx, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # Receive settings for refinement settings = np.zeros(2, dtype=int) comm.Bcast([settings, MPI.INT], root=MPIROOT) n_iter, final_info = settings # Newton-Raphson iterations for refinement of approximation for i in xrange(n_iter): # Receive updated estimate from master comm.Bcast([b_hat, MPI.DOUBLE], root=MPIROOT) # Compute score and information matrix at combined estimate eta = np.dot(X, b_hat) mu = family.link.inv(eta) weights = w * family.weights(mu) dmu_deta = family.link.deriv(eta) sqrt_W_X = (X.T * np.sqrt(weights)).T grad = np.dot(X.T, weights / dmu_deta * (y - mu)) info = np.dot(sqrt_W_X.T, sqrt_W_X) # Condense update to a single vector for reduction update = np.r_[grad, info[np.tril_indices(p)]] # Combine with other updates on master comm.Reduce([update, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # Contribute to final information matrix refinement if requested if final_info: # Receive updated estimate comm.Bcast([b_hat, MPI.DOUBLE], root=MPIROOT) # Update information matrix eta = np.dot(X, b_hat) mu = family.link.inv(eta) weights = w * family.weights(mu) sqrt_W_X = (X.T * np.sqrt(weights)).T info = np.dot(sqrt_W_X.T, sqrt_W_X) # Combine informations on master comm.Reduce([info[np.tril_indices(p)], MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) else: print >> sys.stderr, "Error - method %s unknown" % method return # Obtain proposed value of coefficients from master. b_prop = np.empty(p) comm.Bcast([b_prop, MPI.DOUBLE], root=MPIROOT) # Compute proposed and previous means eta_prop = np.dot(X, b_prop) eta_prev = np.dot(X, b_prev) mu_prop = family.link.inv(eta_prop) mu_prev = family.link.inv(eta_prev) # Compute log-ratio of target densities log_target_ratio = np.sum(family.loglik(y=y, mu=mu_prop, w=w) - family.loglik(y=y, mu=mu_prev, w=w)) # Reduce log-target ratio for MH step on master. comm.Reduce([np.array(log_target_ratio), MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # All subsequent computation is handled on the master node. # Synchronization of the resulting draw is handled separately. def rmh_master_glm_coef(comm, b_prev, MPIROOT=0, propDf=5., method='newton', cov=emulate.cov_sqexp, n_iter_refine=2, final_info_refine=1, prior_log_density=None, prior_args=tuple(), prior_kwargs={}): ''' Master component of single Metropolis-Hastings step for GLM coefficients using a normal approximation to their posterior distribution. Proposes linearly-transformed vector of independent t_propDf random variables. Builds normal approximation based upon local data, then combines this with others on the master process. These approximations are used to generate a proposal, which is then broadcast back to the workers. The workers then evaluate the log-target ratio and combine these on the master to execute the MH step. The resulting draw is __not__ brought back to the workers until the next synchronization. Returns a 2-tuple consisting of the resulting coefficients and a boolean indicating acceptance. ''' # Compute dimensions p = np.size(b_prev) if method == 'emulate': # Gather emulators from workers emulator = emulate.aggregate_emulators_mpi( comm=comm, emulator=None, MPIROOT=MPIROOT, info=lambda e: linalg.cho_solve((e['slope_mean'], True), np.eye(e['slope_mean'].shape[0]))) # Find root of combined approximate score function b_hat = emulator['center'] b_hat = optimize.fsolve( func=emulate.evaluate_emulator, x0=b_hat, args=(emulator, cov)) # Compute Cholesky decomposition of approximate combined information # for proposal U = linalg.cholesky(emulator['info'], lower=False) else: # Build normal approximation to posterior of transformed hyperparameters. # Aggregating local results from workers. # This assumes that rmh_worker_nbinom_glm_coef() has been called on all # workers. b_hat, prec = posterior_approx_distributed( comm=comm, dim_param=p, MPIROOT=MPIROOT) # Refine approximation with single Newton-Raphson step b_hat, prec = refine_distributed_approx( comm=comm, est=b_hat, prec=prec, dim_param=p, n_iter=n_iter_refine, final_info=final_info_refine, MPIROOT=MPIROOT) # Cholesky decompose precision matrix for draws and density calculations U = linalg.cholesky(prec, lower=False) # Propose from linearly-transformed t with appropriate mean and covariance z_prop = (np.random.randn(p) / np.sqrt(np.random.gamma(shape=propDf / 2., scale=2., size=p) / propDf)) b_prop = b_hat + linalg.solve_triangular(U, z_prop, lower=False) # Demean and decorrelate previous draw of b z_prev = np.dot(U, b_prev - b_hat) # Broadcast b_prop to workers comm.Bcast([b_prop, MPI.DOUBLE], root=MPIROOT) # Compute log-ratio of target densities. # Start by obtaining likelihood component from workers. log_target_ratio = np.array(0.) buf = np.array(0.) comm.Reduce([buf, MPI.DOUBLE], [log_target_ratio, MPI.DOUBLE], op=MPI.SUM, root=MPIROOT) if prior_log_density is not None: log_target_ratio += ( prior_log_density(b_prop, *prior_args, **prior_kwargs) - prior_log_density(b_prev, *prior_args, **prior_kwargs)) # Compute log-ratio of proposal densities. This is very easy with the # demeaned and decorrelated values z. log_prop_ratio = -(propDf + 1.) / 2. * \ np.sum(np.log(1. + z_prop ** 2 / propDf) - \ np.log(1. + z_prev ** 2 / propDf)) return mh_update(prop=b_prop, prev=b_prev, log_target_ratio=log_target_ratio, log_prop_ratio=log_prop_ratio) def rgibbs_worker_p_rnd_cen(comm, n_rnd_cen, n_states, MPIROOT=0): ''' Worker component of Gibbs update for p_rnd_cen given all other parameters. This is a conjugate beta draw with Bernoulli observations. n_rnd_cen must be an integer with the total number of randomly-censored states. n_states must be an integer with the total number of states (including imputed). ''' # Combine counts with other workers on master n = np.array([n_rnd_cen, n_states], dtype=np.int) comm.Reduce([n, MPI.INT], None, op=MPI.SUM, root=MPIROOT) # All subsequent computation is handled on the master node. # Synchronization of the resulting draw is handled separately. def rgibbs_master_p_rnd_cen(comm, MPIROOT=0, prior_a=1., prior_b=1.): ''' Master component of Gibbs update for p_rnd_cen given all other parameters. This is a conjugate beta draw with Bernoulli observations. prior_a and prior_b are the parameters of a conjugate beta prior. ''' # Collect counts of randomly censored and total states from workers n = np.empty(2, dtype=np.int) buf = np.zeros(2, dtype=np.int) comm.Reduce([buf, MPI.INT], [n, MPI.INT], op=MPI.SUM, root=MPIROOT) n_rnd_cen = n[0] n_states = n[1] p_rnd_cen = np.random.beta(a=n_rnd_cen + prior_a, b=n_states - n_rnd_cen + prior_b) return p_rnd_cen def rgibbs_worker_beta(comm, concentrations, gamma_bar, tausq, n_peptides, MPIROOT=0): ''' Worker components of Gibbs update for beta parameter of concentration-intensity relationship. Can be used for both the Rao-Blackwellized and conditional versions. Acts as a wrapper around the posterior_approx_distributed logic, as the likelihood is exactly Gaussian. Adds special handling for the case where no concentrations are provided, sending 0s for the estimate and precision. ''' # Save dimensions p = 2 if np.size(concentrations) < 1: # No observations for the model, send zeros approx = np.zeros(p + p*(p+1)/2) else: # Get sufficient statistics from linear regression # Avoiding actual regression routine because of reduced-rank cases sqrt_w = np.sqrt(n_peptides / tausq) X = np.ones((np.size(concentrations), p)) X[:, 1] = concentrations Xw = (X.T * sqrt_w).T yw = gamma_bar*sqrt_w XwtXw = np.dot(Xw.T, Xw) Xwtyw = np.dot(Xw.T, yw) # Condense approximation to a single vector for reduction approx = np.r_[Xwtyw, XwtXw[np.tril_indices(p)]] # Combine with other approximations on master. comm.Reduce([approx, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # All subsequent computation is done on the master node # The resulting draw of beta is not brought back to the workers until the # next synchronization event. def rgibbs_master_beta(comm, MPIROOT=0, prior_mean=np.array([0., 1.]), prior_prec=np.array([0., 0.]), prior_trunc_b1=(-np.Inf, np.Inf)): # Save dimensions p = 2 # Aggregating local results from workers. # This assumes that rgibbs_worker_beta() has been called on all workers. b_hat, prec = posterior_approx_distributed(comm=comm, dim_param=p, MPIROOT=MPIROOT) # Get posterior covariance Sigma = linalg.solve(prec, np.eye(p), sym_pos=True) # Draw beta_1 from truncated distribution beta = np.empty(2) beta[1] = np.random.randn(1) * np.sqrt(Sigma[1,1]) + b_hat[1] while beta[1] < prior_trunc_b1[0] or beta[1] > prior_trunc_b1[1]: beta[1] = np.random.randn(1) * np.sqrt(Sigma[1,1]) + b_hat[1] # Draw beta_0 from conditional posterior given beta_1 beta[0] = np.random.randn(1) * \ np.sqrt(Sigma[0,0] - Sigma[0,1]**2 / Sigma[1,1]) + \ b_hat[0] + Sigma[0,1] / Sigma[1,1] * \ (beta[1] - b_hat[1]) return beta def rgibbs_worker_concentration_dist(comm, concentrations, MPIROOT=0): ''' Gibbs update for hyperparameters of concentration distribution. Very simple, sending mean, variance, and n to master. n is a vital part of the sufficient statistic here. ''' # Compute sufficient statistics n = np.size(concentrations) s = np.r_[n * np.mean(concentrations), n * np.var(concentrations, ddof=0), n] # Combine on master comm.Reduce([s, MPI.DOUBLE], None, op=MPI.SUM, root=MPIROOT) # All subsequent computation is handled on the master node. # Synchronization of the resulting draw is handled separately. def rgibbs_master_concentration_dist(comm, MPIROOT=0, prior_shape=1., prior_rate=0.): ''' Gibbs update for hyperparameters of concentration distribution. Very simple, sending mean, variance, and n to master. n is a vital part of the sufficient statistic here. ''' # Aggregate sufficient statistics from workers s = np.zeros(3) buf = np.zeros(3) comm.Reduce([buf, MPI.DOUBLE], [s, MPI.DOUBLE], op=MPI.SUM, root=MPIROOT) post_mean = s[0] / s[2] prec_concentration = np.random.gamma( shape=prior_shape + (s[2] - 1.) / 2., scale=1. / (prior_rate + s[1] / 2.)) mean_concentration = np.random.normal( loc=post_mean, scale=np.sqrt(1. / prec_concentration / s[2])) return (mean_concentration, prec_concentration)
awblocker/quantitation
lib/quantitation/mcmc_updates_parallel.py
Python
bsd-3-clause
32,314
[ "Gaussian" ]
eec521bfcad6dc9816d080466008191e9e45a6e4cb6323805d48d566a76caf6c
#!/usr/bin/env python ######################################################################## # File : dirac-admin-site-mask-logging # Author : Stuart Paterson ######################################################################## """ Retrieves site mask logging information. Example: $ dirac-admin-site-mask-logging LCG.IN2P3.fr Site Mask Logging Info for LCG.IN2P3.fr Active 2010-12-08 21:28:16 ( atsareg ) """ import DIRAC from DIRAC.Core.Utilities.DIRACScript import DIRACScript as Script @Script() def main(): # Registering arguments will automatically add their description to the help menu Script.registerArgument(["Site: Name of the Site"]) _, args = Script.parseCommandLine(ignoreErrors=True) from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin diracAdmin = DiracAdmin() exitCode = 0 errorList = [] for site in args: result = diracAdmin.getSiteMaskLogging(site, printOutput=True) if not result["OK"]: errorList.append((site, result["Message"])) exitCode = 2 for error in errorList: print("ERROR %s: %s" % error) DIRAC.exit(exitCode) if __name__ == "__main__": main()
ic-hep/DIRAC
src/DIRAC/Interfaces/scripts/dirac_admin_site_mask_logging.py
Python
gpl-3.0
1,199
[ "DIRAC" ]
e47e16d1b54b10c886a2086a0153b5666cbd86e4a08f7b354778283b352944a0
import uuid import jobs.test_rules from galaxy.jobs.mapper import ( JobRunnerMapper, ERROR_MESSAGE_NO_RULE_FUNCTION, ERROR_MESSAGE_RULE_FUNCTION_NOT_FOUND, ) from galaxy.jobs import JobDestination from galaxy.util import bunch WORKFLOW_UUID = uuid.uuid1().hex TOOL_JOB_DESTINATION = JobDestination() DYNAMICALLY_GENERATED_DESTINATION = JobDestination() def test_static_mapping(): mapper = __mapper() assert mapper.get_job_destination( {} ) is TOOL_JOB_DESTINATION def test_caching(): mapper = __mapper() mapper.get_job_destination( {} ) mapper.get_job_destination( {} ) assert mapper.job_wrapper.tool.call_count == 1 def test_dynamic_mapping(): mapper = __mapper( __dynamic_destination( dict( function="upload" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == "local_runner" def test_dynamic_mapping_priorities(): mapper = __mapper( __dynamic_destination( dict( function="tophat" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION # Next line verifies we using definition in 20_instance.py instead of # 10_site.py. assert mapper.job_config.rule_response == "instance_dest_id" def test_dynamic_mapping_defaults_to_tool_id_as_rule(): mapper = __mapper( __dynamic_destination( ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == "tool1_dest_id" def test_dynamic_mapping_job_conf_params(): mapper = __mapper( __dynamic_destination( dict( function="check_job_conf_params", param1="7" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == "sent_7_dest_id" def test_dynamic_mapping_function_parameters(): mapper = __mapper( __dynamic_destination( dict( function="check_rule_params" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == "all_passed" def test_dynamic_mapping_resource_parameters(): mapper = __mapper( __dynamic_destination( dict( function="check_resource_params" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == "have_resource_params" def test_dynamic_mapping_workflow_invocation_parameter(): mapper = __mapper( __dynamic_destination( dict( function="check_workflow_invocation_uuid" ) ) ) assert mapper.get_job_destination( {} ) is DYNAMICALLY_GENERATED_DESTINATION assert mapper.job_config.rule_response == WORKFLOW_UUID def test_dynamic_mapping_no_function(): dest = __dynamic_destination( dict( ) ) mapper = __mapper( dest ) mapper.job_wrapper.tool.all_ids = [ "no_such_function" ] error_message = ERROR_MESSAGE_NO_RULE_FUNCTION % dest __assert_mapper_errors_with_message( mapper, error_message ) def test_dynamic_mapping_missing_function(): dest = __dynamic_destination( dict( function="missing_func" ) ) mapper = __mapper( dest ) mapper.job_wrapper.tool.all_ids = [ "no_such_function" ] error_message = ERROR_MESSAGE_RULE_FUNCTION_NOT_FOUND % ( "missing_func" ) __assert_mapper_errors_with_message( mapper, error_message ) def __assert_mapper_errors_with_message( mapper, message ): exception = None try: mapper.get_job_destination( {} ) except Exception as e: exception = e assert exception assert str( exception ) == message, "%s != %s" % ( str( exception ), message ) def __mapper( tool_job_destination=TOOL_JOB_DESTINATION ): job_wrapper = MockJobWrapper( tool_job_destination ) job_config = MockJobConfig() mapper = JobRunnerMapper( job_wrapper, {}, job_config ) mapper.rules_module = jobs.test_rules return mapper def __dynamic_destination( params={} ): return JobDestination( runner="dynamic", params=params ) class MockJobConfig( object ): def __init__( self ): self.rule_response = None self.dynamic_params = None def get_destination( self, rep ): # Called to transform dynamic job destination rule response # from destination id/runner url into a dynamic job destination. self.rule_response = rep return DYNAMICALLY_GENERATED_DESTINATION class MockJobWrapper( object ): def __init__( self, tool_job_destination ): self.tool = MockTool( tool_job_destination ) self.job_id = 12345 self.app = object() def is_mock_job_wrapper( self ): return True def get_job(self): raw_params = { "threshold": 8, "__workflow_invocation_uuid__": WORKFLOW_UUID, } def get_param_values( app, ignore_errors ): assert app == self.app params = raw_params.copy() params[ "__job_resource" ] = { "__job_resource__select": "True", "memory": "8gb" } return params return bunch.Bunch( user=bunch.Bunch( id=6789, email="test@example.com" ), raw_param_dict=lambda: raw_params, get_param_values=get_param_values ) class MockTool( object ): def __init__( self, tool_job_destination ): self.id = "testtoolshed/devteam/tool1/23abcd13123" self.call_count = 0 self.tool_job_destination = tool_job_destination self.all_ids = [ "testtoolshed/devteam/tool1/23abcd13123", "tool1" ] def get_job_destination( self, params ): self.call_count += 1 return self.tool_job_destination def is_mock_tool( self ): return True
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/test/unit/jobs/test_mapper.py
Python
gpl-3.0
5,801
[ "Galaxy" ]
90a12c8db03d252e979e6bc917535ea360dd3e9952f8fd11f26ba2e2b6fc162f
import copy import Code.SQL.Base as SQLBase class BMT(SQLBase.DBBase): def __init__(self, nomFichero): SQLBase.DBBase.__init__(self, nomFichero) self.tabla = "DATOS" if not self.existeTabla(self.tabla): cursor = self.conexion.cursor() for sql in ( "CREATE TABLE %s( ESTADO VARCHAR(1),ORDEN INTEGER,NOMBRE TEXT,EXTRA TEXT,TOTAL INTEGER,HECHOS INTEGER," "PUNTOS INTEGER,MAXPUNTOS INTEGER,FINICIAL VARCHAR(8),FFINAL VARCHAR(8),SEGUNDOS INTEGER,REPE INTEGER,BMT_LISTA BLOB,HISTORIAL BLOB);", "CREATE INDEX [NOMBRE] ON '%s'(ORDEN DESC,NOMBRE);"): cursor.execute(sql % self.tabla) self.conexion.commit() cursor.close() self.db = None def leerDBF(self, siTerminadas): select = "ESTADO,ORDEN,NOMBRE,EXTRA,TOTAL,HECHOS,PUNTOS,MAXPUNTOS,FFINAL,SEGUNDOS,REPE" condicion = "HECHOS=TOTAL" if siTerminadas else "HECHOS<TOTAL" orden = "ORDEN DESC,NOMBRE" dbf = self.dbf(self.tabla, select, condicion, orden) dbf.leer() self.db = dbf return dbf def cerrar(self): if self.db: self.db.cerrar() self.db = None if self.conexion: self.conexion.close() self.conexion = None class BMT_Uno: def __init__(self, fen, mrm, maxPuntos, clpartida): self.fen = fen self.mrm = mrm self.ponColor() self.puntos = maxPuntos self.maxPuntos = maxPuntos self.segundos = 0 self.estado = 0 self.siTerminado = False self.clpartida = clpartida def ponColor(self): siBlancas = "w" in self.fen self.mrm.siBlancas = siBlancas for rm in self.mrm.liMultiPV: rm.siBlancas = siBlancas def condiciones(self): try: return "%s - %d %s" % (self.mrm.nombre, self.mrm.tiempo / 1000, _("Second(s)")) if self.mrm.nombre else "" except: return "" def actualizaEstado(self): self.estado = 0 if self.siTerminado: if self.maxPuntos: self.estado = int(7.0 * self.puntos / self.maxPuntos) + 1 def reiniciar(self): for rm in self.mrm.liMultiPV: rm.siElegirPartida = False self.puntos = self.maxPuntos self.segundos = 0 self.estado = 0 self.siTerminado = False def siHayPrimero(self): for rm in self.mrm.liMultiPV: if rm.siPrimero: return rm return None class BMT_Lista: def __init__(self): self.liBMT_Uno = [] self.dicPartidas = {} def compruebaColor(self): for uno in self.liBMT_Uno: uno.ponColor() def nuevo(self, bmt_uno): self.liBMT_Uno.append(bmt_uno) def __len__(self): return len(self.liBMT_Uno) def estado(self, num): return self.liBMT_Uno[num].estado def siTerminado(self, num): return self.liBMT_Uno[num].siTerminado def siTerminada(self): for bmt in self.liBMT_Uno: if not bmt.siTerminado: return False return True def compruebaPartida(self, clpartida, txtPartida): if clpartida not in self.dicPartidas: self.dicPartidas[clpartida] = txtPartida def dameUno(self, num): return self.liBMT_Uno[num] def maxPuntos(self): mx = 0 for bmt in self.liBMT_Uno: mx += bmt.maxPuntos return mx def reiniciar(self): for bmt in self.liBMT_Uno: bmt.reiniciar() def calculaTHPSE(self): hechos = 0 t_estado = 0 t_segundos = 0 total = len(self.liBMT_Uno) t_puntos = 0 for uno in self.liBMT_Uno: if uno.siTerminado: hechos += 1 t_estado += uno.estado t_puntos += uno.puntos t_segundos += uno.segundos return total, hechos, t_puntos, t_segundos, t_estado def extrae(self, desde, hasta): nv = BMT_Lista() for x in range(desde, hasta): uno = copy.deepcopy(self.liBMT_Uno[x]) if uno.clpartida: nv.dicPartidas[uno.clpartida] = self.dicPartidas[uno.clpartida] uno.reiniciar() nv.nuevo(uno) return nv def extraeLista(self, lni): nv = BMT_Lista() for num, bmt in enumerate(self.liBMT_Uno): if lni.siEsta(num + 1): uno = copy.deepcopy(bmt) if uno.clpartida: nv.dicPartidas[uno.clpartida] = self.dicPartidas[uno.clpartida] uno.reiniciar() nv.nuevo(uno) return nv
lukasmonk/lucaschess
Code/BMT.py
Python
gpl-2.0
4,802
[ "SIESTA" ]
e0f9fc3bc889f92c2c0c9059beb756a27b65446304fdbcb97a89a4f0c339be71
#!/usr/bin/env python3 #!/usr/bin/python """Cheap and simple API helper This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark@diveintopython.org)" __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2001 Mark Pilgrim" __license__ = "Python" # While this is a good example script to teach about introspection, # in real life it has been superceded by PyDoc, which is part of the # standard library in Python 2.1 and later. # # Your IDE may already import the "help" function from pydoc # automatically on startup; if not, do this: # # >>> from pydoc import help # # The help function in this module takes the object itself to get # help on, but PyDoc can also take a string, like this: # # >>> help("string") # gets help on the string module # >>> help("apihelper.help") # gets help on the function below # >>> help() # enters an interactive help mode # # PyDoc can also act as an HTTP server to dynamically produce # HTML-formatted documentation of any module in your path. # That's wicked cool. Read more about PyDoc here: # http://www.onlamp.com/pub/a/python/2001/04/18/pydoc.html def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print(("\n".join(["\n%s\n\t%s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]))) if __name__ == "__main__": print((help.__doc__))
jtraver/dev
python3/help/apihelper.py
Python
mit
1,830
[ "VisIt" ]
e9389d94997352bf6b58498f4bf77050a6172ae652967f73dec94174ca568438
#!/usr/bin/python3 from __future__ import absolute_import from __future__ import print_function #ensure# encoding: utf-8 """ Module to set up run time parameters for Clawpack. The values set in the function setrun are then written out to data files that will be read in by the Fortran code. """ import os # to exract all the fine grid topography data from /bathy import glob import sys import datetime import shutil import gzip import numpy as np from clawpack.geoclaw.surge.storm import Storm import clawpack.clawutil as clawutil # Time Conversions def days2seconds(days): return days * 60.0**2 * 24.0 #------------------------------ def setrun(claw_pkg='geoclaw'): #------------------------------ """ Define the parameters used for running Clawpack. INPUT: claw_pkg expected to be "geoclaw" for this setrun. OUTPUT: rundata - object of class ClawRunData """ from clawpack.clawutil import data as clawdata assert claw_pkg.lower() == 'geoclaw', "Expected claw_pkg = 'geoclaw'" num_dim = 2 rundata = clawdata.ClawRunData(claw_pkg, num_dim) #------------------------------------------------------------------ # Problem-specific parameters to be written to setprob.data: #------------------------------------------------------------------ #probdata = rundata.new_UserData(name='probdata',fname='setprob.data') #------------------------------------------------------------------ # Standard Clawpack parameters to be written to claw.data: # (or to amr2ez.data for AMR) #------------------------------------------------------------------ clawdata = rundata.clawdata # initialized when rundata instantiated # Set single grid parameters first. # See below for AMR parameters. # --------------- # Spatial domain: # --------------- # Number of space dimensions: clawdata.num_dim = num_dim # Lower and upper edge of computational domain: # clawdata.lower[0] = -85.0 # west longitude # clawdata.upper[0] = -55.0 # east longitude # clawdata.lower[1] = 13.0 # south latitude # clawdata.upper[1] = 45.0 # north latitude clawdata.lower[0] = -88.0 # west longitude clawdata.upper[0] = -55.0 # east longitude clawdata.lower[1] = 15.0 # south latitude clawdata.upper[1] = 45.0 # north latitude # Number of grid cells: degree_factor = 4 clawdata.num_cells[0] = int(clawdata.upper[0] - clawdata.lower[0]) * degree_factor clawdata.num_cells[1] = int(clawdata.upper[1] - clawdata.lower[1]) * degree_factor # --------------- # Size of system: # --------------- # Number of equations in the system: clawdata.num_eqn = 3 # Number of auxiliary variables in the aux array (initialized in setaux) clawdata.num_aux = 3 + 1 + 3 # Index of aux array corresponding to capacity function, if there is one: clawdata.capa_index = 2 # ------------- # Initial time: # ------------- clawdata.t0 = days2seconds(-2.0) # Restart from checkpoint file of a previous run? # Note: If restarting, you must also change the Makefile to set: # RESTART = False # If restarting, t0 above should be from original run, and the # restart_file 'fort.chkNNNNN' specified below should be in # the OUTDIR indicated in Makefile. clawdata.restart = False # True to restart from prior results clawdata.restart_file = 'fort.chk00043' # File to use for restart data # ------------- # Output times: #-------------- # Specify at what times the results should be written to fort.q files. # Note that the time integration stops after the final output time. # The solution at initial time t0 is always written in addition. clawdata.output_style = 1 if clawdata.output_style==1: # Output nout frames at equally spaced times up to tfinal: # day s/hour hours/day clawdata.tfinal = days2seconds(1.0) # Output occurrence per day, 24 = every hour, 4 = every 6 hours recurrence = 24 clawdata.num_output_times = int((clawdata.tfinal - clawdata.t0) * recurrence / (60**2 * 24)) clawdata.output_t0 = True # output at initial (or restart) time? elif clawdata.output_style == 2: # Specify a list of output times. clawdata.output_times = [0.5, 1.0] elif clawdata.output_style == 3: # Output every iout timesteps with a total of ntot time steps: clawdata.output_step_interval = 1 clawdata.total_steps = 1 clawdata.output_t0 = True clawdata.output_format = 'ascii' # 'ascii' or 'netcdf' clawdata.output_q_components = 'all' # could be list such as [True,True] clawdata.output_aux_components = 'all' clawdata.output_aux_onlyonce = False # output aux arrays only at t0 # --------------------------------------------------- # Verbosity of messages to screen during integration: # --------------------------------------------------- # The current t, dt, and cfl will be printed every time step # at AMR levels <= verbosity. Set verbosity = 0 for no printing. # (E.g. verbosity == 2 means print only on levels 1 and 2.) clawdata.verbosity = 4 # -------------- # Time stepping: # -------------- # if dt_variable==1: variable time steps used based on cfl_desired, # if dt_variable==0: fixed time steps dt = dt_initial will always be used. clawdata.dt_variable = True # Initial time step for variable dt. # If dt_variable==0 then dt=dt_initial for all steps: clawdata.dt_initial = 0.016 # Max time step to be allowed if variable dt used: clawdata.dt_max = 1e+99 # Desired Courant number if variable dt used, and max to allow without # retaking step with a smaller dt: # clawdata.cfl_desired = 0.75 clawdata.cfl_desired = 0.75 clawdata.cfl_max = 1.0 # Maximum number of time steps to allow between output times: clawdata.steps_max = 2**16 # ------------------ # Method to be used: # ------------------ # Order of accuracy: 1 => Godunov, 2 => Lax-Wendroff plus limiters clawdata.order = 2 # Use dimensional splitting? (not yet available for AMR) clawdata.dimensional_split = 'unsplit' # For unsplit method, transverse_waves can be # 0 or 'none' ==> donor cell (only normal solver used) # 1 or 'increment' ==> corner transport of waves # 2 or 'all' ==> corner transport of 2nd order corrections too clawdata.transverse_waves = 2 # Number of waves in the Riemann solution: clawdata.num_waves = 3 # List of limiters to use for each wave family: # Required: len(limiter) == num_waves # Some options: # 0 or 'none' ==> no limiter (Lax-Wendroff) # 1 or 'minmod' ==> minmod # 2 or 'superbee' ==> superbee # 3 or 'mc' ==> MC limiter # 4 or 'vanleer' ==> van Leer clawdata.limiter = ['mc', 'mc', 'mc'] clawdata.use_fwaves = True # True ==> use f-wave version of algorithms # Source terms splitting: # src_split == 0 or 'none' ==> no source term (src routine never called) # src_split == 1 or 'godunov' ==> Godunov (1st order) splitting used, # src_split == 2 or 'strang' ==> Strang (2nd order) splitting used, not recommended. clawdata.source_split = 'godunov' # -------------------- # Boundary conditions: # -------------------- # Number of ghost cells (usually 2) clawdata.num_ghost = 2 # Choice of BCs at xlower and xupper: # 0 => user specified (must modify bcN.f to use this option) # 1 => extrapolation (non-reflecting outflow) # 2 => periodic (must specify this at both boundaries) # 3 => solid wall for systems where q(2) is normal velocity clawdata.bc_lower[0] = 'extrap' clawdata.bc_upper[0] = 'extrap' clawdata.bc_lower[1] = 'extrap' clawdata.bc_upper[1] = 'extrap' # Specify when checkpoint files should be created that can be # used to restart a computation. clawdata.checkpt_style = 0 if clawdata.checkpt_style == 0: # Do not checkpoint at all pass elif clawdata.checkpt_style == 1: # Checkpoint only at tfinal. pass elif clawdata.checkpt_style == 2: # Specify a list of checkpoint times. clawdata.checkpt_times = [0.1,0.15] elif clawdata.checkpt_style == 3: # Checkpoint every checkpt_interval timesteps (on Level 1) # and at the final time. clawdata.checkpt_interval = 5 # --------------- # AMR parameters: # --------------- amrdata = rundata.amrdata # max number of refinement levels: amrdata.amr_levels_max = 7 # List of refinement ratios at each level (length at least mxnest-1) # amrdata.refinement_ratios_x = [2, 2, 2, 6, 16] # amrdata.refinement_ratios_y = [2, 2, 2, 6, 16] # amrdata.refinement_ratios_t = [2, 2, 2, 6, 16] <- ~ 9 meters amrdata.refinement_ratios_x = [2, 2, 2, 6, 8, 8] amrdata.refinement_ratios_y = [2, 2, 2, 6, 8, 8] amrdata.refinement_ratios_t = [2, 2, 2, 6, 8, 8] # Specify type of each aux variable in amrdata.auxtype. # This must be a list of length maux, each element of which is one of: # 'center', 'capacity', 'xleft', or 'yleft' (see documentation). amrdata.aux_type = ['center','capacity','yleft','center','center','center', 'center', 'center', 'center'] # Flag using refinement routine flag2refine rather than richardson error amrdata.flag_richardson = False # use Richardson? amrdata.flag2refine = True # steps to take on each level L between regriddings of level L+1: amrdata.regrid_interval = 4 # width of buffer zone around flagged points: # (typically the same as regrid_interval so waves don't escape): amrdata.regrid_buffer_width = 2 # clustering alg. cutoff for (# flagged pts) / (total # of cells refined) # (closer to 1.0 => more small grids may be needed to cover flagged cells) amrdata.clustering_cutoff = 0.700000 # print info about each regridding up to this level: amrdata.verbosity_regrid = 0 # ----- For developers ----- # Toggle debugging print statements: amrdata.dprint = False # print domain flags amrdata.eprint = False # print err est flags amrdata.edebug = False # even more err est flags amrdata.gprint = False # grid bisection/clustering amrdata.nprint = False # proper nesting output amrdata.pprint = False # proj. of tagged points amrdata.rprint = False # print regridding summary amrdata.sprint = False # space/memory output amrdata.tprint = False # time step reporting each level amrdata.uprint = False # update/upbnd reporting # More AMR parameters can be set -- see the defaults in pyclaw/data.py # == setregions.data values == regions = rundata.regiondata.regions # to specify regions of refinement append lines of the form # [minlevel,maxlevel,t1,t2,x1,x2,y1,y2] # regions.append([1,6,days2seconds(-0.45),days2seconds(0.10),-74.1,-73.7,40.55,48.5]) # regions.append([1,5,days2seconds(0.10),days2seconds(1),-74.2,-73.7,40.55,48.5]) # == setgauges.data values == # for gauges append lines of the form [gaugeno, x, y, t1, t2] # battery gauge rundata.gaugedata.gauges.append([1,-74.013,40.7,clawdata.t0,clawdata.tfinal]) # Kings point gauge rundata.gaugedata.gauges.append([2,-73.77,40.81,clawdata.t0,clawdata.tfinal]) # Sandy Hook gauge # rundata.gaugedata.gauges.append([3,-74.01,40.47,clawdata.t0,clawdata.tfinal]) # Bergen Point West Reach rundata.gaugedata.gauges.append([3,-74.14166,40.6367,clawdata.t0,clawdata.tfinal]) # Narrows # rundata.gaugedata.gauges.append([4,-74.038,40.605,clawdata.t0,clawdata.tfinal]) #------------------------------------------------------------------ # GeoClaw specific parameters: #------------------------------------------------------------------ rundata = setgeo(rundata) return rundata # end of function setrun # ---------------------- #------------------- def setgeo(rundata): #------------------- """ Set GeoClaw specific runtime parameters. For documentation see .... """ try: geo_data = rundata.geo_data except: print("*** Error, this rundata has no geodata attribute") raise AttributeError("Missing geodata attribute") # == Physics == geo_data.gravity = 9.81 geo_data.coordinate_system = 2 geo_data.earth_radius = 6367.5e3 geo_data.rho = 1025.0 geo_data.rho_air = 1.15 geo_data.ambient_pressure = 101.3e3 # == Forcing Options geo_data.coriolis_forcing = True geo_data.friction_forcing = True geo_data.friction_depth = 1e10 # == Algorithm and Initial Conditions == geo_data.sea_level = 0.0 geo_data.dry_tolerance = 1.e-2 # Refinement Criteria refine_data = rundata.refinement_data refine_data.wave_tolerance = 1.0 refine_data.speed_tolerance = [1.0, 2.0, 3.0, 4.0] refine_data.deep_depth = 300.0 refine_data.max_level_deep = 4 refine_data.variable_dt_refinement_ratios = True # == settopo.data values == topo_data = rundata.topo_data topo_data.topofiles = [] # for topography, append lines of the form # [topotype, minlevel, maxlevel, t1, t2, fname] topo_path = os.path.join('..', 'bathy') topo_data.topofiles.append([3, 1, 3, days2seconds(-2), days2seconds(1), os.path.join(topo_path,'atlantic_1min.tt3')]) topo_data.topofiles.append([3, 1, 7, days2seconds(-2), days2seconds(1), os.path.join(topo_path,'newyork_3s.tt3')]) # 90 meter accuracy # == setqinit.data values == rundata.qinit_data.qinit_type = 0 rundata.qinit_data.qinitfiles = [] # for qinit perturbations, append lines of the form: (<= 1 allowed for now!) # [minlev, maxlev, fname] # == setfixedgrids.data values == rundata.fixed_grid_data.fixedgrids = [] # for fixed grids append lines of the form # [t1,t2,noutput,x1,x2,y1,y2,xpoints,ypoints,\ # ioutarrivaltimes,ioutsurfacemax] # ================ # Set Surge Data # ================ data = rundata.surge_data # Source term controls data.wind_forcing = True data.drag_law = 1 data.pressure_forcing = True data.display_landfall_time = True # AMR parameters data.wind_refine = [20.0,40.0,60.0] # m/s data.R_refine = [60.0e3,40e3,20e3] # m # Storm parameters data.storm_specification_type = "holland80" # Set type of storm field data.storm_file = os.path.expandvars(os.path.join(os.getcwd(), 'sandy.storm')) # Convert ATCF data to GeoClaw format clawutil.data.get_remote_file( "http://ftp.nhc.noaa.gov/atcf/archive/2012/bal182012.dat.gz", output_dir=os.getcwd()) atcf_path = os.path.join(os.getcwd(), "bal182012.dat") # Note that the get_remote_file function does not support gzip files which # are not also tar files. The following code handles this with gzip.open(".".join((atcf_path, 'gz')), 'rb') as atcf_file: with open(atcf_path, 'w') as atcf_unzipped_file: atcf_unzipped_file.write(atcf_file.read().decode('ascii')) sandy = Storm(path=atcf_path, file_format="ATCF") # Calculate landfall time - Need to specify as the file above does not # include this info (9/13/2008 ~ 7 UTC) sandy.time_offset = datetime.datetime(2012,10,30,0,0) sandy.write(data.storm_file, file_format='geoclaw') # ======================= # Set Variable Friction # ======================= data = rundata.friction_data # Variable friction data.variable_friction = True # Region based friction # Entire domain - seems high on land... data.friction_regions.append([rundata.clawdata.lower, rundata.clawdata.upper, [np.infty,0.0,-np.infty], [0.050, 0.025]]) return rundata # end of function setgeo # ---------------------- if __name__ == '__main__': # Set up run-time parameters and write all data files. import sys if len(sys.argv) == 2: rundata = setrun(sys.argv[1]) else: rundata = setrun() rundata.write()
mandli/surge-examples
sandy/setrun.py
Python
mit
16,806
[ "NetCDF" ]
90603f75f838a3026ab1088c9a4b892dc0a717398617c2b2ee343fd90cd64eb5
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Brewing Classic Styles: 80 Winning Recipes Anyone Can Brew by Jamil Zainasheff and John J. Palmer Munich Madness Used by permission of Brewers Publications (2007). All rights reserved. You can purchase the book here: - http://www.brewerspublications.com/books/brewing-classic-styles-80-winning-recipes-anyone-can-brew/ Original Stats: OG: 1.055 (13.6P) FG: 1.015 ( 3.7P) ADF: 73% IBU: 27 Color: 11 SRM (21 EBC) Alcohol: 5.4% ABV (4.2% ABW) Boil: 60 min Pre-Boil Volume: 7 Gal (26.5L) Pre-Boil Gravity: 1.047 (11.7P) """ # noqa import os from brew.parsers import JSONDataLoader from brew.parsers import parse_recipe def main(): recipe = { u"name": u"Munich Madness (All Grain)", u"start_volume": 7.0, u"final_volume": 6.0, u"grains": [ {u"name": u"Pilsner 2 row Ger", u"data": {u"color": 2.3}, u"weight": 5.0}, {u"name": u"Munich Malt 10L", u"data": {u"color": 9.0}, u"weight": 4.0}, {u"name": u"Vienna Malt", u"weight": 3.0}, { u"name": u"Caramunich Malt", u"data": {u"color": 60.0}, u"weight": 1.0, u"grain_type": u"specialty", }, ], u"hops": [ { u"name": u"Hallertau US", u"data": {u"percent_alpha_acids": 0.04}, u"weight": 1.5, u"boil_time": 60.0, }, { u"name": u"Hallertau US", u"data": {u"percent_alpha_acids": 0.04}, u"weight": 0.5, u"boil_time": 20.0, }, ], u"yeast": {u"name": u"Wyeast 2206", u"data": {u"percent_attenuation": 0.73}}, u"data": {u"brew_house_yield": 0.70, u"units": u"imperial"}, } data_dir = os.path.abspath(os.path.join(os.getcwd(), "data/")) loader = JSONDataLoader(data_dir) beer = parse_recipe(recipe, loader) print(beer.format()) if __name__ == "__main__": main()
chrisgilmerproj/brewday
examples/brewing_classic_styles/munich_madness_dict.py
Python
mit
2,085
[ "ADF" ]
cae4c1e3503c5201f4225922beda80f6b13905a0c0c9fb5e12484e3022e151e6
from __future__ import generators class TreeWalker(object): VERBOSE = 0 def __init__(self): self.node = None self._cache = {} def default(self, node, *args): for child in node.getChildNodes(): self.dispatch(child, *args) def dispatch(self, node, *args): self.node = node klass = node.__class__ meth = self._cache.get(klass, None) if meth is None: className = klass.__name__ meth = getattr(self.visitor, 'visit' + className, self.default) self._cache[klass] = meth return meth(node, *args) def preorder(self, tree, visitor, *args): """Do preorder walk of tree using visitor""" self.visitor = visitor visitor.visit = self.dispatch visitor.visitChildren = self.default return self.dispatch(tree, *args) class GeneratingTreeWalker(TreeWalker): def default(self, node, *args): for child in node.getChildNodes(): for i in self.dispatch(child, *args): yield i def walk(tree, visitor): walker = TreeWalker() walker.preorder(tree, visitor) return walker.visitor def walkAndGenerate(tree,visitor): walker = GeneratingTreeWalker() return walker.preorder(tree, visitor)
srusskih/SublimeBicycleRepair
bike/parsing/visitor.py
Python
mit
1,307
[ "VisIt" ]
1c4812da5c45cc88c8f4051aa6954241281252cfc4033a811b90e0d18127fe60
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import json import os import unittest import warnings import numpy as np from monty.os.path import which from monty.serialization import loadfn from pymatgen.core.lattice import Lattice from pymatgen.core.periodic_table import Species from pymatgen.core.structure import Molecule, Structure from pymatgen.analysis.energy_models import IsingModel from pymatgen.analysis.gb.grain import GrainBoundaryGenerator from pymatgen.core.surface import SlabGenerator from pymatgen.io import atat from pymatgen.io.cif import CifParser from pymatgen.io.vasp.inputs import Poscar from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.transformations.advanced_transformations import ( AddAdsorbateTransformation, ChargeBalanceTransformation, CubicSupercellTransformation, DisorderOrderedTransformation, DopingTransformation, EnumerateStructureTransformation, GrainBoundaryTransformation, MagOrderingTransformation, MagOrderParameterConstraint, MonteCarloRattleTransformation, MultipleSubstitutionTransformation, SlabTransformation, SQSTransformation, SubstituteSurfaceSiteTransformation, SubstitutionPredictorTransformation, SuperTransformation, _find_codopant, ) from pymatgen.transformations.standard_transformations import ( AutoOxiStateDecorationTransformation, OrderDisorderedStructureTransformation, OxidationStateDecorationTransformation, SubstitutionTransformation, ) from pymatgen.util.testing import PymatgenTest try: import hiphive # type: ignore except ImportError: hiphive = None def get_table(): """ Loads a lightweight lambda table for use in unit tests to reduce initialization time, and make unit tests insensitive to changes in the default lambda table. """ data_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "test_files", "struct_predictor") json_file = os.path.join(data_dir, "test_lambda.json") with open(json_file) as f: lambda_table = json.load(f) return lambda_table enum_cmd = which("enum.x") or which("multienum.x") makestr_cmd = which("makestr.x") or which("makeStr.x") or which("makeStr.py") mcsqs_cmd = which("mcsqs") enumlib_present = enum_cmd and makestr_cmd class SuperTransformationTest(unittest.TestCase): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_apply_transformation(self): tl = [ SubstitutionTransformation({"Li+": "Na+"}), SubstitutionTransformation({"Li+": "K+"}), ] t = SuperTransformation(tl) coords = list() coords.append([0, 0, 0]) coords.append([0.375, 0.375, 0.375]) coords.append([0.5, 0.5, 0.5]) coords.append([0.875, 0.875, 0.875]) coords.append([0.125, 0.125, 0.125]) coords.append([0.25, 0.25, 0.25]) coords.append([0.625, 0.625, 0.625]) coords.append([0.75, 0.75, 0.75]) lattice = Lattice( [ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ] ) struct = Structure(lattice, ["Li+", "Li+", "Li+", "Li+", "Li+", "Li+", "O2-", "O2-"], coords) s = t.apply_transformation(struct, return_ranked_list=True) for s_and_t in s: self.assertEqual( s_and_t["transformation"].apply_transformation(struct), s_and_t["structure"], ) @unittest.skipIf(not enumlib_present, "enum_lib not present.") def test_apply_transformation_mult(self): # Test returning multiple structures from each transformation. disord = Structure( np.eye(3) * 4.209, [{"Cs+": 0.5, "K+": 0.5}, "Cl-"], [[0, 0, 0], [0.5, 0.5, 0.5]], ) disord.make_supercell([2, 2, 1]) tl = [ EnumerateStructureTransformation(), OrderDisorderedStructureTransformation(), ] t = SuperTransformation(tl, nstructures_per_trans=10) self.assertEqual(len(t.apply_transformation(disord, return_ranked_list=20)), 8) t = SuperTransformation(tl) self.assertEqual(len(t.apply_transformation(disord, return_ranked_list=20)), 2) class MultipleSubstitutionTransformationTest(unittest.TestCase): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_apply_transformation(self): sub_dict = {1: ["Na", "K"]} t = MultipleSubstitutionTransformation("Li+", 0.5, sub_dict, None) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) coords.append([0.25, 0.25, 0.25]) lattice = Lattice( [ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ] ) struct = Structure(lattice, ["Li+", "Li+", "O2-", "O2-"], coords) self.assertEqual(len(t.apply_transformation(struct, return_ranked_list=True)), 2) class ChargeBalanceTransformationTest(unittest.TestCase): def test_apply_transformation(self): t = ChargeBalanceTransformation("Li+") coords = list() coords.append([0, 0, 0]) coords.append([0.375, 0.375, 0.375]) coords.append([0.5, 0.5, 0.5]) coords.append([0.875, 0.875, 0.875]) coords.append([0.125, 0.125, 0.125]) coords.append([0.25, 0.25, 0.25]) coords.append([0.625, 0.625, 0.625]) coords.append([0.75, 0.75, 0.75]) lattice = Lattice( [ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ] ) struct = Structure(lattice, ["Li+", "Li+", "Li+", "Li+", "Li+", "Li+", "O2-", "O2-"], coords) s = t.apply_transformation(struct) self.assertAlmostEqual(s.charge, 0, 5) @unittest.skipIf(not enumlib_present, "enum_lib not present.") class EnumerateStructureTransformationTest(unittest.TestCase): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_apply_transformation(self): enum_trans = EnumerateStructureTransformation(refine_structure=True) enum_trans2 = EnumerateStructureTransformation(refine_structure=True, sort_criteria="nsites") p = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR.LiFePO4"), check_for_POTCAR=False) struct = p.structure expected_ans = [1, 3, 1] for i, frac in enumerate([0.25, 0.5, 0.75]): trans = SubstitutionTransformation({"Fe": {"Fe": frac}}) s = trans.apply_transformation(struct) oxitrans = OxidationStateDecorationTransformation({"Li": 1, "Fe": 2, "P": 5, "O": -2}) s = oxitrans.apply_transformation(s) alls = enum_trans.apply_transformation(s, 100) self.assertEqual(len(alls), expected_ans[i]) self.assertIsInstance(trans.apply_transformation(s), Structure) for ss in alls: self.assertIn("energy", ss) alls = enum_trans2.apply_transformation(s, 100) self.assertEqual(len(alls), expected_ans[i]) self.assertIsInstance(trans.apply_transformation(s), Structure) for ss in alls: self.assertIn("num_sites", ss) # make sure it works for non-oxidation state decorated structure trans = SubstitutionTransformation({"Fe": {"Fe": 0.5}}) s = trans.apply_transformation(struct) alls = enum_trans.apply_transformation(s, 100) self.assertEqual(len(alls), 3) self.assertIsInstance(trans.apply_transformation(s), Structure) for s in alls: self.assertNotIn("energy", s) def test_max_disordered_sites(self): l = Lattice.cubic(4) s_orig = Structure( l, [{"Li": 0.2, "Na": 0.2, "K": 0.6}, {"O": 1}], [[0, 0, 0], [0.5, 0.5, 0.5]], ) est = EnumerateStructureTransformation(max_cell_size=None, max_disordered_sites=5) dd = est.apply_transformation(s_orig, return_ranked_list=100) self.assertEqual(len(dd), 9) for d in dd: self.assertEqual(len(d["structure"]), 10) def test_to_from_dict(self): trans = EnumerateStructureTransformation() d = trans.as_dict() trans = EnumerateStructureTransformation.from_dict(d) self.assertEqual(trans.symm_prec, 0.1) class SubstitutionPredictorTransformationTest(unittest.TestCase): def test_apply_transformation(self): t = SubstitutionPredictorTransformation(threshold=1e-3, alpha=-5, lambda_table=get_table()) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.75, 0.75]) coords.append([0.5, 0.5, 0.5]) lattice = Lattice( [ [3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603], ] ) struct = Structure(lattice, ["O2-", "Li1+", "Li1+"], coords) outputs = t.apply_transformation(struct, return_ranked_list=True) self.assertEqual(len(outputs), 4, "incorrect number of structures") def test_as_dict(self): t = SubstitutionPredictorTransformation(threshold=2, alpha=-2, lambda_table=get_table()) d = t.as_dict() t = SubstitutionPredictorTransformation.from_dict(d) self.assertEqual(t.threshold, 2, "incorrect threshold passed through dict") self.assertEqual(t._substitutor.p.alpha, -2, "incorrect alpha passed through dict") @unittest.skipIf(not enumlib_present, "enum_lib not present.") class MagOrderingTransformationTest(PymatgenTest): def setUp(self): latt = Lattice.cubic(4.17) species = ["Ni", "O"] coords = [[0, 0, 0], [0.5, 0.5, 0.5]] self.NiO = Structure.from_spacegroup(225, latt, species, coords) latt = Lattice([[2.085, 2.085, 0.0], [0.0, -2.085, -2.085], [-2.085, 2.085, -4.17]]) species = ["Ni", "Ni", "O", "O"] coords = [[0.5, 0, 0.5], [0, 0, 0], [0.25, 0.5, 0.25], [0.75, 0.5, 0.75]] self.NiO_AFM_111 = Structure(latt, species, coords) self.NiO_AFM_111.add_spin_by_site([-5, 5, 0, 0]) latt = Lattice([[2.085, 2.085, 0], [0, 0, -4.17], [-2.085, 2.085, 0]]) species = ["Ni", "Ni", "O", "O"] coords = [[0.5, 0.5, 0.5], [0, 0, 0], [0, 0.5, 0], [0.5, 0, 0.5]] self.NiO_AFM_001 = Structure(latt, species, coords) self.NiO_AFM_001.add_spin_by_site([-5, 5, 0, 0]) parser = CifParser(os.path.join(PymatgenTest.TEST_FILES_DIR, "Fe3O4.cif")) self.Fe3O4 = parser.get_structures()[0] trans = AutoOxiStateDecorationTransformation() self.Fe3O4_oxi = trans.apply_transformation(self.Fe3O4) parser = CifParser(os.path.join(PymatgenTest.TEST_FILES_DIR, "Li8Fe2NiCoO8.cif")) self.Li8Fe2NiCoO8 = parser.get_structures()[0] self.Li8Fe2NiCoO8.remove_oxidation_states() warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_apply_transformation(self): trans = MagOrderingTransformation({"Fe": 5}) p = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR.LiFePO4"), check_for_POTCAR=False) s = p.structure alls = trans.apply_transformation(s, 10) self.assertEqual(len(alls), 3) f = SpacegroupAnalyzer(alls[0]["structure"], 0.1) self.assertEqual(f.get_space_group_number(), 31) model = IsingModel(5, 5) trans = MagOrderingTransformation({"Fe": 5}, energy_model=model) alls2 = trans.apply_transformation(s, 10) # Ising model with +J penalizes similar neighbor magmom. self.assertNotEqual(alls[0]["structure"], alls2[0]["structure"]) self.assertEqual(alls[0]["structure"], alls2[2]["structure"]) s = self.get_structure("Li2O") # Li2O doesn't have magnetism of course, but this is to test the # enumeration. trans = MagOrderingTransformation({"Li+": 1}, max_cell_size=3) alls = trans.apply_transformation(s, 100) # TODO: check this is correct, unclear what len(alls) should be self.assertEqual(len(alls), 12) trans = MagOrderingTransformation({"Ni": 5}) alls = trans.apply_transformation(self.NiO.get_primitive_structure(), return_ranked_list=10) self.assertArrayAlmostEqual(self.NiO_AFM_111.lattice.parameters, alls[0]["structure"].lattice.parameters) self.assertArrayAlmostEqual(self.NiO_AFM_001.lattice.parameters, alls[1]["structure"].lattice.parameters) def test_ferrimagnetic(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75, max_cell_size=1) p = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR.LiFePO4"), check_for_POTCAR=False) s = p.structure a = SpacegroupAnalyzer(s, 0.1) s = a.get_refined_structure() alls = trans.apply_transformation(s, 10) self.assertEqual(len(alls), 1) def test_as_from_dict(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75) d = trans.as_dict() # Check json encodability s = json.dumps(d) trans = MagOrderingTransformation.from_dict(d) self.assertEqual(trans.mag_species_spin, {"Fe": 5}) from pymatgen.analysis.energy_models import SymmetryModel self.assertIsInstance(trans.energy_model, SymmetryModel) def test_zero_spin_case(self): # ensure that zero spin case maintains sites and formula s = self.get_structure("Li2O") trans = MagOrderingTransformation({"Li+": 0.0}, order_parameter=0.5) alls = trans.apply_transformation(s) Li_site = alls.indices_from_symbol("Li")[0] # Ensure s does not have a spin property self.assertFalse("spin" in s.sites[Li_site].specie._properties) # ensure sites are assigned a spin property in alls self.assertTrue("spin" in alls.sites[Li_site].specie._properties) self.assertEqual(alls.sites[Li_site].specie._properties["spin"], 0) def test_advanced_usage(self): # test spin on just one oxidation state magtypes = {"Fe2+": 5} trans = MagOrderingTransformation(magtypes) alls = trans.apply_transformation(self.Fe3O4_oxi) self.assertIsInstance(alls, Structure) self.assertEqual(str(alls[0].specie), "Fe2+,spin=5") self.assertEqual(str(alls[2].specie), "Fe3+") # test multiple order parameters # this should only order on Fe3+ site, but assign spin to both magtypes = {"Fe2+": 5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(1, species_constraints="Fe2+"), MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi) # using this 'sorted' syntax because exact order of sites in first # returned structure varies between machines: we just want to ensure # that the order parameter is accurate self.assertEqual( sorted([str(alls[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=5", "Fe2+,spin=5"]), ) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5"]), ) self.assertEqual(str(alls[0].specie), "Fe2+,spin=5") # this should give same results as previously # but with opposite sign on Fe2+ site magtypes = {"Fe2+": -5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(1, species_constraints="Fe2+"), MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=-5", "Fe2+,spin=-5"]), ) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5"]), ) # while this should order on both sites magtypes = {"Fe2+": 5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(0.5, species_constraints="Fe2+"), MagOrderParameterConstraint(0.25, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]), ) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=-5"]), ) # add coordination numbers to our test case # don't really care what these are for the test case cns = [6, 6, 6, 6, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0] self.Fe3O4.add_site_property("cn", cns) # this should give FM ordering on cn=4 sites, and AFM ordering on cn=6 sites magtypes = {"Fe": 5} order_parameters = [ MagOrderParameterConstraint( 0.5, species_constraints="Fe", site_constraint_name="cn", site_constraints=6, ), MagOrderParameterConstraint( 1.0, species_constraints="Fe", site_constraint_name="cn", site_constraints=4, ), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4) alls.sort(key=lambda x: x.properties["cn"], reverse=True) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(0, 4)]), sorted(["Fe,spin=-5", "Fe,spin=-5", "Fe,spin=5", "Fe,spin=5"]), ) self.assertEqual( sorted([str(alls[idx].specie) for idx in range(4, 6)]), sorted(["Fe,spin=5", "Fe,spin=5"]), ) # now ordering on both sites, equivalent to order_parameter = 0.5 magtypes = {"Fe2+": 5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(0.5, species_constraints="Fe2+"), MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) struct = alls[0]["structure"] self.assertEqual( sorted([str(struct[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]), ) self.assertEqual( sorted([str(struct[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=5"]), ) self.assertEqual(len(alls), 4) # now mixed orderings where neither are equal or 1 magtypes = {"Fe2+": 5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(0.5, species_constraints="Fe2+"), MagOrderParameterConstraint(0.25, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=100) struct = alls[0]["structure"] self.assertEqual( sorted([str(struct[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]), ) self.assertEqual( sorted([str(struct[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=-5"]), ) self.assertEqual(len(alls), 2) # now order on multiple species magtypes = {"Fe2+": 5, "Fe3+": 5} order_parameters = [ MagOrderParameterConstraint(0.5, species_constraints=["Fe2+", "Fe3+"]), ] trans = MagOrderingTransformation(magtypes, order_parameter=order_parameters) alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) struct = alls[0]["structure"] self.assertEqual( sorted([str(struct[idx].specie) for idx in range(0, 2)]), sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]), ) self.assertEqual( sorted([str(struct[idx].specie) for idx in range(2, 6)]), sorted(["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=5"]), ) self.assertEqual(len(alls), 6) @unittest.skipIf(not enumlib_present, "enum_lib not present.") class DopingTransformationTest(PymatgenTest): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_apply_transformation(self): structure = PymatgenTest.get_structure("LiFePO4") a = SpacegroupAnalyzer(structure, 0.1) structure = a.get_refined_structure() t = DopingTransformation("Ca2+", min_length=10) ss = t.apply_transformation(structure, 100) self.assertEqual(len(ss), 1) t = DopingTransformation("Al3+", min_length=15, ionic_radius_tol=0.1) ss = t.apply_transformation(structure, 100) self.assertEqual(len(ss), 0) # Aliovalent doping with vacancies for dopant, nstructures in [("Al3+", 2), ("N3-", 235), ("Cl-", 8)]: t = DopingTransformation(dopant, min_length=4, alio_tol=1, max_structures_per_enum=1000) ss = t.apply_transformation(structure, 1000) self.assertEqual(len(ss), nstructures) for d in ss: self.assertEqual(d["structure"].charge, 0) # Aliovalent doping with codopant for dopant, nstructures in [("Al3+", 3), ("N3-", 37), ("Cl-", 37)]: t = DopingTransformation( dopant, min_length=4, alio_tol=1, codopant=True, max_structures_per_enum=1000, ) ss = t.apply_transformation(structure, 1000) self.assertEqual(len(ss), nstructures) for d in ss: self.assertEqual(d["structure"].charge, 0) # Make sure compensation is done with lowest oxi state structure = PymatgenTest.get_structure("SrTiO3") t = DopingTransformation( "Nb5+", min_length=5, alio_tol=1, max_structures_per_enum=1000, allowed_doping_species=["Ti4+"], ) ss = t.apply_transformation(structure, 1000) self.assertEqual(len(ss), 3) for d in ss: self.assertEqual(d["structure"].formula, "Sr7 Ti6 Nb2 O24") def test_as_from_dict(self): trans = DopingTransformation("Al3+", min_length=5, alio_tol=1, codopant=False, max_structures_per_enum=1) d = trans.as_dict() # Check json encodability s = json.dumps(d) trans = DopingTransformation.from_dict(d) self.assertEqual(str(trans.dopant), "Al3+") self.assertEqual(trans.max_structures_per_enum, 1) def test_find_codopant(self): self.assertEqual(_find_codopant(Species("Fe", 2), 1), Species("Cu", 1)) self.assertEqual(_find_codopant(Species("Fe", 2), 3), Species("In", 3)) class SlabTransformationTest(PymatgenTest): def test_apply_transformation(self): s = self.get_structure("LiFePO4") trans = SlabTransformation([0, 0, 1], 10, 10, shift=0.25) gen = SlabGenerator(s, [0, 0, 1], 10, 10) slab_from_gen = gen.get_slab(0.25) slab_from_trans = trans.apply_transformation(s) self.assertArrayAlmostEqual(slab_from_gen.lattice.matrix, slab_from_trans.lattice.matrix) self.assertArrayAlmostEqual(slab_from_gen.cart_coords, slab_from_trans.cart_coords) fcc = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]]) trans = SlabTransformation([1, 1, 1], 10, 10) slab_from_trans = trans.apply_transformation(fcc) gen = SlabGenerator(fcc, [1, 1, 1], 10, 10) slab_from_gen = gen.get_slab() self.assertArrayAlmostEqual(slab_from_gen.lattice.matrix, slab_from_trans.lattice.matrix) self.assertArrayAlmostEqual(slab_from_gen.cart_coords, slab_from_trans.cart_coords) class GrainBoundaryTransformationTest(PymatgenTest): def test_apply_transformation(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") Al_bulk = Structure.from_spacegroup("Fm-3m", Lattice.cubic(2.8575585), ["Al"], [[0, 0, 0]]) gb_gen_params_s5 = { "rotation_axis": [1, 0, 0], "rotation_angle": 53.13010235415599, "expand_times": 3, "vacuum_thickness": 0.0, "normal": True, "plane": [0, -1, -3], "rm_ratio": 0.6, } gbg = GrainBoundaryGenerator(Al_bulk) gb_from_generator = gbg.gb_from_parameters(**gb_gen_params_s5) gbt_s5 = GrainBoundaryTransformation(**gb_gen_params_s5) gb_from_trans = gbt_s5.apply_transformation(Al_bulk) self.assertArrayAlmostEqual(gb_from_generator.lattice.matrix, gb_from_trans.lattice.matrix) self.assertArrayAlmostEqual(gb_from_generator.cart_coords, gb_from_trans.cart_coords) class DisorderedOrderedTransformationTest(PymatgenTest): def test_apply_transformation(self): # non-sensical example just for testing purposes struct = self.get_structure("BaNiO3") trans = DisorderOrderedTransformation() output = trans.apply_transformation(struct) self.assertFalse(output.is_ordered) self.assertDictEqual(output[-1].species.as_dict(), {"Ni": 0.5, "Ba": 0.5}) @unittest.skipIf(not mcsqs_cmd, "mcsqs not present.") class SQSTransformationTest(PymatgenTest): def test_apply_transformation(self): pztstructs = loadfn(os.path.join(PymatgenTest.TEST_FILES_DIR, "mcsqs/pztstructs.json")) trans = SQSTransformation(scaling=[2, 1, 1], search_time=0.01, instances=1, wd=0) # nonsensical example just for testing purposes struc = self.get_structure("Pb2TiZrO6").copy() struc.replace_species({"Ti": {"Ti": 0.5, "Zr": 0.5}, "Zr": {"Ti": 0.5, "Zr": 0.5}}) struc_out = trans.apply_transformation(struc) matches = [struc_out.matches(s) for s in pztstructs] self.assertIn(True, matches) def test_return_ranked_list(self): # list of structures pztstructs2 = loadfn(os.path.join(PymatgenTest.TEST_FILES_DIR, "mcsqs/pztstructs2.json")) trans = SQSTransformation(scaling=2, search_time=0.01, instances=8, wd=0) struc = self.get_structure("Pb2TiZrO6").copy() struc.replace_species({"Ti": {"Ti": 0.5, "Zr": 0.5}, "Zr": {"Ti": 0.5, "Zr": 0.5}}) ranked_list_out = trans.apply_transformation(struc, return_ranked_list=True) matches = [ranked_list_out[0]["structure"].matches(s) for s in pztstructs2] self.assertIn(True, matches) def test_spin(self): trans = SQSTransformation(scaling=[2, 1, 1], search_time=0.01, instances=1, wd=0) # nonsensical example just for testing purposes struc = self.get_structure("Pb2TiZrO6").copy() struc.replace_species({"Ti": {"Ti,spin=5": 0.5, "Ti,spin=-5": 0.5}}) struc_out = trans.apply_transformation(struc) struc_out_specie_strings = [site.species_string for site in struc_out] self.assertIn("Ti,spin=-5", struc_out_specie_strings) self.assertIn("Ti,spin=5", struc_out_specie_strings) class CubicSupercellTransformationTest(PymatgenTest): def test_apply_transformation(self): structure = self.get_structure("TlBiSe2") min_atoms = 100 max_atoms = 1000 # Test the transformation without constraining trans_mat to be diagonal supercell_generator = CubicSupercellTransformation(min_atoms=min_atoms, max_atoms=max_atoms, min_length=13.0) superstructure = supercell_generator.apply_transformation(structure) num_atoms = superstructure.num_sites self.assertTrue(num_atoms >= min_atoms) self.assertTrue(num_atoms <= max_atoms) self.assertArrayAlmostEqual( superstructure.lattice.matrix[0], [1.49656087e01, -1.11448000e-03, 9.04924836e00], ) self.assertArrayAlmostEqual(superstructure.lattice.matrix[1], [-0.95005506, 14.95766342, 10.01819773]) self.assertArrayAlmostEqual( superstructure.lattice.matrix[2], [3.69130000e-02, 4.09320200e-02, 5.90830153e01], ) self.assertEqual(superstructure.num_sites, 448) self.assertArrayEqual( supercell_generator.transformation_matrix, np.array([[4, 0, 0], [1, 4, -4], [0, 0, 1]]), ) # Test the diagonal transformation structure2 = self.get_structure("Si") sga = SpacegroupAnalyzer(structure2) structure2 = sga.get_primitive_standard_structure() diagonal_supercell_generator = CubicSupercellTransformation( min_atoms=min_atoms, max_atoms=max_atoms, min_length=13.0, force_diagonal=True, ) _ = diagonal_supercell_generator.apply_transformation(structure2) self.assertArrayEqual(diagonal_supercell_generator.transformation_matrix, np.eye(3) * 4) class AddAdsorbateTransformationTest(PymatgenTest): def test_apply_transformation(self): co = Molecule(["C", "O"], [[0, 0, 0], [0, 0, 1.23]]) trans = AddAdsorbateTransformation(co) pt = Structure(Lattice.cubic(5), ["Pt"], [[0, 0, 0]]) # fictitious slab = SlabTransformation([0, 0, 1], 20, 10).apply_transformation(pt) out = trans.apply_transformation(slab) self.assertEqual(out.composition.reduced_formula, "Pt4CO") class SubstituteSurfaceSiteTransformationTest(PymatgenTest): def test_apply_transformation(self): trans = SubstituteSurfaceSiteTransformation("Au") pt = Structure(Lattice.cubic(5), ["Pt"], [[0, 0, 0]]) # fictitious slab = SlabTransformation([0, 0, 1], 20, 10).apply_transformation(pt) out = trans.apply_transformation(slab) self.assertEqual(out.composition.reduced_formula, "Pt3Au") @unittest.skipIf(not hiphive, "hiphive not present. Skipping...") class MonteCarloRattleTransformationTest(PymatgenTest): def test_apply_transformation(self): s = self.get_structure("Si") mcrt = MonteCarloRattleTransformation(0.01, 2, seed=1) s_trans = mcrt.apply_transformation(s) self.assertFalse(np.allclose(s.cart_coords, s_trans.cart_coords, atol=0.01)) self.assertTrue(np.allclose(s.cart_coords, s_trans.cart_coords, atol=1)) # test using same seed gives same coords mcrt = MonteCarloRattleTransformation(0.01, 2, seed=1) s_trans2 = mcrt.apply_transformation(s) self.assertTrue(np.allclose(s_trans.cart_coords, s_trans2.cart_coords)) if __name__ == "__main__": unittest.main()
gmatteo/pymatgen
pymatgen/transformations/tests/test_advanced_transformations.py
Python
mit
32,270
[ "VASP", "pymatgen" ]
ab089ca311e821a1c0ef3788a440ccb195a2012752cf6bb1390e6c9ddcfd4c67
class OWLAnnotationAxiomVisitor(object): """Marker class""" def visit(self, axiom): """ :param axiom: an object of one of these classes: - owlapy.model.OWLAnnotationAssertionAxiom - owlapy.model.OWLSubAnnotationPropertyOfAxiom - owlapy.model.OWLAnnotationPropertyDomainAxiom - owlapy.model.OWLAnnotationPropertyRangeAxiom :return: None """ raise NotImplementedError() class OWLAnnotationAxiomVisitorEx(object): """Marker Class""" def visit(self, axiom): """ :param axiom: an object of one of these classes: - owlapy.model.OWLAnnotationAssertionAxiom - owlapy.model.OWLSubAnnotationPropertyOfAxiom - owlapy.model.OWLAnnotationPropertyDomainAxiom - owlapy.model.OWLAnnotationPropertyRangeAxiom """ raise NotImplementedError()
patrickwestphal/owlapy
owlapy/model/owlannotationaxiomvisitor.py
Python
gpl-3.0
912
[ "VisIt" ]
83e24c5c9cc563a7e8a5ca2550750f3e95fca28b3e434514e68ec8298d6bb112
""" A module defining a function :func:`~mockdata` which is able to generate 1D mock data given a model, selection function and several other parameters. """ from .model import Schechter import numpy as np from scipy.integrate import quad from scipy.interpolate import InterpolatedUnivariateSpline as spline from .dffit import Data from .selection import SelectionRdep def mockdata( n=None, seed=None, model=Schechter(), selection=None, p=None, sigma=0, shot_noise=False, verbose=False, ): """ Generate 1D mock data. This function produces a mock survey with observed log-masses with Gaussian uncertainties and distances, using a custom mass function and selection function. Parameters ---------- n : int, optional Number of objects (galaxies) to be generated. If None, the number is determined from the mass function model and the selection criteria (specified by ``f`` and ``dVdr``). Otherwise, the survey volume (specified by the derivative ``dVdr``) is automatically multiplied by the scaling factor required to obtain the requested number of objects ``n``. seed : int, optional Used as seed for the random number generator. If you wish to generate different realizations, with the same survey specifications, it suffices to vary this number. model : :class:`~model.Model` intance Defines the 'generative distribution function', i.e. the underlying mass function, from which the galaxies are drawn. selection : :class:`~.selection.Selection` instance Defines the selection function. Any sub-class of :class:`~.selection.Selection` may be used. See docstrings for more info. p : tuple, optional Model parameters for the `model`. sigma : scalar or array-like Gaussian observing errors in log-mass ``x``, which are automatically added to the survey. If array-like, sigma must be equal to or longer than the number of samples, ``n``. shot_noise : bool, optional Whether the number of galaxies in the survey can differ from the expected number, following a Poisson distribution. verbose : bool, optional Whether information will be displayed in the console while generating the mock survey. Returns ------- data : :class:`~.dffit.Data` instance An instance of :class:`~.dffit.Data` ready to be passed to the fitting routine. selection : :class:`~.selection.Selection` instance An instance of :class:`~.selection.Selection` containing selection function quantities. Note, this is not to be passed to :class:`~dfft.DFFit`, as in real situations, these quantities are unknown. model : :class:`~.model.Model` instance A :class:`~.model.Model` instance defining the generative distribution used in this function (which can be directly passed to :class:`~.dffit.DFFit` to fit to the mock data). other : dict A dictionary containing the following entries: * scd: function returning the expected source count density as a function of log-mass ``x``. * rescaling_factor: value of rescaling factor applied to the cosmic volume to match the requested number of galaxies ``n``. * n: number of galaxies in sample * n_expected: expected number of galaxies in volume. * p: parameters of the model used. * dx: grid spacing used * x_true: the true log-masses (before scattering by uncertainty). Examples -------- Draw 1000 galaxies with mass errors of 0.3 dex from a Schechter function with parameters (-2,11,-1.3) and a preset selection function >>> import pydftools as df >>> data, selection, model, other = df.mockdata(n = 1000, sigma = 0.3) Plot the distance-log(mass) relation of observed data, true data, and approximate survey limit >>> import matplotlib.pyplot as plt >>> plt.scatter(data.r,data.x,color='blue') >>> plt.scatter(data.r,other['x_true'],color='green') >>> x = np.arange(5,11,0.01) >>> plt.plot(1e-2*sqrt(10**x),x,color='red') These data can then be used to fit a MF in several ways. For instance, assuming that the effective volume function Veff(x) is known: >>> selection_veff = df.selection.SelectionVeff(veff=selection.Veff) >>> survey = df.DFFit(data=data, selection=selection, model=model) Or assuming that Veff is known only on a galaxy-by-galaxy basis >>> selection_pts = df.selection.SelectionVeffPoints(xval = data.x, veff = selection.Veff(data.x)) >>> survey = df.DFFit(data=data, selection=selection_pts,model=model) Or assuming that Veff is known on a galaxy-by-balaxy basis, but approximate analytically outside the range of observed galaxy masses >>> selection_pts_fnc = df.selection.SelectionVeffPoints(xval = data.x, veff = selection.Veff(data.x), veff_extrap=selection.Veff) >>> survey = df.DFFit(data=data, selection=selection_pts_fnc,model=model) Or assuming that the full selection function f(x,r) and the observing volume derivative dVdr(r) are known >>> survey = df.DFFit(data=data, selection=selection,model=model) """ # Set default p if p is None: p = model.p0 if selection is None: selection = SelectionRdep(xmin=4.0, xmax=13.0, rmin=0, rmax=20) # Check whether the model can be evaluated at p try: test = model.gdf(selection.xmin, p) except Exception as e: raise e if np.isinf(test): raise ValueError("model cannot be evaluated for parameter-vector p.") if seed: np.random.seed(seed) # Generate source count function (including LSS if present) def scd(x): return selection.Veff(x) * model.gdf(x, p) # compute expected number of galaxies (accounting for lss if present) n_expected = quad(scd, selection.xmin, selection.xmax)[0] n_expected_large = quad( scd, 2 * selection.xmin - selection.xmax, 2 * selection.xmax - selection.xmin )[0] if n_expected_large > 1.001 * n_expected: raise ValueError( "A non-negligible number of galaxies lies outside the range xmin-xmax. Please change this range." ) # rescale effective volume to match the (optional) requested number of galaxies if n is None: if n_expected < 2: raise ValueError( "Input arguments imply less than two sources in the survey." ) rescaling_factor = 1 else: if n < 2: raise ValueError("Number of sources must be at least 2.") rescaling_factor = n / n_expected selection.vol_renorm *= rescaling_factor n_expected = n # make actual number of sources if shot_noise: n = int(max(1, np.random.poisson(n_expected))) else: n = int(round(n_expected)) if verbose: print("Number of sources in the mock survey (expected): %.3f" % n_expected) print("Number of sources in the mock survey (selected): %d" % n) # sample masses (x) dx = min(0.005, (selection.xmax - selection.xmin) / 1000.0) xgrid = np.arange(selection.xmin, selection.xmax, dx) cdf = np.cumsum( scd(xgrid) ) # cumulative distribution function of source count density if cdf[-2] == cdf[-1]: indxu = np.where(cdf == cdf[-1])[0][ 0 ] # only interpolate up to where cdf stops rising, otherwise errors occur else: indxu = len(cdf) - 1 if cdf[1] == cdf[0]: indxl = np.where(cdf == cdf[0])[0][ -1 ] # only interpolate up to where cdf stops rising, otherwise errors occur else: indxl = 0 qnf = spline( cdf[indxl:indxu], xgrid[indxl:indxu] ) # quantile function of source count density x = qnf(np.random.uniform(cdf[0], cdf[-1], size=n)) # add mass observing errors (x.err) if sigma is not None: if hasattr(sigma, "__len__"): if len(sigma) < n: raise ValueError("If sigma is a vector its too short.") else: x_err = sigma[:n] else: x_err = np.repeat(sigma, n) x_obs = x + np.random.normal(size=n) * x_err else: x_obs = x x_err = None if hasattr(selection, "mock_r"): r = selection.mock_r(x, verbose=verbose) else: r = None return ( Data(x=x_obs, x_err=x_err, r=r), selection, model, dict( x_true=x, dx=dx, scd=scd, p=p, rescaling_factor=rescaling_factor, n=n, n_expected=n_expected, ), )
steven-murray/pydftools
pydftools/mockdata.py
Python
mit
8,710
[ "Galaxy", "Gaussian" ]
e1539170fe6eeeafbce416d7d6dde916e35583ac5ce55269db82781a55c0101e
"""CRAWL-E is a highly distributed web crawling framework.""" import Queue, cStringIO, gzip, httplib, logging, mimetypes, resource, socket import sys, subprocess, threading, time, urllib, urlparse from optparse import OptionParser VERSION = '0.6.4' HEADER_DEFAULTS = {'Accept':'*/*', 'Accept-Language':'en-us,en;q=0.8', 'User-Agent':'CRAWL-E/%s' % VERSION} DEFAULT_SOCKET_TIMEOUT = 30 STOP_CRAWLE = False class CrawleException(Exception): """Base Crawle exception class.""" class CrawleRequestAborted(CrawleException): """Exception raised when the handler pre_process function sets the response_url to None to indicate not to visit the URL.""" class CrawleStopped(CrawleException): """Exception raised when the crawler is stopped.""" class CrawleUnsupportedScheme(CrawleException): """Exception raised when the url does not start with "http" or "https".""" class CrawleRedirectsExceeded(CrawleException): """Exception raised when the number of redirects exceeds the limit.""" class Handler(object): """An _abstract_ class for handling what urls to retrieve and how to parse and save them. The functions of this class need to be designed in such a way so that they are threadsafe as multiple threads will have access to the same instance. """ def pre_process(self, request_response): """pre_process is called directly before making the reqeust. Any of the request parameters can be modified here. Setting the responseURL to None will cause the request to be dropped. This is useful for testing if a redirect link should be followed. """ return def process(self, request_response, queue): """Process is called after the request has been made. It needs to be implemented by a subclass. Keyword Arguments: request_response -- the request response object queue -- the handler to the queue class """ assert request_response and queue # pychecker hack raise NotImplementedError(' '.join(('Handler.process must be defined', 'in a subclass'))) class RequestResponse(object): """This class is a container for information pertaining to requests and responses.""" def __init__(self, url, headers=None, method='GET', params=None, files=None, redirects=10): """Constructs a RequestResponse object. Keyword Arguments: url -- The url to request. headers -- The http request headers. method -- The http request method. params -- The http parameters as a dictionary. files -- A list of tuples containing key, filename, filedata redirects -- The maximum number of redirects to follow. """ self.error = None self.redirects = redirects self.extra = [] self.request_headers = headers self.request_url = url self.request_method = method self.request_params = params self.request_files = files self.response_status = None self.response_url = url self.response_headers = None self.response_body = None self.response_time = None class HTTPConnectionQueue(object): """This class handles the queue of sockets for a particular address. This essentially is a queue of socket objects which also adds a transparent field to each connection object which is the request_count. When the request_count exceeds the REQUEST_LIMIT the connection is automatically reset. """ REQUEST_LIMIT = None @staticmethod def connection_object(address, encrypted): """Very simply return a HTTP(S)Connection object.""" if encrypted: connection = httplib.HTTPSConnection(*address) else: connection = httplib.HTTPConnection(*address) connection.request_count = 0 return connection def __init__(self, address, encrypted=False, max_conn=None): """Constructs a HTTPConnectionQueue object. Keyword Arguments: address -- The address for which this object maps to. encrypted -- Where or not the connection is encrypted. max_conn -- The maximum number of connections to maintain """ self.address = address self.encrypted = encrypted self.queue = Queue.Queue(0) self.connections = 0 self.max_conn = max_conn def destroy(self): """Destroy the HTTPConnectionQueue object.""" try: while True: connection = self.queue.get(block=False) connection.close() except Queue.Empty: pass def get(self): """Return a HTTP(S)Connection object for the appropriate address. First try to return the object from the queue, however if the queue is empty create a new socket object to return. Dynamically add new field to HTTPConnection called request_count to keep track of the number of requests made with the specific connection. """ try: connection = self.queue.get(block=False) self.connections -= 1 # Reset the connection if exceeds request limit if (self.REQUEST_LIMIT and connection.request_count >= self.REQUEST_LIMIT): connection.close() connection = HTTPConnectionQueue.connection_object( self.address, self.encrypted) except Queue.Empty: connection = HTTPConnectionQueue.connection_object(self.address, self.encrypted) return connection def put(self, connection): """Put the HTTPConnection object back on the queue.""" connection.request_count += 1 if self.max_conn != None and self.connections + 1 > self.max_conn: connection.close() else: self.queue.put(connection) self.connections += 1 class QueueNode(object): """This class handles an individual node in the CQueueLRU.""" def __init__(self, connection_queue, key, next=None): """Construct a QueueNode object. Keyword Arguments: connection_queue -- The ConnectionQueue object. key -- The unique identifier that allows one to perform a reverse lookup in the hash table. next -- The previous least recently used item. """ self.connection_queue = connection_queue self.key = key self.next = next if next: self.next.prev = self self.prev = None def remove(self): """Properly remove the node""" if self.prev: self.prev.next = None self.connection_queue.destroy() class CQueueLRU(object): """This class manages a least recently used list with dictionary lookup.""" def __init__(self, max_queues=None, max_conn=None): """Construct a CQueueLRU object. Keyword Arguments: max_queues -- The maximum number of unique queues to manage. When only crawling a single domain, one should be sufficient. max_conn -- The maximum number of connections that may persist within a single ConnectionQueue. """ self.lock = threading.Lock() self.max_queues = max_queues self.max_conn = max_conn self.table = {} self.newest = None self.oldest = None def __getitem__(self, key): """Return either a HTTP(S)Connection object. Fetches an already utilized object if one exists. """ self.lock.acquire() if key in self.table: connection = self.table[key].connection_queue.get() else: connection = HTTPConnectionQueue.connection_object(*key) self.lock.release() return connection def __setitem__(self, key, connection): """Store the HTTP(S)Connection object. This function ensures that there are at most max_queues. In the event there are too many, the oldest inactive queues will be deleted. """ self.lock.acquire() if key in self.table: node = self.table[key] # move the node to the head of the list if self.newest != node: node.prev.next = node.next if self.oldest != node: node.next.prev = node.prev else: self.oldest = node.prev node.prev = None node.next = self.newest self.newest = node.next.prev = node else: # delete the oldest while too many while (self.max_queues != None and len(self.table) + 1 > self.max_queues): if self.oldest == self.newest: self.newest = None del self.table[self.oldest.key] prev = self.oldest.prev self.oldest.remove() self.oldest = prev connection_queue = HTTPConnectionQueue(*key, max_conn=self.max_conn) node = QueueNode(connection_queue, key, self.newest) self.newest = node if not self.oldest: self.oldest = node self.table[key] = node node.connection_queue.put(connection) self.lock.release() class HTTPConnectionControl(object): """This class handles HTTPConnectionQueues by storing a queue in a dictionary with the address as the index to the dictionary. Additionally this class handles resetting the connection when it reaches a specified request limit. """ def __init__(self, handler, max_queues=None, max_conn=None, timeout=None): """Constructs the HTTPConnection Control object. These objects are to be shared between each thread. Keyword Arguments: handler -- The Handler class for checking if a url is valid. max_queues -- The maximum number of connection_queues to maintain. max_conn -- The maximum number of connections (sockets) allowed for a given connection_queue. timeout -- The socket timeout value. """ socket.setdefaulttimeout(timeout) self.cq_lru = CQueueLRU(max_queues, max_conn) self.handler = handler def _build_request(self, req_res): """Construct request headers and URI from request_response object.""" u = urlparse.urlparse(req_res.response_url) if u.scheme not in ['http', 'https'] or u.netloc == '': raise CrawleUnsupportedScheme() address = socket.gethostbyname(u.hostname), u.port encrypted = u.scheme == 'https' url = urlparse.urlunparse(('', '', u.path, u.params, u.query, '')) if req_res.request_headers: headers = req_res.request_headers else: headers = {} if 'Accept' not in headers: headers['Accept'] = HEADER_DEFAULTS['Accept'] if 'Accept-Encoding' not in headers: headers['Accept-Encoding'] = 'gzip' if 'Accept-Languge' not in headers: headers['Accept-Language'] = HEADER_DEFAULTS['Accept-Language'] if 'Host' not in headers: if u.port == None: headers['Host'] = u.hostname else: headers['Host'] = '%s:%d' % (u.hostname, u.port) if 'User-Agent' not in headers: headers['User-Agent'] = HEADER_DEFAULTS['User-Agent'] return address, encrypted, url, headers def request(self, req_res): """Handles the request to the server.""" if STOP_CRAWLE: raise CrawleStopped() self.handler.pre_process(req_res) if req_res.response_url == None: raise CrawleRequestAborted() address, encrypted, url, headers = self._build_request(req_res) connection = self.cq_lru[(address, encrypted)] try: start = time.time() if req_res.request_files: content_type, data = self.encode_multipart_formdata( req_res.request_params, req_res.request_files) headers['Content-Type'] = content_type elif req_res.request_params: data = urllib.urlencode(req_res.request_params) headers['Content-Type'] = 'application/x-www-form-urlencoded' else: data = '' connection.request(req_res.request_method, url, data, headers) response = connection.getresponse() response_time = time.time() - start response_body = response.read() self.cq_lru[(address, encrypted)] = connection except Exception: connection.close() raise if response.status in (301, 302, 303) and req_res.redirects != None: if req_res.redirects <= 0: raise CrawleRedirectsExceeded() req_res.redirects -= 1 redirect_url = response.getheader('location') req_res.response_url = urlparse.urljoin(req_res.response_url, redirect_url) self.request(req_res) else: req_res.response_time = response_time req_res.response_status = response.status req_res.response_headers = dict(response.getheaders()) if ('content-encoding' in req_res.response_headers and req_res.response_headers['content-encoding'] == 'gzip'): try: fileobj = cStringIO.StringIO(response_body) temp = gzip.GzipFile(fileobj=fileobj) req_res.response_body = temp.read() temp.close() fileobj.close() except IOError: # HACK for pages that append plain text to gzip output sb = subprocess.Popen(['zcat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sb.stdin.write(response_body) sb.stdin.close() req_res.response_body = sb.stdout.read() del sb req_res.extra.append('Used zcat') else: req_res.response_body = response_body # The following function is modified from the snippet at: # http://code.activestate.com/recipes/146306/ def encode_multipart_formdata(self, fields, files): """Encode data properly when files are uploaded. Keyword Arguments: fields -- A dictionary containing key value pairs for form submission files -- A list of tuples with key, filename, file data for form submission. """ default_type = 'application/octet-stream' BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for key, value in fields.items(): L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) content_type = mimetypes.guess_type(filename)[0] or default_type L.append('Content-Type: %s' % content_type) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body class ControlThread(threading.Thread): """A single thread of control""" def __init__(self, connection_control, handler, queue): """Sets up the ControlThread. Keyword Arguments: connection_control -- A HTTPConnectionControl object. This object is shared amongst the threads handler -- The handler class for parsing the returned information queue -- The handle to the queue class which implements get and put. """ threading.Thread.__init__(self) self.connection_control = connection_control self.handler = handler self.queue = queue def run(self): """This is the execution order of a single thread. The threads will stop when STOP_CRAWLE becomes true, or when the queue raises Queue.Empty. """ while not STOP_CRAWLE: try: request_response = self.queue.get() except Queue.Empty: break try: self.connection_control.request(request_response) except Exception, e: request_response.error = e self.handler.process(request_response, self.queue) self.queue.work_complete() class Controller(object): """The primary controller manages all the threads.""" def __init__(self, handler, queue, num_threads=1, timeout=DEFAULT_SOCKET_TIMEOUT): """Create the controller object Keyword Arguments: handler -- The Handler class each thread will use for processing queue -- The handle the the queue class num_threads -- The number of threads to spawn (Default 1) timeout -- The socket timeout time """ nofiles = resource.getrlimit(resource.RLIMIT_NOFILE)[0] queues = nofiles * 2 / (num_threads * 3) self.connection_ctrl = HTTPConnectionControl(handler=handler, max_queues=queues, max_conn=num_threads, timeout=timeout) self.handler = handler self.threads = [] for _ in range(num_threads): thread = ControlThread(handler=handler, queue=queue, connection_control=self.connection_ctrl) self.threads.append(thread) def start(self): """Starts all threads""" for thread in self.threads: thread.start() def join(self): """Join on all threads""" for thread in self.threads: while 1: thread.join(1) if not thread.isAlive(): break def stop(self): """Stops all threads gracefully""" global STOP_CRAWLE STOP_CRAWLE = True self.join() class VisitURLHandler(Handler): """Very simple example handler which simply visits the page. This handler just demonstrates how to interact with the queue. """ def process(self, info, queue): """Puts item back on the queue if the request was no successful.""" if info['status'] != 200: print 'putting %s back on queue' % info['url'] queue.put(info['url']) class CrawlQueue(object): """Crawl Queue is a mostly abstract concurrent Queue class. Users of this class must implement their specific __init__, _get, and _put functions both initialize their queue, get items from the queue, and put items into the queue. The CrawlQueue class takes care of concurrency issues, so that subclass implementations can be assured atomic accesses to the user defined _get and _put functions. As such both the user defined _get and _put functions should be nonblocking. In addition to assuring atomic access, the CrawlQueue class manages the number of outstanding workers so that it only raises Queue.Empty when both its queue it empty and there is no outstanding work. """ def __init__(self, single_threaded=False): """Initializes the CrawlQueue class with a condition variable and container for the numer of workers.""" if not single_threaded: self._lock = threading.Lock() self.cv = threading.Condition(self._lock) else: self.cv = None self._workers = 0 def get(self): """The interface to obtaining an object from the queue. This function manages the concurrency and waits for more items if there is outstanding work, otherwise it raises Queue.Empty. This class should not be overwritten, but rather the user should write a _get class. """ while True: if self.cv: self.cv.acquire() try: item = self._get() self._workers += 1 return item except Queue.Empty: if self._workers == 0: if self.cv: self.cv.notify_all() raise if not self.cv: raise Exception('Invalid single thread handling') self.cv.wait() finally: if self.cv: self.cv.release() def put(self, item): """The interface for putting an item on the queue. This function manages concurrency and notifies other threads when an item is added.""" if self.cv: self.cv.acquire() try: self._put(item) if self.cv: self.cv.notify() finally: if self.cv: self.cv.release() def work_complete(self): """Called by the ControlThread after the user defined handler has returned thus indicating no more items will be added to the queue from that thread before the next call to get.""" if self.cv: self.cv.acquire() if self._workers > 0: self._workers -= 1 if self.cv: self.cv.notify() self.cv.release() def _get(self): """Function to be implemented by the user.""" raise NotImplementedError('CrawlQueue._get() must be implemented') def _put(self, item): """Function to be implemented by the user.""" assert item # pychecker hack raise NotImplementedError('CrawlQueue._put(...) must be implemented') class URLQueue(CrawlQueue): """URLQueue is the most basic queue type and is all that is needed for most situations. Simply, it queues full urls.""" formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) sh.setFormatter(formatter) logger = logging.getLogger('queue') logger.setLevel(logging.DEBUG) logger.addHandler(sh) LOG_STRING = 'Crawled: %d Remaining: %d RPS: %.2f (%.2f avg)' def __init__(self, seed_file=None, seed_urls=None, single_threaded=False, log_after=1000): """Sets up the URLQueue by creating a queue. Keyword arguments: seedfile -- file containing urls to seed the queue (default None) """ super(URLQueue, self).__init__(single_threaded) self.queue = [] self.start_time = self.block_time = None self.total_items = 0 self.log_after = log_after # Add seeded items to the queue if seed_file: try: fp = open(seed_file) except IOError: raise Exception('Could not open seed file') for line in fp: self.queue.append(line.strip()) fp.close() URLQueue.logger.info('Queued: %d from seed file' % len(self.queue)) if seed_urls: [self.queue.put(x) for x in seed_urls] URLQueue.logger.info('Queued: %d from seed url' % len(seed_urls)) if len(self.queue) == 0: URLQueue.logger.info('Starting with empty queue') def save(self, save_file): """Outputs queue to file specified. On error prints queue to screen.""" try: fp = open(save_file, 'w') except IOError: URLQueue.logger.warn('Could not open file for saving.') fp = sys.stdout items = 0 for item in self.queue: fp.write('%s\n' % item) items += 1 if fp != sys.stdout: fp.close() URLQueue.logger.info('Saved %d items.' % items) def _get(self): """Return url at the head of the queue or raise Queue.Empty""" if len(self.queue): url = self.queue.pop(0) self.total_items += 1 if self.start_time == None: self.start_time = self.block_time = time.time() elif (self.log_after and self.total_items % self.log_after == 0): now = time.time() rps_now = self.log_after / (now - self.block_time) rps_avg = self.total_items / (now - self.start_time) log = URLQueue.LOG_STRING % (self.total_items, len(self.queue), rps_now, rps_avg) URLQueue.logger.info(log) self.block_time = now return RequestResponse(url) else: raise Queue.Empty def _put(self, url): """Puts the item back on the queue.""" self.queue.append(url) def quick_request(url, redirects=30, timeout=30): """Convenience function to quickly request a URL within CRAWl-E.""" cc = HTTPConnectionControl(Handler(), timeout=timeout) rr = RequestResponse(url, redirects=redirects) cc.request(rr) return rr def run_crawle(argv, handler, log_after=1): """The typical way to start CRAWL-E""" parser = OptionParser() parser.add_option('-t', '--threads', help='number of threads to use', type='int', default=1) parser.add_option('-s', '--seed', help='file to seed queue with') parser.add_option('-u', '--url', help='url to seed queue with', action='append', metavar='URL', dest='urls') parser.add_option('-S', '--save', help='file to save remaining urls to') options, args = parser.parse_args() queue_handler = URLQueue(seed_file=options.seed, seed_urls=options.urls) controller = Controller(handler=handler, queue=queue_handler, num_threads=options.threads) controller.start() try: controller.join() except KeyboardInterrupt: controller.stop() if options.save: queue_handler.save(options.save) if __name__ == '__main__': """Basic example of how to start CRAWL-E.""" run_crawle(sys.argv, handler=VisitURLHandler())
davesabatini/crawl-e
crawle.py
Python
bsd-3-clause
27,065
[ "VisIt" ]
b87f936616fc17538ba22261ea9c5b729e0cad21837f5ef8cdb2d5005105bd01
# This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. """Perform quick astronomical stellar analysis. **Plugin Type: Local** ``Pick`` is a local plugin, which means it is associated with a channel. An instance can be opened for each channel. **Usage** The ``Pick`` plugin is used to perform quick astronomical data quality analysis on stellar objects. It locates stellar candidates within a drawn box and picks the most likely candidate based on a set of search settings. The Full Width Half Max (FWHM) is reported on the candidate object, as well as its size based on the plate scale of the detector. Rough measurement of background, sky level and brightness is also done. **Defining the pick area** The default pick area is defined as a box of approximately 30x30 pixels that encloses the search area. The move/draw/edit selector at the bottom of the plugin is used to determine what operation is being done to the pick area: .. figure:: figures/pick-move-draw-edit.png :width: 400px :align: center :alt: Move, Draw and Edit buttons "Move", "Draw", and "Edit" buttons. * If "move" is selected, then you can move the existing pick area by dragging it or clicking where you want the center of it placed. If there is no existing area, a default one will be created. * If "draw" is selected, then you can draw a shape with the cursor to enclose and define a new pick area. The default shape is a box, but other shapes can be selected in the "Settings" tab. * If "edit" is selected, then you can edit the pick area by dragging its control points, or moving it by dragging in the bounding box. After the area is moved, drawn or edited, ``Pick`` will perform one of three actions: 1. In "Quick Mode" ON, with "From Peak" OFF, it will simply attempt to perform a calculation based on the coordinate under the crosshair in the center of the pick area. 2. In "Quick Mode" ON, with "From Peak" ON, it will perform a quick detection of peaks in the pick area and perform a calculation on the first one found, using the peak's coordinates. 3. In "Quick Mode" OFF, it will search the area for all peaks and evaluate the peaks based on the criteria in the "Settings" tab of the UI (see "The Settings Tab" below) and try to locate the best candidate matching the settings. **If a candidate is found** The candidate will be marked with a point (usually an "X") in the channel viewer canvas, centered on the object as determined by the horizontal and vertical FWHM measurements. The top set of tabs in the UI will be populated as follows: .. figure:: figures/pick-cutout.png :width: 400px :align: center :alt: Image tab of Pick area "Image" tab of ``Pick`` area. The "Image" tab will show the contents of the cutout area. The widget in this tab is a Ginga widget and so can be zoomed and panned with the usual keyboard and mouse bindings (e.g., scroll wheel). It will also be marked with a point centered on the object and additionally the pan position will be set to the found center. .. figure:: figures/pick-contour.png :width: 300px :align: center :alt: Contour tab of Pick area "Contour" tab of ``Pick`` area. The "Contour" tab will show a contour plot. This is a contour plot of the area immediately surrounding the candidate, and not usually encompassing the entire region of the pick area. You can use the scroll wheel to zoom the plot and a click of the scroll wheel (mouse button 2) to set the pan position in the plot. .. figure:: figures/pick-fwhm.png :width: 400px :align: center :alt: FWHM tab of Pick area "FWHM" tab of ``Pick`` area. The "FWHM" tab will show a FWHM plot. The purple lines show measurements in the X direction and the green lines show measurements in the Y direction. The solid lines indicate actual pixel values and the dotted lines indicate the fitted 1D function. The shaded purple and green regions indicate the FWHM measurements for the respective axes. .. figure:: figures/pick-radial.png :width: 400px :align: center :alt: Radial tab of Pick area "Radial" tab of ``Pick`` area. The "Radial" tab contains a radial profile plot. Plotted points in purple are data values, and a line is fitted to the data. .. figure:: figures/pick-ee.png :width: 600px :align: center :alt: EE tab of Pick area "EE" tab of ``Pick`` area. The "EE" tab contains a plot of fractional encircled and ensquared energies (EE) in purple and green, respectively, for the chosen target. Simple background subtraction is done in a way that is consistent with FWHM calculations before EE values are measured. The sampling and total radii, shown as black dashed lines, can be set in the "Settings" tab; when these are changed, click "Redo Pick" to update the plot and measurements. The measured EE values at the given sampling radius are also displayed in the "Readout" tab. When reporting is requested, the EE values at the given sampling radius and the radius itself will be recorded under "Report" table, along with other information. When "Show Candidates" is active, the candidates near the edges of the bounding box will not have EE values (set to 0). .. figure:: figures/pick-readout.png :width: 400px :align: center :alt: Readout tab of Pick area "Readout" tab of ``Pick`` area. The "Readout" tab will be populated with a summary of the measurements. There are two buttons and three check boxes in this tab: * The "Default Region" button restores the pick region to the default shape and size. * The "Pan to pick" button will pan the channel viewer to the located center. * The "Quick Mode" check box toggles "Quick Mode" on and off. This affects the behavior of the pick region as described above. * The "From Peak" check box changes the behavior of "Quick Mode" slightly as described above. * If "Center on pick" is checked, the shape will be recentered on the located center, if found (i.e., the shape "tracks" the pick). .. figure:: figures/pick-controls.png :width: 400px :align: center :alt: Controls tab of Pick area "Controls" tab of ``Pick`` area. The "Controls" tab has a couple of buttons that will work off of the measurements. * The "Bg cut" button will set the low cut level of the channel viewer to the measured background level. A delta to this value can be applied by setting a value in the "Delta bg" box (press "Enter" to change the setting). * The "Sky cut" button will set the low cut level of the channel viewer to the measured sky level. A delta to this value can be applied by setting a value in the "Delta sky" box (press "Enter" to change the setting). * The "Bright cut" button will set the high cut level of the channel viewer to the measured sky+brightness levels. A delta to this value can be applied by setting a value in the "Delta bright" box (press "Enter" to change the setting). .. figure:: figures/pick-report.png :width: 400px :align: center :alt: Report tab of Pick area "Report" tab of ``Pick`` area. The "Report" tab is used to record information about the measurements in tabular form. By pressing the "Add Pick" button, the information about the most recent candidate is added to the table. If the "Record Picks automatically" checkbox is checked, then any candidates are added to the table automatically. .. note:: If the "Show Candidates" checkbox in the "Settings" tab is checked, then *all* objects found in the region (according to the settings) will be added to the table instead of just the selected candidate. You can clear the table at any time by pressing the "Clear Log" button. The log can be saved to a table by putting a valid path and filename in the "File:" box and pressing "Save table". File type is automatically determined by the given extension (e.g., ".fits" is FITS and ".txt" is plain text). **If no candidate is found** If no candidate can be found (based on the settings), then the pick area is marked with a red point centered on the pick area. .. figure:: figures/pick-no-candidate.png :width: 800px :align: center :alt: Marker when no candidate found Marker when no candidate found. The image cutout will be taken from this central area and so the "Image" tab will still have content. It will also be marked with a central red "X". The contour plot will still be produced from the cutout. .. figure:: figures/pick-contour-no-candidate.png :width: 400px :align: center :alt: Contour when no candidate found. Contour when no candidate found. All the other plots will be cleared. **The Settings Tab** .. figure:: figures/pick-settings.png :width: 400px :align: center :alt: Settings tab of Pick plugin "Settings" tab of ``Pick`` plugin. The "Settings" tab controls aspects of the search within the pick area: * The "Show Candidates" checkbox controls whether all detected sources are marked or not (as shown in the figure below). Additionally, if checked, then all the found objects are added to the pick log table when using the "Report" controls. * The "Draw type" parameter is used to choose the shape of the pick area to be drawn. * The "Radius" parameter sets the radius to be used when finding and evaluating bright peaks in the image. * The "Threshold" parameter is used to set a threshold for peak finding; if set to "None", then a reasonable default value will be chosen. * The "Min FWHM" and "Max FWHM" parameters can be used to eliminate certain sized objects from being candidates. * The "Ellipticity" parameter is used to eliminate candidates based on their asymmetry in shape. * The "Edge" parameter is used to eliminate candidates based on how close to the edge of the cutout they are. *NOTE: currently this works reliably only for non-rotated rectangular shapes.* * The "Max side" parameter is used to limit the size of the bounding box that can be used in the pick shape. Larger sizes take longer to evaluate. * The "Coordinate Base" parameter is an offset to apply to located sources. Set to "1" if you want sources pixel locations reported in a FITS-compliant manner and "0" if you prefer 0-based indexing. * The "Calc center" parameter is used to determine whether the center is calculated from FWHM fitting ("fwhm") or centroiding ("centroid"). * The "FWHM fitting" parameter is used to determine which function is is used for FWHM fitting ("gaussian" or "moffat"). The option to use "lorentz" is also available if "calc_fwhm_lib" is set to "astropy" in ``~/.ginga/plugin_Pick.cfg``. * The "Contour Interpolation" parameter is used to set the interpolation method used in rendering the background image in the "Contour" plot. * The "EE total radius" defines the radius (for encircled energy) and box half-width (for ensquared energy) in pixels where EE fraction is expected to be 1 (i.e., all the flux for a point-spread function is contained within). * The "EE sampling radius" is the radius in pixel used to sample the measured EE curves for reporting. The "Redo Pick" button will redo the search operation. It is convenient if you have changed some parameters and want to see the effect based on the current pick area without disturbing it. .. figure:: figures/pick-candidates.png :width: 600px :align: center :alt: The channel viewer when "Show Candidates" is checked. The channel viewer when "Show Candidates" is checked. **User Configuration** """ import threading import sys import traceback import time from collections import OrderedDict import numpy as np from ginga.gw import Widgets, Viewers from ginga.misc import Bunch from ginga.util import wcs, contour from ginga import GingaPlugin, cmap, trcalc try: from ginga.gw import Plot from ginga.util import plots have_mpl = True except ImportError: have_mpl = False region_default_width = 30 region_default_height = 30 __all__ = ['Pick'] class Pick(GingaPlugin.LocalPlugin): def __init__(self, fv, fitsimage): # superclass defines some variables for us, like logger super(Pick, self).__init__(fv, fitsimage) self.layertag = 'pick-canvas' self.pickimage = None self.pickcenter = None self.pick_qs = None self.pick_obj = None self._textlabel = 'Pick' self.contour_image = None self.contour_plot = None self.fwhm_plot = None self.radial_plot = None self.contour_interp_methods = trcalc.interpolation_methods # types of pick shapes that can be drawn self.drawtypes = ['box', 'squarebox', 'rectangle', 'circle', 'ellipse', 'freepolygon', 'polygon', ] # get Pick preferences prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_Pick') self.settings.load(onError='silent') self.sync_preferences() self.pick_x1 = 0 self.pick_y1 = 0 self.pick_data = None self.pick_log = None self.dx = region_default_width self.dy = region_default_height # For offloading intensive calculation from graphics thread self.serialnum = 0 self.lock = threading.RLock() self.lock2 = threading.RLock() self.ev_intr = threading.Event() self._wd, self._ht = 400, 300 self._split_sizes = [self._ht, self._ht] self.last_rpt = [] self.rpt_dict = OrderedDict({}) self.rpt_cnt = 0 self.rpt_tbl = None self.rpt_mod_time = 0.0 self.rpt_wrt_time = 0.0 self.rpt_wrt_interval = self.settings.get('report_write_interval', 30.0) if self.iqcalc_lib == 'astropy': self.logger.debug('Using iqcalc_astropy') from ginga.util import iqcalc_astropy as iqcalc else: # Falls back to native self.logger.debug('Using native iqcalc') from ginga.util import iqcalc if not iqcalc.have_scipy: raise ImportError('Please install scipy to use this plugin') self.iqcalc = iqcalc.IQCalc(self.logger) self.copy_attrs = ['transforms', 'cutlevels'] if (self.settings.get('pick_cmap_name', None) is None and self.settings.get('pick_imap_name', None) is None): self.copy_attrs.append('rgbmap') self.dc = self.fv.get_draw_classes() canvas = self.dc.DrawingCanvas() canvas.enable_draw(True) canvas.enable_edit(True) canvas.set_drawtype(self.pickshape, color='cyan', linestyle='dash') canvas.set_callback('draw-event', self.draw_cb) canvas.set_callback('edit-event', self.edit_cb) canvas.add_draw_mode('move', down=self.btn_down, move=self.btn_drag, up=self.btn_up) canvas.register_for_cursor_drawing(self.fitsimage) canvas.set_surface(self.fitsimage) canvas.set_draw_mode('move') self.canvas = canvas self.have_mpl = have_mpl self.gui_up = False def sync_preferences(self): # Load various preferences self.pickcolor = self.settings.get('color_pick', 'green') self.pickshape = self.settings.get('shape_pick', 'box') if self.pickshape not in self.drawtypes: self.pickshape = 'box' self.candidate_color = self.settings.get('color_candidate', 'orange') self.quick_mode = self.settings.get('quick_mode', False) self.from_peak = self.settings.get('quick_from_peak', True) # Peak finding parameters and selection criteria self.max_side = self.settings.get('max_side', 1024) self.radius = self.settings.get('radius', 10) self.ee_total_radius = self.settings.get('ee_total_radius', 10.0) self.ee_sampling_radius = self.settings.get('ee_sampling_radius', 2.5) self.threshold = self.settings.get('threshold', None) self.min_fwhm = self.settings.get('min_fwhm', 1.5) self.max_fwhm = self.settings.get('max_fwhm', 50.0) self.min_ellipse = self.settings.get('min_ellipse', 0.5) self.edgew = self.settings.get('edge_width', 0.01) self.show_candidates = self.settings.get('show_candidates', False) # Report in 0- or 1-based coordinates coord_offset = self.fv.settings.get('pixel_coords_offset', 0.0) self.pixel_coords_offset = self.settings.get('pixel_coords_offset', coord_offset) self.center_algs = ['fwhm', 'centroid'] self.center_alg = self.settings.get('calc_center_alg', 'fwhm') self.fwhm_algs = ['gaussian', 'moffat'] self.iqcalc_lib = self.settings.get('calc_fwhm_lib', 'native') if self.iqcalc_lib == 'astropy': self.fwhm_algs.append('lorentz') self.fwhm_alg = self.settings.get('calc_fwhm_alg', 'gaussian') self.center_on_pick = self.settings.get('center_on_pick', False) # For controls self.delta_bg = self.settings.get('delta_bg', 0.0) self.delta_sky = self.settings.get('delta_sky', 0.0) self.delta_bright = self.settings.get('delta_bright', 0.0) # Formatting for reports self.do_record = self.settings.get('record_picks', False) columns = [("RA", 'ra_txt'), ("DEC", 'dec_txt'), ("Equinox", 'equinox'), ("X", 'x'), ("Y", 'y'), ("FWHM", 'fwhm'), ("FWHM_X", 'fwhm_x'), ("FWHM_Y", 'fwhm_y'), ("EE_circ", 'encircled_energy'), ("EE_sq", 'ensquared_energy'), ("EE_r", 'ee_sampling_radius'), ("Star Size", 'starsize'), ("Ellip", 'ellipse'), ("Background", 'background'), ("Sky Level", 'skylevel'), ("Brightness", 'brightness'), ("Time Local", 'time_local'), ("Time UT", 'time_ut'), ("RA deg", 'ra_deg'), ("DEC deg", 'dec_deg'), ] self.rpt_columns = self.settings.get('report_columns', columns) # For contour plot self.num_contours = self.settings.get('num_contours', 8) self.contour_size_max = self.settings.get('contour_size_limit', 100) self.contour_size_min = self.settings.get('contour_size_min', 30) self.contour_interpolation = self.settings.get('contour_interpolation', 'nearest') def build_gui(self, container): vtop = Widgets.VBox() vtop.set_border_width(4) box, sw, orientation = Widgets.get_oriented_box(container, orientation=self.settings.get('orientation', None)) box.set_border_width(4) box.set_spacing(2) paned = Widgets.Splitter(orientation=orientation) self.w.splitter = paned nb = Widgets.TabWidget(tabpos='bottom') self.w.nb1 = nb paned.add_widget(Widgets.hadjust(nb, orientation)) cm, im = self.fv.cm, self.fv.im # Set up "Image" tab viewer di = Viewers.CanvasView(logger=self.logger) width, height = self._wd, self._ht di.set_desired_size(width, height) di.enable_autozoom('override') di.enable_autocuts('off') di.set_zoom_algorithm('rate') di.set_zoomrate(1.6) settings = di.get_settings() settings.get_setting('zoomlevel').add_callback('set', self.zoomset, di) cmname = self.settings.get('pick_cmap_name', None) if cmname is not None: di.set_color_map(cmname) else: di.set_cmap(cm) imname = self.settings.get('pick_imap_name', None) if imname is not None: di.set_intensity_map(imname) else: di.set_imap(im) di.set_callback('none-move', self.detailxy) di.set_bg(0.4, 0.4, 0.4) # for debugging di.set_name('pickimage') di.show_mode_indicator(True) self.pickimage = di bd = di.get_bindings() bd.enable_pan(True) bd.enable_zoom(True) bd.enable_cuts(True) bd.enable_cmap(True) di.set_desired_size(width, height) p_canvas = di.get_canvas() tag = p_canvas.add(self.dc.Point(width / 2, height / 2, 5, linewidth=1, color='red')) self.pickcenter = p_canvas.get_object_by_tag(tag) iw = Viewers.GingaViewerWidget(viewer=di) iw.resize(width, height) nb.add_widget(iw, title="Image") # Set up "Contour" tab viewer if contour.have_skimage: # Contour plot, Ginga-style ci = Viewers.CanvasView(logger=self.logger) width, height = 400, 300 ci.set_desired_size(width, height) ci.enable_autozoom('override') ci.enable_autocuts('override') ci.set_zoom_algorithm('rate') ci.set_zoomrate(1.6) ci.set_autocut_params('histogram') t_ = ci.get_settings() if self.contour_interpolation not in self.contour_interp_methods: self.contour_interpolation = 'basic' t_.set(interpolation=self.contour_interpolation) ci.set_bg(0.4, 0.4, 0.4) # for debugging ci.set_name('contour_image') self.contour_canvas = self.dc.DrawingCanvas() ci.get_canvas().add(self.contour_canvas) if cmap.has_cmap('RdYlGn_r'): ci.set_color_map('RdYlGn_r') else: ci.set_color_map('pastel') ci.show_color_bar(True) self.contour_image = ci bd = ci.get_bindings() bd.enable_pan(True) bd.enable_zoom(True) bd.enable_cuts(True) bd.enable_cmap(True) ci.set_desired_size(width, height) ci.show_mode_indicator(True) ciw = Viewers.GingaViewerWidget(viewer=ci) ciw.resize(width, height) nb.add_widget(ciw, title="Contour") if have_mpl: if not contour.have_skimage: # Contour plot self.contour_plot = plots.ContourPlot( logger=self.logger, width=width, height=height) self.contour_plot.add_axis(facecolor='black') pw = Plot.PlotWidget(self.contour_plot) pw.resize(width, height) self.contour_plot.enable(pan=True, zoom=True) self.contour_interp_methods = ('bilinear', 'nearest', 'bicubic') if self.contour_interpolation not in self.contour_interp_methods: self.contour_interpolation = 'nearest' self.contour_plot.interpolation = self.contour_interpolation nb.add_widget(pw, title="Contour") # FWHM gaussians plot self.fwhm_plot = plots.FWHMPlot(logger=self.logger, width=width, height=height) self.fwhm_plot.add_axis(facecolor='white') pw = Plot.PlotWidget(self.fwhm_plot) pw.resize(width, height) nb.add_widget(pw, title="FWHM") # Radial profile plot self.radial_plot = plots.RadialPlot(logger=self.logger, width=width, height=height) self.radial_plot.add_axis(facecolor='white') pw = Plot.PlotWidget(self.radial_plot) pw.resize(width, height) nb.add_widget(pw, title="Radial") # EE profile plot self.ee_plot = plots.EEPlot(logger=self.logger, width=width, height=height) self.ee_plot.add_axis(facecolor='white') pw = Plot.PlotWidget(self.ee_plot) pw.resize(width, height) nb.add_widget(pw, title="EE") fr = Widgets.Frame(self._textlabel) nb = Widgets.TabWidget(tabpos='bottom') self.w.nb2 = nb # Build report panel captions = (('Zoom:', 'label', 'Zoom', 'llabel'), ('Object_X', 'label', 'Object_X', 'llabel', 'Object_Y', 'label', 'Object_Y', 'llabel'), ('RA:', 'label', 'RA', 'llabel', 'DEC:', 'label', 'DEC', 'llabel'), ('Equinox:', 'label', 'Equinox', 'llabel', 'Background:', 'label', 'Background', 'llabel'), ('Sky Level:', 'label', 'Sky Level', 'llabel', 'Brightness:', 'label', 'Brightness', 'llabel'), ('FWHM X:', 'label', 'FWHM X', 'llabel', 'FWHM Y:', 'label', 'FWHM Y', 'llabel'), ('FWHM:', 'label', 'FWHM', 'llabel', 'Star Size:', 'label', 'Star Size', 'llabel'), ('EE (circ):', 'label', 'Encircled energy', 'llabel', 'EE (sq):', 'label', 'Ensquared energy', 'llabel'), ('Sample Area:', 'label', 'Sample Area', 'llabel', 'Default Region', 'button', 'Pan to pick', 'button'), ('Quick Mode', 'checkbutton', 'From Peak', 'checkbutton', 'Center on pick', 'checkbutton'), ) w, b = Widgets.build_info(captions, orientation=orientation) self.w.update(b) b.zoom.set_text(self.fv.scale2text(di.get_scale())) self.wdetail = b b.encircled_energy.set_tooltip("Encircled energy") b.ensquared_energy.set_tooltip("Ensquared energy") b.default_region.add_callback('activated', lambda w: self.reset_region()) b.default_region.set_tooltip("Reset region size to default") b.pan_to_pick.add_callback('activated', lambda w: self.pan_to_pick_cb()) b.pan_to_pick.set_tooltip("Pan image to pick center") b.quick_mode.set_tooltip("Turn Quick Mode on or off.\n" "ON: Pick object manually ('From Peak' off)\n" "or simply evaluate first peak found\n" "in pick region ('From Peak' on).\n" "OFF: Compare all peaks against selection\n" "criteria (Settings) to avoid objects\n" "and/or find 'best' peak.") b.quick_mode.add_callback('activated', self.quick_mode_cb) b.quick_mode.set_state(self.quick_mode) b.from_peak.set_tooltip("In quick mode, calculate from any peak\n" "found (on), or simply calculate from the\n" "center of pick shape (off).") b.from_peak.add_callback('activated', self.from_peak_cb) b.from_peak.set_state(self.from_peak) ## b.drag_only.set_tooltip("In quick mode, require cursor press or follow cursor") ## b.drag_only.add_callback('activated', self.drag_only_cb) ## b.drag_only.set_state(self.drag_only) b.center_on_pick.add_callback('activated', self.center_on_pick_cb) b.center_on_pick.set_state(self.center_on_pick) b.center_on_pick.set_tooltip("When peak is found, center shape\n" "on peak.") vbox1 = Widgets.VBox() vbox1.add_widget(w, stretch=0) # spacer vbox1.add_widget(Widgets.Label(''), stretch=0) # Pick field evaluation status hbox = Widgets.HBox() hbox.set_spacing(4) hbox.set_border_width(4) label = Widgets.Label() #label.set_alignment(0.05, 0.5) self.w.eval_status = label hbox.add_widget(self.w.eval_status, stretch=0) hbox.add_widget(Widgets.Label(''), stretch=1) vbox1.add_widget(hbox, stretch=0) # Pick field evaluation progress bar and stop button hbox = Widgets.HBox() hbox.set_spacing(4) hbox.set_border_width(4) btn = Widgets.Button("Stop") btn.add_callback('activated', lambda w: self.eval_intr()) btn.set_enabled(False) self.w.btn_intr_eval = btn hbox.add_widget(btn, stretch=0) self.w.eval_pgs = Widgets.ProgressBar() hbox.add_widget(self.w.eval_pgs, stretch=1) vbox1.add_widget(hbox, stretch=0) nb.add_widget(vbox1, title="Readout") # Build settings panel captions = (('Show Candidates', 'checkbutton'), ("Draw type:", 'label', 'xlbl_drawtype', 'label', "Draw type", 'combobox'), ('Radius:', 'label', 'xlbl_radius', 'label', 'Radius', 'spinbutton'), ('Threshold:', 'label', 'xlbl_threshold', 'label', 'Threshold', 'entry'), ('Min FWHM:', 'label', 'xlbl_min_fwhm', 'label', 'Min FWHM', 'spinfloat'), ('Max FWHM:', 'label', 'xlbl_max_fwhm', 'label', 'Max FWHM', 'spinfloat'), ('Ellipticity:', 'label', 'xlbl_ellipticity', 'label', 'Ellipticity', 'entry'), ('Edge:', 'label', 'xlbl_edge', 'label', 'Edge', 'entry'), ('Max side:', 'label', 'xlbl_max_side', 'label', 'Max side', 'spinbutton'), ('Coordinate Base:', 'label', 'xlbl_coordinate_base', 'label', 'Coordinate Base', 'entry'), ("Calc center:", 'label', 'xlbl_calccenter', 'label', "Calc center", 'combobox'), ("FWHM fitting:", 'label', 'xlbl_fwhmfitting', 'label', "FWHM fitting", 'combobox'), ('Contour Interpolation:', 'label', 'xlbl_cinterp', 'label', 'Contour Interpolation', 'combobox'), ('EE total radius:', 'label', 'xlbl_ee_total_radius', 'label', 'EE total radius', 'spinfloat'), ('EE sampling radius:', 'label', 'xlbl_ee_radius', 'label', 'EE sampling radius', 'spinfloat') ) w, b = Widgets.build_info(captions, orientation=orientation) self.w.update(b) b.radius.set_tooltip("Radius for peak detection") b.threshold.set_tooltip("Threshold for peak detection (blank=default)") b.min_fwhm.set_tooltip("Minimum FWHM for selection") b.max_fwhm.set_tooltip("Maximum FWHM for selection") b.ellipticity.set_tooltip("Minimum ellipticity for selection") b.edge.set_tooltip("Minimum edge distance for selection") b.show_candidates.set_tooltip("Show all peak candidates") b.max_side.set_tooltip("Maximum dimension to search for peaks") b.coordinate_base.set_tooltip("Base of pixel coordinate system") b.calc_center.set_tooltip("How to calculate the center of object") b.fwhm_fitting.set_tooltip("Function for fitting the FWHM") b.contour_interpolation.set_tooltip("Interpolation for use in contour plot") b.ee_total_radius.set_tooltip("Radius where EE fraction is 1") b.ee_sampling_radius.set_tooltip("Radius for EE sampling") def chg_pickshape(w, idx): pickshape = self.drawtypes[idx] self.set_drawtype(pickshape) return True combobox = b.draw_type for name in self.drawtypes: combobox.append_text(name) index = self.drawtypes.index(self.pickshape) combobox.set_index(index) combobox.add_callback('activated', chg_pickshape) b.xlbl_drawtype.set_text(self.pickshape) # radius control #b.radius.set_digits(2) #b.radius.set_numeric(True) b.radius.set_limits(5, 200, incr_value=1) def chg_radius(w, val): self.radius = int(val) self.w.xlbl_radius.set_text(str(self.radius)) return True b.xlbl_radius.set_text(str(self.radius)) b.radius.add_callback('value-changed', chg_radius) # EE total radius control b.ee_total_radius.set_limits(0.1, 200.0, incr_value=0.1) b.ee_total_radius.set_value(self.ee_total_radius) def chg_ee_total_radius(w, val): self.ee_total_radius = float(val) self.w.xlbl_ee_total_radius.set_text(str(self.ee_total_radius)) return True b.xlbl_ee_total_radius.set_text(str(self.ee_total_radius)) b.ee_total_radius.add_callback('value-changed', chg_ee_total_radius) # EE sampling radius control b.ee_sampling_radius.set_limits(0.1, 200.0, incr_value=0.1) b.ee_sampling_radius.set_value(self.ee_sampling_radius) def chg_ee_sampling_radius(w, val): self.ee_sampling_radius = float(val) self.w.xlbl_ee_radius.set_text(str(self.ee_sampling_radius)) return True b.xlbl_ee_radius.set_text(str(self.ee_sampling_radius)) b.ee_sampling_radius.add_callback('value-changed', chg_ee_sampling_radius) # threshold control def chg_threshold(w): threshold = None ths = w.get_text().strip() if len(ths) > 0: threshold = float(ths) self.threshold = threshold self.w.xlbl_threshold.set_text(str(self.threshold)) return True b.xlbl_threshold.set_text(str(self.threshold)) b.threshold.add_callback('activated', chg_threshold) # min fwhm #b.min_fwhm.set_digits(2) #b.min_fwhm.set_numeric(True) b.min_fwhm.set_limits(0.1, 200.0, incr_value=0.1) b.min_fwhm.set_value(self.min_fwhm) def chg_min(w, val): self.min_fwhm = float(val) self.w.xlbl_min_fwhm.set_text(str(self.min_fwhm)) return True b.xlbl_min_fwhm.set_text(str(self.min_fwhm)) b.min_fwhm.add_callback('value-changed', chg_min) # max fwhm #b.max_fwhm.set_digits(2) #b.max_fwhm.set_numeric(True) b.max_fwhm.set_limits(0.1, 200.0, incr_value=0.1) b.max_fwhm.set_value(self.max_fwhm) def chg_max(w, val): self.max_fwhm = float(val) self.w.xlbl_max_fwhm.set_text(str(self.max_fwhm)) return True b.xlbl_max_fwhm.set_text(str(self.max_fwhm)) b.max_fwhm.add_callback('value-changed', chg_max) # Ellipticity control def chg_ellipticity(w): minellipse = None val = w.get_text().strip() if len(val) > 0: minellipse = float(val) self.min_ellipse = minellipse self.w.xlbl_ellipticity.set_text(str(self.min_ellipse)) return True b.xlbl_ellipticity.set_text(str(self.min_ellipse)) b.ellipticity.add_callback('activated', chg_ellipticity) # Edge control def chg_edgew(w): edgew = None val = w.get_text().strip() if len(val) > 0: edgew = float(val) self.edgew = edgew self.w.xlbl_edge.set_text(str(self.edgew)) return True b.xlbl_edge.set_text(str(self.edgew)) b.edge.add_callback('activated', chg_edgew) #b.max_side.set_digits(0) #b.max_side.set_numeric(True) b.max_side.set_limits(5, 10000, incr_value=10) b.max_side.set_value(self.max_side) def chg_max_side(w, val): self.max_side = int(val) self.w.xlbl_max_side.set_text(str(self.max_side)) return True b.xlbl_max_side.set_text(str(self.max_side)) b.max_side.add_callback('value-changed', chg_max_side) combobox = b.contour_interpolation def chg_contour_interp(w, idx): self.contour_interpolation = self.contour_interp_methods[idx] self.w.xlbl_cinterp.set_text(self.contour_interpolation) if self.contour_image is not None: t_ = self.contour_image.get_settings() t_.set(interpolation=self.contour_interpolation) elif self.contour_plot is not None: self.contour_plot.interpolation = self.contour_interpolation return True for name in self.contour_interp_methods: combobox.append_text(name) index = self.contour_interp_methods.index(self.contour_interpolation) combobox.set_index(index) self.w.xlbl_cinterp.set_text(self.contour_interpolation) if self.contour_plot is not None: self.contour_plot.interpolation = self.contour_interpolation combobox.add_callback('activated', chg_contour_interp) b.show_candidates.set_state(self.show_candidates) b.show_candidates.add_callback('activated', self.show_candidates_cb) self.w.xlbl_coordinate_base.set_text(str(self.pixel_coords_offset)) b.coordinate_base.set_text(str(self.pixel_coords_offset)) b.coordinate_base.add_callback('activated', self.coordinate_base_cb) def chg_calccenter(w, idx): self.center_alg = self.center_algs[idx] self.w.xlbl_calccenter.set_text(self.center_alg) return True combobox = b.calc_center for name in self.center_algs: combobox.append_text(name) index = self.center_algs.index(self.center_alg) combobox.set_index(index) combobox.add_callback('activated', chg_calccenter) b.xlbl_calccenter.set_text(self.center_alg) def chg_fwhmfitting(w, idx): self.fwhm_alg = self.fwhm_algs[idx] self.w.xlbl_fwhmfitting.set_text(self.fwhm_alg) return True combobox = b.fwhm_fitting for name in self.fwhm_algs: combobox.append_text(name) index = self.fwhm_algs.index(self.fwhm_alg) combobox.set_index(index) combobox.add_callback('activated', chg_fwhmfitting) b.xlbl_fwhmfitting.set_text(self.fwhm_alg) sw2 = Widgets.ScrollArea() sw2.set_widget(w) vbox3 = Widgets.VBox() vbox3.add_widget(sw2, stretch=1) btns = Widgets.HBox() btn = Widgets.Button('Redo Pick') btn.add_callback('activated', lambda w: self.redo_manual()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox3.add_widget(btns, stretch=0) nb.add_widget(vbox3, title="Settings") # Build controls panel vbox3 = Widgets.VBox() captions = ( ('Bg cut', 'button', 'Delta bg:', 'label', 'xlbl_delta_bg', 'label', 'Delta bg', 'entry'), ('Sky cut', 'button', 'Delta sky:', 'label', 'xlbl_delta_sky', 'label', 'Delta sky', 'entry'), ('Bright cut', 'button', 'Delta bright:', 'label', 'xlbl_delta_bright', 'label', 'Delta bright', 'entry'), ) w, b = Widgets.build_info(captions, orientation=orientation) self.w.update(b) b.bg_cut.set_tooltip("Set image low cut to Background Level") b.delta_bg.set_tooltip("Delta to apply to this cut") b.sky_cut.set_tooltip("Set image low cut to Sky Level") b.delta_sky.set_tooltip("Delta to apply to this cut") b.bright_cut.set_tooltip("Set image high cut to Sky Level+Brightness") b.delta_bright.set_tooltip("Delta to apply to this cut") b.bg_cut.set_enabled(False) self.w.btn_bg_cut = b.bg_cut self.w.btn_bg_cut.add_callback('activated', lambda w: self.bg_cut()) self.w.bg_cut_delta = b.delta_bg b.xlbl_delta_bg.set_text(str(self.delta_bg)) b.delta_bg.set_text(str(self.delta_bg)) def chg_delta_bg(w): delta_bg = 0.0 val = w.get_text().strip() if len(val) > 0: delta_bg = float(val) self.delta_bg = delta_bg self.w.xlbl_delta_bg.set_text(str(self.delta_bg)) return True b.delta_bg.add_callback('activated', chg_delta_bg) b.sky_cut.set_enabled(False) self.w.btn_sky_cut = b.sky_cut self.w.btn_sky_cut.add_callback('activated', lambda w: self.sky_cut()) self.w.sky_cut_delta = b.delta_sky b.xlbl_delta_sky.set_text(str(self.delta_sky)) b.delta_sky.set_text(str(self.delta_sky)) def chg_delta_sky(w): delta_sky = 0.0 val = w.get_text().strip() if len(val) > 0: delta_sky = float(val) self.delta_sky = delta_sky self.w.xlbl_delta_sky.set_text(str(self.delta_sky)) return True b.delta_sky.add_callback('activated', chg_delta_sky) b.bright_cut.set_enabled(False) self.w.btn_bright_cut = b.bright_cut self.w.btn_bright_cut.add_callback('activated', lambda w: self.bright_cut()) self.w.bright_cut_delta = b.delta_bright b.xlbl_delta_bright.set_text(str(self.delta_bright)) b.delta_bright.set_text(str(self.delta_bright)) def chg_delta_bright(w): delta_bright = 0.0 val = w.get_text().strip() if len(val) > 0: delta_bright = float(val) self.delta_bright = delta_bright self.w.xlbl_delta_bright.set_text(str(self.delta_bright)) return True b.delta_bright.add_callback('activated', chg_delta_bright) vbox3.add_widget(w, stretch=0) vbox3.add_widget(Widgets.Label(''), stretch=1) nb.add_widget(vbox3, title="Controls") vbox3 = Widgets.VBox() tv = Widgets.TreeView(sortable=True, use_alt_row_color=True) self.rpt_tbl = tv vbox3.add_widget(tv, stretch=1) tv.setup_table(self.rpt_columns, 1, 'time_local') btns = Widgets.HBox() btns.set_spacing(4) btn = Widgets.Button("Add Pick") btn.add_callback('activated', lambda w: self.add_pick_cb()) btns.add_widget(btn) btn = Widgets.CheckBox("Record Picks automatically") btn.set_state(self.do_record) btn.add_callback('activated', self.record_cb) btns.add_widget(btn) btn = Widgets.Button("Clear Log") btn.add_callback('activated', lambda w: self.clear_pick_log_cb()) btns.add_widget(btn) btns.add_widget(Widgets.Label(''), stretch=1) vbox3.add_widget(btns, stretch=0) btns = Widgets.HBox() btns.set_spacing(4) btn = Widgets.Button("Save table") btn.add_callback('activated', self.write_pick_log_cb) btns.add_widget(btn) btns.add_widget(Widgets.Label("File:")) ent = Widgets.TextEntry() report_log = self.settings.get('report_log_path', None) if report_log is None: report_log = "pick_log.fits" ent.set_text(report_log) ent.set_tooltip('File type determined by extension') self.w.report_log = ent btns.add_widget(ent, stretch=1) vbox3.add_widget(btns, stretch=0) nb.add_widget(vbox3, title="Report") fr.set_widget(nb) box.add_widget(fr, stretch=5) paned.add_widget(sw) paned.set_sizes(self._split_sizes) vtop.add_widget(paned, stretch=5) mode = self.canvas.get_draw_mode() hbox = Widgets.HBox() btn1 = Widgets.RadioButton("Move") btn1.set_state(mode == 'move') btn1.add_callback( 'activated', lambda w, val: self.set_mode_cb('move', val)) btn1.set_tooltip("Choose this to position pick") self.w.btn_move = btn1 hbox.add_widget(btn1) btn2 = Widgets.RadioButton("Draw", group=btn1) btn2.set_state(mode == 'draw') btn2.add_callback( 'activated', lambda w, val: self.set_mode_cb('draw', val)) btn2.set_tooltip("Choose this to draw a replacement pick") self.w.btn_draw = btn2 hbox.add_widget(btn2) btn3 = Widgets.RadioButton("Edit", group=btn1) btn3.set_state(mode == 'edit') btn3.add_callback( 'activated', lambda w, val: self.set_mode_cb('edit', val)) btn3.set_tooltip("Choose this to edit or move a pick") self.w.btn_edit = btn3 hbox.add_widget(btn3) hbox.add_widget(Widgets.Label(''), stretch=1) vtop.add_widget(hbox, stretch=0) btns = Widgets.HBox() btns.set_spacing(4) btn = Widgets.Button("Close") btn.add_callback('activated', lambda w: self.close()) btns.add_widget(btn) btn = Widgets.Button("Help") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vtop.add_widget(btns, stretch=0) container.add_widget(vtop, stretch=5) self.gui_up = True def record_cb(self, w, tf): self.do_record = tf return True def update_status(self, text): self.fv.gui_do(self.w.eval_status.set_text, text) def init_progress(self): self.w.btn_intr_eval.set_enabled(True) self.w.eval_pgs.set_value(0.0) def update_progress(self, pct): self.w.eval_pgs.set_value(pct) def show_candidates_cb(self, w, state): self.show_candidates = state if not self.show_candidates: # Delete previous peak marks objs = self.canvas.get_objects_by_tag_pfx('peak') self.canvas.delete_objects(objs) def coordinate_base_cb(self, w): self.pixel_coords_offset = float(w.get_text()) self.w.xlbl_coordinate_base.set_text(str(self.pixel_coords_offset)) def bump_serial(self): with self.lock: self.serialnum += 1 return self.serialnum def get_serial(self): with self.lock: return self.serialnum def plot_contours(self, image): # Make a contour plot ht, wd = self.pick_data.shape x, y = self.pick_x1 + wd // 2, self.pick_y1 + ht // 2 # If size of pick region is too small/large, recut out a subset # around the picked object coordinates for plotting contours recut = False if wd < self.contour_size_min or wd > self.contour_size_max: wd = max(self.contour_size_min, min(wd, self.contour_size_max)) recut = True if ht < self.contour_size_min or ht > self.contour_size_max: ht = max(self.contour_size_min, min(ht, self.contour_size_max)) recut = True if recut: radius = max(wd, ht) // 2 if self.pick_qs is not None: x, y = self.pick_qs.x, self.pick_qs.y data, x1, y1, x2, y2 = image.cutout_radius(x, y, radius) x, y = x - x1, y - y1 ht, wd = data.shape else: data = self.pick_data x, y = self.pickcenter.x, self.pickcenter.y try: if self.contour_image is not None: cv = self.contour_image with cv.suppress_redraw: cv.set_data(data) # copy orientation of main image, so that contour will # make sense. Don't do rotation, for now. flips = self.fitsimage.get_transforms() cv.transform(*flips) #rot_deg = self.fitsimage.get_rotation() #cv.rotate(rot_deg) cv.panset_xy(x, y) canvas = self.contour_canvas try: canvas.delete_object_by_tag('_$cntr', redraw=False) except KeyError: pass # calculate contour polygons contour_grps = contour.calc_contours(data, self.num_contours) # get compound polygons object c_obj = contour.create_contours_obj(canvas, contour_grps, colors=['black'], linewidth=2) canvas.add(c_obj, tag='_$cntr') elif self.contour_plot is not None: self.contour_plot.plot_contours_data( x, y, data, num_contours=self.num_contours) except Exception as e: self.logger.error("Error making contour plot: %s" % ( str(e))) def clear_contours(self): if self.contour_image is not None: self.contour_canvas.delete_all_objects() elif self.contour_plot is not None: self.contour_plot.clear() def plot_fwhm(self, qs, image): # Make a FWHM plot x, y = qs.x - self.pick_x1, qs.y - self.pick_y1 radius = qs.fwhm_radius try: self.fwhm_plot.plot_fwhm_data(x, y, radius, self.pick_data, iqcalc=self.iqcalc, fwhm_method=self.fwhm_alg) except Exception as e: self.logger.error("Error making fwhm plot: %s" % ( str(e))) def clear_fwhm(self): self.fwhm_plot.clear() def plot_radial(self, qs, image): # Make a radial plot x, y, radius = qs.x, qs.y, qs.fwhm_radius try: self.radial_plot.plot_radial(x, y, radius, image) except Exception as e: self.logger.error("Error making radial plot: %s" % ( str(e))) def clear_radial(self): self.radial_plot.clear() def plot_ee(self, qs): # Make a EE plot try: self.ee_plot.plot_ee( encircled_energy_function=qs.encircled_energy_fn, ensquared_energy_function=qs.ensquared_energy_fn, sampling_radius=self.ee_sampling_radius, total_radius=self.ee_total_radius) except Exception as e: self.logger.error("Error making EE plot: %s" % (str(e))) def clear_ee(self): self.ee_plot.clear() def close(self): self.fv.stop_local_plugin(self.chname, str(self)) return True def start(self): # insert layer if it is not already p_canvas = self.fitsimage.get_canvas() try: p_canvas.get_object_by_tag(self.layertag) except KeyError: # Add canvas layer p_canvas.add(self.canvas, tag=self.layertag) self.resume() def pause(self): self.canvas.ui_set_active(False) def resume(self): # turn off any mode user may be in self.modes_off() self.canvas.ui_set_active(True, viewer=self.fitsimage) self.fv.show_status("Draw a shape with the right mouse button") def stop(self): self.gui_up = False self._split_sizes = self.w.splitter.get_sizes() # Delete previous peak marks objs = self.canvas.get_objects_by_tag_pfx('peak') self.canvas.delete_objects(objs) # deactivate the canvas self.canvas.ui_set_active(False) p_canvas = self.fitsimage.get_canvas() try: p_canvas.delete_object_by_tag(self.layertag) except Exception: pass self.fv.show_status("") def redo_manual(self): if self.quick_mode: self.redo_quick() self.calc_quick() else: serialnum = self.bump_serial() self.ev_intr.set() self._redo(serialnum) def redo(self): serialnum = self.bump_serial() self._redo(serialnum) def _redo(self, serialnum): if self.pick_obj is None: return pickobj = self.pick_obj if pickobj.kind != 'compound': return True shape = pickobj.objects[0] point = pickobj.objects[1] text = pickobj.objects[2] # reposition other elements to match ctr_x, ctr_y = shape.get_center_pt() point.x, point.y = ctr_x, ctr_y x1, y1, x2, y2 = shape.get_llur() text.x, text.y = x1, y2 try: image = self.fitsimage.get_vip() # sanity check on size of region width, height = abs(x2 - x1), abs(y2 - y1) if (width > self.max_side) or (height > self.max_side): errmsg = "Image area (%dx%d) too large!" % ( width, height) self.fv.show_error(errmsg) raise Exception(errmsg) # Extract image in pick window self.logger.debug("bbox %f,%f %f,%f" % (x1, y1, x2, y2)) x1, y1, x2, y2, data = self.cutdetail(image, shape) self.logger.debug("cut box %d,%d %d,%d" % (x1, y1, x2, y2)) # calculate center of pick image ht, wd = data.shape[:2] xc = wd // 2 yc = ht // 2 self.pick_x1, self.pick_y1 = x1, y1 self.pick_data = data point.color = 'red' text.text = '{0}: calc'.format(self._textlabel) self.pickcenter.x = xc self.pickcenter.y = yc self.pickcenter.color = 'red' # Offload this task to another thread so that GUI remains # responsive self.fv.nongui_do(self.search, serialnum, data, x1, y1, wd, ht, pickobj) except Exception as e: self.logger.error("Error calculating quality metrics: %s" % ( str(e))) return True def search(self, serialnum, data, x1, y1, wd, ht, pickobj): with self.lock2: if serialnum != self.get_serial(): return self.pgs_cnt = 0 self.ev_intr.clear() self.fv.gui_call(self.init_progress) msg, results, qs = None, None, None try: self.update_status("Finding bright peaks...") # Find bright peaks in the cutout peaks = self.iqcalc.find_bright_peaks(data, threshold=self.threshold, radius=self.radius) num_peaks = len(peaks) if num_peaks == 0: raise Exception("Cannot find bright peaks") def cb_fn(obj): self.pgs_cnt += 1 pct = float(self.pgs_cnt) / num_peaks self.fv.gui_do(self.update_progress, pct) # Evaluate those peaks self.update_status("Evaluating %d bright peaks..." % ( num_peaks)) objlist = self.iqcalc.evaluate_peaks( peaks, data, fwhm_radius=self.radius, cb_fn=cb_fn, ev_intr=self.ev_intr, fwhm_method=self.fwhm_alg, ee_total_radius=self.ee_total_radius) num_candidates = len(objlist) if num_candidates == 0: raise Exception( "Error evaluating bright peaks: no candidates found") self.update_status("Selecting from %d candidates..." % ( num_candidates)) height, width = data.shape results = self.iqcalc.objlist_select(objlist, width, height, minfwhm=self.min_fwhm, maxfwhm=self.max_fwhm, minelipse=self.min_ellipse, edgew=self.edgew) if len(results) == 0: raise Exception("No object matches selection criteria") # Add back in offsets into image to get correct values with # respect to the entire image for qs in results: qs.x += x1 qs.y += y1 if qs.objx is not None: qs.objx += x1 qs.objy += y1 if qs.oid_x is not None: qs.oid_x += x1 qs.oid_y += y1 # pick main result qs = results[0] except Exception as e: msg = str(e) self.update_status(msg) self.fv.gui_do(self.update_pick, serialnum, results, qs, x1, y1, wd, ht, data, pickobj, msg) def _make_report(self, vip_img, qs): d = Bunch.Bunch() try: x, y = qs.objx, qs.objy if (qs.oid_x is not None) and (self.center_alg == 'centroid'): # user wants RA/DEC calculated by centroid instead of fwhm x, y = qs.oid_x, qs.oid_y image, pt2 = vip_img.get_image_at_pt((x, y)) equinox = float(image.get_keyword('EQUINOX', 2000.0)) try: ra_deg, dec_deg = image.pixtoradec(x, y, coords='data') ra_txt, dec_txt = wcs.deg2fmt(ra_deg, dec_deg, 'str') except Exception as e: self.logger.warning( "Couldn't calculate sky coordinates: %s" % (str(e))) ra_deg, dec_deg = 0.0, 0.0 ra_txt = dec_txt = 'BAD WCS' # Calculate star size from pixel pitch try: header = image.get_header() ((xrot, yrot), (cdelt1, cdelt2)) = wcs.get_xy_rotation_and_scale(header) starsize = self.iqcalc.starsize(qs.fwhm_x, cdelt1, qs.fwhm_y, cdelt2) except Exception as e: self.logger.warning( "Couldn't calculate star size: %s" % (str(e))) starsize = 0.0 rpt_x = x + self.pixel_coords_offset rpt_y = y + self.pixel_coords_offset # EE at sampling radius try: ee_circ = qs.encircled_energy_fn(self.ee_sampling_radius) ee_sq = qs.ensquared_energy_fn(self.ee_sampling_radius) except Exception as e: self.logger.warning("Couldn't calculate EE at %.2f: %s" % (self.ee_sampling_radius, str(e))) ee_circ = 0 ee_sq = 0 # make a report in the form of a dictionary d.setvals(x=rpt_x, y=rpt_y, ra_deg=ra_deg, dec_deg=dec_deg, ra_txt=ra_txt, dec_txt=dec_txt, equinox=equinox, fwhm=qs.fwhm, fwhm_x=qs.fwhm_x, fwhm_y=qs.fwhm_y, ellipse=qs.elipse, background=qs.background, skylevel=qs.skylevel, brightness=qs.brightness, encircled_energy=ee_circ, ensquared_energy=ee_sq, ee_sampling_radius=self.ee_sampling_radius, starsize=starsize, time_local=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), time_ut=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()), ) except Exception as e: self.logger.error("Error making report: %s" % (str(e))) return d def update_pick(self, serialnum, objlist, qs, x1, y1, wd, ht, data, pickobj, msg): try: # set the pick image to have the same cut levels and transforms self.fitsimage.copy_attributes(self.pickimage, self.copy_attrs) self.pickimage.set_data(data) # Delete previous peak marks objs = self.canvas.get_objects_by_tag_pfx('peak') self.canvas.delete_objects(objs) vip_img = self.fitsimage.get_vip() shape_obj = pickobj.objects[0] point = pickobj.objects[1] text = pickobj.objects[2] text.text = self._textlabel _x1, _y1, x2, y2 = shape_obj.get_llur() text.x, text.y = x1, y2 if msg is not None: raise Exception(msg) # Mark new peaks, if desired if self.show_candidates: reports = [self._make_report(vip_img, x) for x in objlist] for obj in objlist: self.canvas.add(self.dc.Point( obj.objx, obj.objy, 5, linewidth=1, color=self.candidate_color), tagpfx='peak') else: reports = [self._make_report(vip_img, qs)] # Calculate X/Y of center of star obj_x = qs.objx obj_y = qs.objy fwhm = qs.fwhm fwhm_x, fwhm_y = qs.fwhm_x, qs.fwhm_y point.x, point.y = obj_x, obj_y text.color = 'cyan' if self.center_on_pick: shape_obj.move_to_pt((obj_x, obj_y)) # reposition label above moved shape _x1, _y1, x2, y2 = shape_obj.get_llur() text.x, text.y = _x1, y2 # Make report self.last_rpt = reports if self.do_record: self.add_reports(reports) self.last_rpt = [] d = reports[0] self.wdetail.sample_area.set_text('%dx%d' % (wd, ht)) self.wdetail.fwhm_x.set_text('%.3f' % fwhm_x) self.wdetail.fwhm_y.set_text('%.3f' % fwhm_y) self.wdetail.fwhm.set_text('%.3f' % fwhm) self.wdetail.object_x.set_text('%.3f' % d.x) self.wdetail.object_y.set_text('%.3f' % d.y) self.wdetail.sky_level.set_text('%.3f' % qs.skylevel) self.wdetail.background.set_text('%.3f' % qs.background) self.wdetail.brightness.set_text('%.3f' % qs.brightness) self.wdetail.encircled_energy.set_text('%.3f' % d.encircled_energy) self.wdetail.ensquared_energy.set_text('%.3f' % d.ensquared_energy) self.wdetail.ra.set_text(d.ra_txt) self.wdetail.dec.set_text(d.dec_txt) self.wdetail.equinox.set_text(str(d.equinox)) self.wdetail.star_size.set_text('%.3f' % d.starsize) self.w.btn_bg_cut.set_enabled(True) self.w.btn_sky_cut.set_enabled(True) self.w.btn_bright_cut.set_enabled(True) # Mark center of object on pick image i1 = obj_x - x1 j1 = obj_y - y1 self.pickcenter.x = i1 self.pickcenter.y = j1 self.pickcenter.color = 'cyan' self.pick_qs = qs self.pickimage.panset_xy(i1, j1) # Mark object center on image point.color = 'cyan' shape_obj.linestyle = 'solid' shape_obj.color = self.pickcolor self.update_status("Done") self.plot_panx = float(i1) / wd self.plot_pany = float(j1) / ht if self.have_mpl: self.plot_contours(vip_img) self.plot_fwhm(qs, vip_img) self.plot_radial(qs, vip_img) self.plot_ee(qs) except Exception as e: errmsg = "Error calculating quality metrics: %s" % ( str(e)) self.logger.error(errmsg) self.fv.show_error(errmsg, raisetab=False) try: (type, value, tb) = sys.exc_info() tb_str = "\n".join(traceback.format_tb(tb)) except Exception as e: tb_str = "Traceback information unavailable." self.logger.error(tb_str) #self.update_status("Error") for key in ('sky_level', 'background', 'brightness', 'star_size', 'fwhm_x', 'fwhm_y', 'ra', 'dec', 'object_x', 'object_y', 'encircled_energy', 'ensquared_energy'): self.wdetail[key].set_text('') self.wdetail.fwhm.set_text('Failed') self.w.btn_bg_cut.set_enabled(False) self.w.btn_sky_cut.set_enabled(False) self.w.btn_bright_cut.set_enabled(False) self.pick_qs = None text.color = 'red' shape_obj.linestyle = 'dash' self.pickimage.center_image() self.plot_panx = self.plot_pany = 0.5 if self.have_mpl: self.plot_contours(vip_img) # TODO: could calc background based on numpy calc self.clear_fwhm() self.clear_radial() self.clear_ee() self.w.btn_intr_eval.set_enabled(False) self.pickimage.redraw(whence=3) self.canvas.redraw(whence=3) self.fv.show_status("Click left mouse button to reposition pick") return True def eval_intr(self): self.ev_intr.set() def redo_quick(self): vip_img = self.fitsimage.get_vip() obj = self.pick_obj if obj is None: return shape = obj.objects[0] x1, y1, x2, y2, data = self.cutdetail(vip_img, shape) self.pick_x1, self.pick_y1 = x1, y1 self.pick_data = data def calc_quick(self): if self.pick_data is None: return # examine cut area data, x1, y1 = self.pick_data, self.pick_x1, self.pick_y1 ht, wd = data.shape[:2] xc, yc = wd // 2, ht // 2 radius = min(xc, yc) peaks = [(xc, yc)] with_peak = self.w.from_peak.get_state() if with_peak: # find the peak in the area, if possible, and calc from that try: peaks = self.iqcalc.find_bright_peaks(data, threshold=self.threshold, radius=radius) except Exception as e: self.logger.debug("no peaks found in data--using center") if len(peaks) > 0: xc, yc = peaks[0] self.pickcenter.x = xc self.pickcenter.y = yc self.pickcenter.color = 'red' msg = qs = None try: radius = int(round(radius)) objlist = self.iqcalc.evaluate_peaks(peaks, data, fwhm_radius=radius, fwhm_method=self.fwhm_alg) num_candidates = len(objlist) if num_candidates == 0: raise Exception("Error calculating image quality") # Add back in offsets into image to get correct values with # respect to the entire image qs = objlist[0] qs.x += x1 qs.y += y1 if qs.objx is not None: qs.objx += x1 qs.objy += y1 if qs.oid_x is not None: qs.oid_x += x1 qs.oid_y += y1 except Exception as e: msg = str(e) self.update_status(msg) self.fv.gui_do(self.update_pick, 0, objlist, qs, x1, y1, wd, ht, data, self.pick_obj, msg) def draw_cb(self, canvas, tag): obj = canvas.get_object_by_tag(tag) canvas.delete_object_by_tag(tag) if obj.kind not in self.drawtypes: return True self.create_pick_box(obj) self.redo_manual() def edit_cb(self, canvas, obj): if obj.kind not in self.drawtypes: return True if self.pick_obj is not None and self.pick_obj.has_object(obj): self.redo_manual() def reset_region(self): self.dx = region_default_width self.dy = region_default_height self.set_drawtype('box') obj = self.pick_obj if obj.kind != 'compound': return shape = obj.objects[0] # determine center of shape data_x, data_y = shape.get_center_pt() rd_x, rd_y = self.dx // 2, self.dy // 2 x1, y1 = data_x - rd_x, data_y - rd_y x2, y2 = data_x + rd_x, data_y + rd_y # replace shape Box = self.dc.Box tag = self.canvas.add(Box(data_x, data_y, self.dx // 2, self.dy // 2, color=self.pickcolor)) self.draw_cb(self.canvas, tag) def create_pick_box(self, obj): pick_obj = self.pick_obj if pick_obj is not None and self.canvas.has_object(pick_obj): self.canvas.delete_object(pick_obj) # determine center of object x1, y1, x2, y2 = obj.get_llur() x, y = obj.get_center_pt() obj.color = self.pickcolor args = [obj, self.dc.Point(x, y, 10, color='red'), self.dc.Text(x1, y2, '{0}: calc'.format(self._textlabel), color=self.pickcolor) ] self.pick_obj = self.dc.CompoundObject(*args) self.canvas.add(self.pick_obj) def pan_to_pick_cb(self): if not self.pick_qs: self.fv.show_status("Please pick an object to set the sky level!") return pan_x, pan_y = self.pick_qs.objx, self.pick_qs.objy # TODO: convert to WCS coords based on user preference self.fitsimage.set_pan(pan_x, pan_y, coord='data') return True def bg_cut(self): if not self.pick_qs: self.fv.show_status("Please pick an object to set the bg level!") return loval = self.pick_qs.background oldlo, hival = self.fitsimage.get_cut_levels() try: loval += self.delta_bg self.fitsimage.cut_levels(loval, hival) except Exception as e: self.fv.show_status("No valid bg level: '%s'" % (loval)) def sky_cut(self): if not self.pick_qs: self.fv.show_status("Please pick an object to set the sky level!") return loval = self.pick_qs.skylevel oldlo, hival = self.fitsimage.get_cut_levels() try: loval += self.delta_sky self.fitsimage.cut_levels(loval, hival) except Exception as e: self.fv.show_status("No valid sky level: '%s'" % (loval)) def bright_cut(self): if not self.pick_qs: self.fv.show_status("Please pick an object to set the brightness!") return skyval = self.pick_qs.skylevel hival = self.pick_qs.brightness loval, oldhi = self.fitsimage.get_cut_levels() try: # brightness is measured ABOVE sky level hival = skyval + hival + self.delta_bright self.fitsimage.cut_levels(loval, hival) except Exception as e: self.fv.show_status("No valid brightness level: '%s'" % (hival)) def zoomset(self, setting, zoomlevel, fitsimage): scalefactor = fitsimage.get_scale() self.logger.debug("scalefactor = %.2f" % (scalefactor)) text = self.fv.scale2text(scalefactor) self.wdetail.zoom.set_text(text) def detailxy(self, canvas, event, data_x, data_y): """Motion event in the pick fits window. Show the pointing information under the cursor. """ chviewer = self.fv.getfocus_viewer() # Don't update global information if our chviewer isn't focused if chviewer != self.fitsimage: return True # Add offsets from cutout data_x = data_x + self.pick_x1 data_y = data_y + self.pick_y1 return self.fv.showxy(chviewer, data_x, data_y) def cutdetail(self, image, shape_obj): view, mask = image.get_shape_view(shape_obj) data = image._slice(view) y1, y2 = view[0].start, view[0].stop x1, x2 = view[1].start, view[1].stop # mask non-containing members mdata = np.ma.array(data, mask=np.logical_not(mask)) return (x1, y1, x2, y2, mdata) def pan_plot(self, xdelta, ydelta): x1, x2 = self.w.ax.get_xlim() y1, y2 = self.w.ax.get_ylim() self.w.ax.set_xlim(x1 + xdelta, x2 + xdelta) self.w.ax.set_ylim(y1 + ydelta, y2 + ydelta) self.w.canvas.draw() def write_pick_log(self, filepath): if len(self.rpt_dict) == 0: return # Save the table as a binary table HDU from astropy.table import Table try: self.logger.debug("Writing modified pick log") tbl = Table(rows=list(self.rpt_dict.values())) tbl.meta['comments'] = ["Written by ginga Pick plugin"] if filepath.lower().endswith('.txt'): fmt = 'ascii.commented_header' else: fmt = None tbl.write(filepath, format=fmt, overwrite=True) self.rpt_wrt_time = time.time() except Exception as e: self.logger.error("Error writing to pick log: %s" % (str(e))) def write_pick_log_cb(self, w): path = self.w.report_log.get_text().strip() self.write_pick_log(path) def add_reports(self, reports): for rpt in reports: self.rpt_cnt += 1 # Hack to insure that we get the columns in the desired order d = OrderedDict([(key, rpt[key]) for col, key in self.rpt_columns]) self.rpt_dict[self.rpt_cnt] = d self.rpt_mod_time = time.time() self.rpt_tbl.set_tree(self.rpt_dict) def add_pick_cb(self): if len(self.last_rpt) > 0: self.add_reports(self.last_rpt) self.last_rpt = [] def clear_pick_log_cb(self): self.rpt_dict = OrderedDict({}) self.rpt_tbl.set_tree(self.rpt_dict) def set_drawtype(self, shapename): if shapename not in self.drawtypes: raise ValueError("shape must be one of %s not %s" % ( str(self.drawtypes), shapename)) self.pickshape = shapename self.w.xlbl_drawtype.set_text(self.pickshape) self.canvas.set_drawtype(self.pickshape, color='cyan', linestyle='dash') def edit_select_pick(self): obj = self.pick_obj if obj is not None and self.canvas.has_object(obj): if obj.kind != 'compound': return True # drill down to reference shape bbox = obj.objects[0] self.canvas.edit_select(bbox) self.canvas.update_canvas() return self.canvas.clear_selected() self.canvas.update_canvas() def btn_down(self, canvas, event, data_x, data_y, viewer): if self.pick_obj is not None: if not canvas.has_object(self.pick_obj): self.canvas.add(self.pick_obj) obj = self.pick_obj shape = obj.objects[0] shape.color = 'cyan' shape.linestyle = 'dash' point = obj.objects[1] point.color = 'red' shape.move_to(data_x, data_y) self.canvas.update_canvas() if self.quick_mode: self.redo_quick() else: # No object yet? Add a default one. self.set_drawtype('box') rd_x, rd_y = self.dx // 2, self.dy // 2 x1, y1 = data_x - rd_x, data_y - rd_y x2, y2 = data_x + rd_x, data_y + rd_y Box = self.canvas.get_draw_class('box') tag = self.canvas.add(Box(data_x, data_y, rd_x, rd_y, color=self.pickcolor)) self.draw_cb(self.canvas, tag) return True def btn_drag(self, canvas, event, data_x, data_y, viewer): if self.pick_obj is not None: obj = self.pick_obj if obj.kind != 'compound': return False shape = obj.objects[0] shape.move_to(data_x, data_y) self.canvas.update_canvas() if self.quick_mode: self.redo_quick() return True return False def btn_up(self, canvas, event, data_x, data_y, viewer): if self.pick_obj is not None: obj = self.pick_obj if obj.kind != 'compound': return False shape = obj.objects[0] shape.move_to(data_x, data_y) self.canvas.update_canvas() self.redo_manual() return True def set_mode_cb(self, mode, tf): if tf: self.canvas.set_draw_mode(mode) if mode == 'edit': self.edit_select_pick() return True def quick_mode_cb(self, w, tf): self.quick_mode = tf return True def from_peak_cb(self, w, tf): self.from_peak = tf return True def center_on_pick_cb(self, w, tf): self.center_on_pick = tf return True def drag_only_cb(self, w, tf): self.drag_only = tf return True def __str__(self): return 'pick' # Append module docstring with config doc for auto insert by Sphinx. from ginga.util.toolbox import generate_cfg_example # noqa if __doc__ is not None: __doc__ += generate_cfg_example('plugin_Pick', package='ginga') # END
naojsoft/ginga
ginga/rv/plugins/Pick.py
Python
bsd-3-clause
77,921
[ "Gaussian" ]
445ca1b21066094a321a330942dfe0a07ac0f6263dac3a867edac54ed20090ea
# coding: utf-8 """ This module provides objects describing the basic parameters of the pseudopotentials used in Abinit, and a parser to instantiate pseudopotential objects.. """ from __future__ import unicode_literals, division, print_function import sys import os import abc import collections import json import six import pprint import numpy as np from collections import OrderedDict from monty.string import list_strings, is_string from monty.itertools import iterator_from_slice from monty.io import FileLock from monty.collections import AttrDict, Namespace from monty.functools import lazy_property from monty.os.path import find_exts from monty.dev import deprecated from pymatgen.util.plotting_utils import add_fig_kwargs, get_ax_fig_plt from pymatgen.core.periodic_table import PeriodicTable, Element from pymatgen.serializers.json_coders import PMGSONable, pmg_serialize from .eos import EOS from monty.json import MontyDecoder import logging logger = logging.getLogger(__name__) __all__ = [ "Pseudo", "PseudoTable", ] __author__ = "Matteo Giantomassi" __version__ = "0.1" __maintainer__ = "Matteo Giantomassi" _PTABLE = PeriodicTable() # Tools and helper functions. def straceback(): """Returns a string with the traceback.""" import sys import traceback return "\n".join((traceback.format_exc(), str(sys.exc_info()[0]))) def _read_nlines(filename, nlines): """ Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. """ if nlines < 0: with open(filename, 'r') as fh: return fh.readlines() lines = [] with open(filename, 'r') as fh: for (lineno, line) in enumerate(fh): if lineno == nlines: break lines.append(line) return lines _l2str = { 0: "s", 1: "p", 2: "d", 3: "f", 4: "g", 5: "h", 6: "i", } _str2l = {v: k for k, v in _l2str.items()} def l2str(l): """Convert the angular momentum l (int) to string.""" try: return _l2str[l] except KeyError: return "Unknown angular momentum, received l = %s" % l def str2l(s): """Convert a string to the angular momentum l (int)""" return _str2l[s] class Pseudo(six.with_metaclass(abc.ABCMeta, PMGSONable, object)): """ Abstract base class defining the methods that must be implemented by the concrete pseudopotential classes. """ @classmethod def as_pseudo(cls, obj): """ Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path. """ return obj if isinstance(obj, cls) else cls.from_file(obj) @staticmethod def from_file(filename): """ Return a :class:`Pseudo` object from filename. Note: the parser knows the concrete class that should be instanciated """ return PseudoParser().parse(filename) #def __eq__(self, other): # if not isinstance(other, Pseudo): return False # return (self.__class__ == other.__class__ and # return (self.md5 == other.md5 and # self.text == other.text) #def __ne__(self, other): # return not self.__eq__(other) def __repr__(self): return "<%s at %s, name = %s>" % (self.__class__.__name__, id(self), self.basename) def __str__(self): """String representation.""" lines = [] app = lines.append app("<%s: %s>" % (self.__class__.__name__, self.basename)) app(" summary: " + self.summary.strip()) app(" number of valence electrons: %s" % self.Z_val) #FIXME: rewrite the treatment of xc, use XML specs as starting point #app(" XC correlation (ixc): %s" % self._pspxc) #FIXME app(" maximum angular momentum: %s" % l2str(self.l_max)) app(" angular momentum for local part: %s" % l2str(self.l_local)) if self.isnc: app(" radius for non-linear core correction: %s" % self.nlcc_radius) app("") if self.has_hints: hint_normal = self.hint_for_accuracy() if hint_normal is not None: app(" hint for normal accuracy: %s" % str(hint_normal)) else: app(" hints on cutoff-energy are not available") return "\n".join(lines) @abc.abstractproperty def summary(self): """String summarizing the most important properties.""" @property def filepath(self): return os.path.abspath(self.path) @property def basename(self): """File basename.""" return os.path.basename(self.filepath) @abc.abstractproperty def Z(self): """The atomic number of the atom.""" @abc.abstractproperty def Z_val(self): """Valence charge""" @property def type(self): return self.__class__.__name__ @property def element(self): """Pymatgen :class:`Element`.""" try: return _PTABLE[self.Z] except (KeyError, IndexError): return _PTABLE[int(self.Z)] @property def symbol(self): """Element symbol.""" return self.element.symbol @abc.abstractproperty def l_max(self): """Maximum angular momentum.""" @abc.abstractproperty def l_local(self): """Angular momentum used for the local part.""" @property def isnc(self): """True if norm-conserving pseudopotential.""" return isinstance(self, NcPseudo) @property def ispaw(self): """True if PAW pseudopotential.""" return isinstance(self, PawPseudo) #@lazy_property #def md5(self): # import md5 # m = md5.new() # with open(self.filepath, "r") as fh: # # Warning: line-based parser # for line in fh: # if line.startswith("<DOJO_REPORT>"): break # m.update(line) # return m.digest() #@lazy_property #def md5(self): # """Md5 hash value.""" # with open(self.path, "r") as fh: # lines = fh.readlines() # start = lines.index("<DOJO_REPORT>\n") # stop = lines.index("</DOJO_REPORT>\n") # text = "".join(lines[:start]) # # import hashlib # return hashlib.md5(text) #@abc.abstractproperty #def xc_type(self): # """XC family e.g LDA, GGA, MGGA.""" #@abc.abstractproperty #def xc_flavor(self): # """XC flavor e.g PW, PW91, PBE.""" #@property #def xc_functional(self): # """XC identifier e.g LDA-PW91, GGA-PBE, GGA-revPBE.""" # return "-".join([self.xc_type, self.xc_flavor]) #@abc.abstractproperty #def has_soc(self): # """True if pseudo contains spin-orbit coupling.""" #@abc.abstractmethod #def num_of_projectors(self, l='s'): # """Number of projectors for the angular channel l""" #@abc.abstractmethod #def generation_mode # """scalar scalar-relativistic, relativistic.""" @pmg_serialize def as_dict(self, **kwargs): return dict( basename=self.basename, type=self.type, symbol=self.symbol, Z=self.Z, Z_val=self.Z_val, l_max=self.l_max, #md5=self.md5, #nlcc_radius=self.nlcc_radius, #xc_type= #pp_type= filepath=self.filepath ) @classmethod def from_dict(cls, d): return cls.from_file(d['filepath']) @property def has_dojo_report(self): """True if self contains the `DOJO_REPORT` section.""" return bool(self.dojo_report) def delta_factor(self, accuracy="normal"): """ Returns the deltafactor [meV/natom] computed with the given accuracy. None if the `Pseudo` does not have info on the deltafactor. """ if not self.has_dojo_report: return None try: return self.dojo_report["delta_factor"][accuracy]["dfact"] except KeyError: return None def read_dojo_report(self): """ Read the `DOJO_REPORT` section and set dojo_report attribute. returns {} if section is not present. """ self.dojo_report = DojoReport.from_file(self.path) return self.dojo_report def write_dojo_report(self, report=None): """Write a new `DOJO_REPORT` section to the pseudopotential file.""" if report is None: report = self.dojo_report report["symbol"] = self.symbol # Create JSON string from report. jstring = json.dumps(report, indent=4, sort_keys=True) + "\n" # Read lines from file and insert jstring between the tags. with open(self.path, "r") as fh: lines = fh.readlines() try: start = lines.index("<DOJO_REPORT>\n") except ValueError: start = -1 if start == -1: # DOJO_REPORT was not present. lines += ["<DOJO_REPORT>\n", jstring , "</DOJO_REPORT>\n",] else: stop = lines.index("</DOJO_REPORT>\n") lines.insert(stop, jstring) del lines[start+1:stop] # Write new file. with FileLock(self.path): with open(self.path, "w") as fh: fh.writelines(lines) def remove_dojo_report(self): """Remove the `DOJO_REPORT` section from the pseudopotential file.""" # Read lines from file and insert jstring between the tags. with open(self.path, "r") as fh: lines = fh.readlines() try: start = lines.index("<DOJO_REPORT>\n") except ValueError: start = -1 if start == -1: return stop = lines.index("</DOJO_REPORT>\n") if stop == -1: return del lines[start+1:stop] # Write new file. with FileLock(self.path): with open(self.path, "w") as fh: fh.writelines(lines) def hint_for_accuracy(self, accuracy="normal"): """ Returns an hint object with parameters such as ecut [Ha] and aug_ratio for given accuracy. Returns None if no hint is available. Args: accuracy: ["low", "normal", "high"] """ if self.has_dojo_report: return Hint.from_dict(self.dojo_report["hints"][accuracy]) else: return None @property def has_hints(self): """True if self provides hints on the cutoff energy.""" for acc in ["low", "normal", "high"]: if self.hint_for_accuracy(acc) is None: return False return True class NcPseudo(six.with_metaclass(abc.ABCMeta, object)): """ Abstract class defining the methods that must be implemented by the concrete classes representing norm-conserving pseudopotentials. """ @abc.abstractproperty def nlcc_radius(self): """ Radius at which the core charge vanish (i.e. cut-off in a.u.). Returns 0.0 if nlcc is not used. """ @property def has_nlcc(self): """True if the pseudo is generated with non-linear core correction.""" return self.nlcc_radius > 0.0 @property def rcore(self): """Radius of the pseudization sphere in a.u.""" try: return self._core except AttributeError: return None class PawPseudo(six.with_metaclass(abc.ABCMeta, object)): """ Abstract class that defines the methods that must be implemented by the concrete classes representing PAW pseudopotentials. """ #def nlcc_radius(self): # """ # Radius at which the core charge vanish (i.e. cut-off in a.u.). # Returns 0.0 if nlcc is not used. # """ # return 0.0 # #@property #def has_nlcc(self): # """True if the pseudo is generated with non-linear core correction.""" # return True @abc.abstractproperty def paw_radius(self): """Radius of the PAW sphere in a.u.""" @property def rcore(self): """Alias of paw_radius.""" return self.paw_radius class AbinitPseudo(Pseudo): """ An AbinitPseudo is a pseudopotential whose file contains an abinit header. """ def __init__(self, path, header): """ Args: path: Filename. header: :class:`AbinitHeader` instance. """ self.path = path self._summary = header.summary if hasattr(header, "dojo_report"): self.dojo_report = header.dojo_report else: self.dojo_report = {} #self.pspcod = header.pspcod for attr_name, desc in header.items(): value = header.get(attr_name, None) # Hide these attributes since one should always use the public interface. setattr(self, "_" + attr_name, value) @property def summary(self): """Summary line reported in the ABINIT header.""" return self._summary.strip() @property def Z(self): return self._zatom @property def Z_val(self): return self._zion @property def l_max(self): return self._lmax @property def l_local(self): return self._lloc class NcAbinitPseudo(NcPseudo, AbinitPseudo): """Norm-conserving pseudopotential in the Abinit format.""" @property def summary(self): return self._summary.strip() @property def Z(self): return self._zatom @property def Z_val(self): """Number of valence electrons.""" return self._zion @property def l_max(self): return self._lmax @property def l_local(self): return self._lloc @property def nlcc_radius(self): return self._rchrg class PawAbinitPseudo(PawPseudo, AbinitPseudo): """Paw pseudopotential in the Abinit format.""" @property def paw_radius(self): return self._r_cut #def orbitals(self): class Hint(collections.namedtuple("Hint", "ecut aug_ratio")): """ Suggested value for the cutoff energy [Hartree units] and the augmentation ratio (PAW pseudo) """ def as_dict(self): return {f: getattr(self, f) for f in self._fields} @classmethod def from_dict(cls, d): return cls(**{k: v for k,v in d.items() if not k.startswith("@")}) def _dict_from_lines(lines, key_nums, sep=None): """ Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates the keys from the value (None if no separator is present). Returns: dict{key1 : value1, key2 : value2, ...} Raises: ValueError if parsing fails. """ if is_string(lines): lines = [lines] if not isinstance(key_nums, collections.Iterable): key_nums = list(key_nums) if len(lines) != len(key_nums): err_msg = "lines = %s\n key_num = %s" % (str(lines), str(key_nums)) raise ValueError(err_msg) kwargs = Namespace() for (i, nk) in enumerate(key_nums): if nk == 0: continue line = lines[i] tokens = [t.strip() for t in line.split()] values, keys = tokens[:nk], "".join(tokens[nk:]) # Sanitize keys: In some case we might string in for foo[,bar] keys.replace("[", "").replace("]", "") keys = keys.split(",") if sep is not None: check = keys[0][0] if check != sep: raise ValueError("Expecting separator %s, got %s" % (sep, check)) keys[0] = keys[0][1:] if len(values) != len(keys): msg = "line: %s\n len(keys) != len(value)\nkeys: %s\n values: %s" % (line, keys, values) raise ValueError(msg) kwargs.update(zip(keys, values)) return kwargs class AbinitHeader(dict): """Dictionary whose keys can be also accessed as attributes.""" def __getattr__(self, name): try: # Default behaviour return super(AbinitHeader, self).__getattribute__(name) except AttributeError: try: # Try in the dictionary. return self[name] except KeyError as exc: raise AttributeError(str(exc)) def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ float_num = float(string) int_num = int(float_num) if float_num == int_num: return int_num else: raise TypeError("Cannot convert string %s to int" % string) class NcAbinitHeader(AbinitHeader): """The abinit header found in the NC pseudopotential files.""" _attr_desc = collections.namedtuple("att", "default astype") _VARS = { # Mandatory "zatom" : _attr_desc(None, _int_from_str), "zion" : _attr_desc(None, float), "pspdat" : _attr_desc(None, float), "pspcod" : _attr_desc(None, int), "pspxc" : _attr_desc(None, int), "lmax" : _attr_desc(None, int), "lloc" : _attr_desc(None, int), "r2well" : _attr_desc(None, float), "mmax" : _attr_desc(None, float), # Optional variables for non linear-core correction. HGH does not have it. "rchrg" : _attr_desc(0.0, float), # radius at which the core charge vanish (i.e. cut-off in a.u.) "fchrg" : _attr_desc(0.0, float), "qchrg" : _attr_desc(0.0, float), } del _attr_desc def __init__(self, summary, **kwargs): super(NcAbinitHeader, self).__init__() # APE uses llocal instead of lloc. if "llocal" in kwargs: kwargs["lloc"] = kwargs.pop("llocal") self.summary = summary.strip() for (key, desc) in NcAbinitHeader._VARS.items(): default, astype = desc.default, desc.astype value = kwargs.pop(key, None) if value is None: value = default if default is None: raise RuntimeError("Attribute %s must be specified" % key) else: try: value = astype(value) except: raise RuntimeError("Conversion Error for key %s, value %s" % (key, value)) self[key] = value # Add dojo_report self["dojo_report"] = kwargs.pop("dojo_report", {}) #if kwargs: # raise RuntimeError("kwargs should be empty but got %s" % str(kwargs)) @staticmethod def fhi_header(filename, ppdesc): """Parse the FHI abinit header.""" # Example: # Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994 # 21.00000 3.00000 940714 zatom, zion, pspdat # 1 1 2 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well # 1.80626423934776 .22824404341771 1.17378968127746 rchrg,fchrg,qchrg lines = _read_nlines(filename, -1) try: header = _dict_from_lines(lines[:4], [0, 3, 6, 3]) except ValueError: # The last record with rchrg ... seems to be optional. header = _dict_from_lines(lines[:3], [0, 3, 6]) summary = lines[0] header["dojo_report"] = DojoReport.from_file(filename) return NcAbinitHeader(summary, **header) @staticmethod def hgh_header(filename, ppdesc): """Parse the HGH abinit header.""" # Example: #Hartwigsen-Goedecker-Hutter psp for Ne, from PRB58, 3641 (1998) # 10 8 010605 zatom,zion,pspdat # 3 1 1 0 2001 0 pspcod,pspxc,lmax,lloc,mmax,r2well lines = _read_nlines(filename, -1) header = _dict_from_lines(lines[:3], [0, 3, 6]) summary = lines[0] header["dojo_report"] = DojoReport.from_file(filename) return NcAbinitHeader(summary, **header) @staticmethod def gth_header(filename, ppdesc): """Parse the GTH abinit header.""" # Example: #Goedecker-Teter-Hutter Wed May 8 14:27:44 EDT 1996 #1 1 960508 zatom,zion,pspdat #2 1 0 0 2001 0. pspcod,pspxc,lmax,lloc,mmax,r2well #0.2000000 -4.0663326 0.6778322 0 0 rloc, c1, c2, c3, c4 #0 0 0 rs, h1s, h2s #0 0 rp, h1p # 1.36 .2 0.6 rcutoff, rloc lines = _read_nlines(filename, -1) header = _dict_from_lines(lines[:3], [0, 3, 6]) summary = lines[0] header["dojo_report"] = DojoReport.from_file(filename) return NcAbinitHeader(summary, **header) @staticmethod def oncvpsp_header(filename, ppdesc): """Parse the ONCVPSP abinit header.""" # Example #Li ONCVPSP r_core= 2.01 3.02 # 3.0000 3.0000 140504 zatom,zion,pspd # 8 2 1 4 600 0 pspcod,pspxc,lmax,lloc,mmax,r2well # 5.99000000 0.00000000 0.00000000 rchrg fchrg qchrg # 2 2 0 0 0 nproj # 0 extension_switch # 0 -2.5000025868368D+00 -1.2006906995331D+00 # 1 0.0000000000000D+00 0.0000000000000D+00 0.0000000000000D+00 # 2 1.0000000000000D-02 4.4140499497377D-02 1.9909081701712D-02 lines = _read_nlines(filename, -1) header = _dict_from_lines(lines[:3], [0, 3, 6]) summary = lines[0] header.update({'pspdat': header['pspd']}) header.pop('pspd') header["dojo_report"] = DojoReport.from_file(filename) return NcAbinitHeader(summary, **header) @staticmethod def tm_header(filename, ppdesc): """Parse the TM abinit header.""" # Example: #Troullier-Martins psp for element Fm Thu Oct 27 17:28:39 EDT 1994 #100.00000 14.00000 940714 zatom, zion, pspdat # 1 1 3 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well # 0 4.085 6.246 0 2.8786493 l,e99.0,e99.9,nproj,rcpsp # .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm # 1 3.116 4.632 1 3.4291849 l,e99.0,e99.9,nproj,rcpsp # .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm # 2 4.557 6.308 1 2.1865358 l,e99.0,e99.9,nproj,rcpsp # .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm # 3 23.251 29.387 1 2.4776730 l,e99.0,e99.9,nproj,rcpsp # .00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm # 3.62474762267880 .07409391739104 3.07937699839200 rchrg,fchrg,qchrg lines = _read_nlines(filename, -1) header = [] for (lineno, line) in enumerate(lines): header.append(line) if lineno == 2: # Read lmax. tokens = line.split() pspcod, pspxc, lmax, lloc = map(int, tokens[:4]) mmax, r2well = map(float, tokens[4:6]) #if tokens[-1].strip() != "pspcod,pspxc,lmax,lloc,mmax,r2well": # raise RuntimeError("%s: Invalid line\n %s" % (filename, line)) lines = lines[3:] break # TODO # Parse the section with the projectors. #0 4.085 6.246 0 2.8786493 l,e99.0,e99.9,nproj,rcpsp #.00000000 .0000000000 .0000000000 .00000000 rms,ekb1,ekb2,epsatm projectors = OrderedDict() for idx in range(2*(lmax+1)): line = lines[idx] if idx % 2 == 0: proj_info = [line,] if idx % 2 == 1: proj_info.append(line) d = _dict_from_lines(proj_info, [5,4]) projectors[int(d["l"])] = d # Add the last line with info on nlcc. header.append(lines[idx+1]) summary = header[0] header = _dict_from_lines(header, [0,3,6,3]) header["dojo_report"] = DojoReport.from_file(filename) return NcAbinitHeader(summary, **header) class PawAbinitHeader(AbinitHeader): """The abinit header found in the PAW pseudopotential files.""" _attr_desc = collections.namedtuple("att", "default astype") _VARS = { "zatom" : _attr_desc(None, _int_from_str), "zion" : _attr_desc(None, float), "pspdat" : _attr_desc(None, float), "pspcod" : _attr_desc(None, int), "pspxc" : _attr_desc(None, int), "lmax" : _attr_desc(None, int), "lloc" : _attr_desc(None, int), "mmax" : _attr_desc(None, int), "r2well" : _attr_desc(None, float), "pspfmt" : _attr_desc(None, str), "creatorID" : _attr_desc(None, int), "basis_size" : _attr_desc(None, int), "lmn_size" : _attr_desc(None, int), "orbitals" : _attr_desc(None, list), "number_of_meshes": _attr_desc(None, int), "r_cut" : _attr_desc(None, float), # r_cut(PAW) in the header "shape_type" : _attr_desc(None, int), "rshape" : _attr_desc(None, float), } del _attr_desc def __init__(self, summary, **kwargs): super(PawAbinitHeader, self).__init__() self.summary = summary.strip() for (key, desc) in self._VARS.items(): default, astype = desc.default, desc.astype value = kwargs.pop(key, None) if value is None: value = default if default is None: raise RuntimeError("Attribute %s must be specified" % key) else: try: value = astype(value) except: raise RuntimeError("Conversion Error for key %s, with value %s" % (key, value)) self[key] = value if kwargs: raise RuntimeError("kwargs should be empty but got %s" % str(kwargs)) @staticmethod def paw_header(filename, ppdesc): """Parse the PAW abinit header.""" #Paw atomic data for element Ni - Generated by AtomPAW (N. Holzwarth) + AtomPAW2Abinit v3.0.5 # 28.000 18.000 20061204 : zatom,zion,pspdat # 7 7 2 0 350 0. : pspcod,pspxc,lmax,lloc,mmax,r2well # paw3 1305 : pspfmt,creatorID # 5 13 : basis_size,lmn_size # 0 0 1 1 2 : orbitals # 3 : number_of_meshes # 1 3 350 1.1803778368E-05 3.5000000000E-02 : mesh 1, type,size,rad_step[,log_step] # 2 1 921 2.500000000000E-03 : mesh 2, type,size,rad_step[,log_step] # 3 3 391 1.1803778368E-05 3.5000000000E-02 : mesh 3, type,size,rad_step[,log_step] # 2.3000000000 : r_cut(SPH) # 2 0. # Example #C (US d-loc) - PAW data extracted from US-psp (D.Vanderbilt) - generated by USpp2Abinit v2.3.0 # 6.000 4.000 20090106 : zatom,zion,pspdat # 7 11 1 0 560 0. : pspcod,pspxc,lmax,lloc,mmax,r2well # paw4 2230 : pspfmt,creatorID # 4 8 : basis_size,lmn_size # 0 0 1 1 : orbitals # 5 : number_of_meshes # 1 2 560 1.5198032759E-04 1.6666666667E-02 : mesh 1, type,size,rad_step[,log_step] # 2 2 556 1.5198032759E-04 1.6666666667E-02 : mesh 2, type,size,rad_step[,log_step] # 3 2 576 1.5198032759E-04 1.6666666667E-02 : mesh 3, type,size,rad_step[,log_step] # 4 2 666 1.5198032759E-04 1.6666666667E-02 : mesh 4, type,size,rad_step[,log_step] # 5 2 673 1.5198032759E-04 1.6666666667E-02 : mesh 5, type,size,rad_step[,log_step] # 1.5550009124 : r_cut(PAW) # 3 0. : shape_type,rshape #Paw atomic data for element Si - Generated by atompaw v3.0.1.3 & AtomPAW2Abinit v3.3.1 # 14.000 4.000 20120814 : zatom,zion,pspdat # 7 11 1 0 663 0. : pspcod,pspxc,lmax,lloc,mmax,r2well # paw5 1331 : pspfmt,creatorID # 4 8 : basis_size,lmn_size # 0 0 1 1 : orbitals # 5 : number_of_meshes # 1 2 663 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 1, type,size,rad_step[,log_step] # 2 2 658 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 2, type,size,rad_step[,log_step] # 3 2 740 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 3, type,size,rad_step[,log_step] # 4 2 819 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 4, type,size,rad_step[,log_step] # 5 2 870 8.2129718540404674E-04 1.1498160595656655E-02 : mesh 5, type,size,rad_step[,log_step] # 1.5669671236 : r_cut(PAW) # 2 0. : shape_type,rshape supported_formats = ["paw3", "paw4", "paw5"] if ppdesc.format not in supported_formats: raise NotImplementedError("format %s not in %s" % (ppdesc.format, supported_formats)) lines = _read_nlines(filename, -1) summary = lines[0] header = _dict_from_lines(lines[:5], [0, 3, 6, 2, 2], sep=":") lines = lines[5:] # TODO # Parse orbitals and number of meshes. header["orbitals"] = [int(t) for t in lines[0].split(":")[0].split()] header["number_of_meshes"] = num_meshes = int(lines[1].split(":")[0]) #print filename, header # Skip meshes = lines = lines[2+num_meshes:] #for midx in range(num_meshes): # l = midx + 1 #print lines[0] header["r_cut"] = float(lines[0].split(":")[0]) #print lines[1] header.update(_dict_from_lines(lines[1], [2], sep=":")) report = DojoReport.from_file(filename) if report: header["dojo_report"] = report #print("PAW header\n", header) return PawAbinitHeader(summary, **header) class PseudoParserError(Exception): """Base Error class for the exceptions raised by :class:`PseudoParser`""" class PseudoParser(object): """ Responsible for parsing pseudopotential files and returning pseudopotential objects. Usage:: pseudo = PseudoParser().parse("filename") """ Error = PseudoParserError # Supported values of pspcod ppdesc = collections.namedtuple("ppdesc", "pspcod name psp_type format") # TODO Recheck _PSPCODES = OrderedDict( { 1: ppdesc(1, "TM", "NC", None), 2: ppdesc(2, "GTH", "NC", None), 3: ppdesc(3, "HGH", "NC", None), #4: ppdesc(4, "NC", , None), #5: ppdesc(5, "NC", , None), 6: ppdesc(6, "FHI", "NC", None), 7: ppdesc(6, "PAW_abinit_text", "PAW", None), 8: ppdesc(8, "ONCVPSP", "NC", None), 10: ppdesc(10, "HGHK", "NC", None), }) del ppdesc # renumber functionals from oncvpsp todo confrim that 3 is 2 _FUNCTIONALS = {1: {'n': 4, 'name': 'Wigner'}, 2: {'n': 5, 'name': 'HL'}, 3: {'n': 2, 'name': 'PWCA'}, 4: {'n': 11, 'name': 'PBE'}} def __init__(self): # List of files that have been parsed succesfully. self._parsed_paths = [] # List of files that could not been parsed. self._wrong_paths = [] def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()): """ Analyze the files contained in directory dirname. Args: dirname: directory path exclude_exts: list of file extensions that should be skipped. exclude_fnames: list of file names that should be skipped. Returns: List of pseudopotential objects. """ for (i, ext) in enumerate(exclude_exts): if not ext.strip().startswith("."): exclude_exts[i] = "." + ext.strip() # Exclude files depending on the extension. paths = [] for fname in os.listdir(dirname): root, ext = os.path.splitext(fname) path = os.path.join(dirname, fname) if (ext in exclude_exts or fname in exclude_fnames or fname.startswith(".") or not os.path.isfile(path)): continue paths.append(path) pseudos = [] for path in paths: # Parse the file and generate the pseudo. try: pseudo = self.parse(path) except: pseudo = None if pseudo is not None: pseudos.append(pseudo) self._parsed_paths.extend(path) else: self._wrong_paths.extend(path) return pseudos def read_ppdesc(self, filename): """ Read the pseudopotential descriptor from file filename. Returns: Pseudopotential descriptor. None if filename is not a valid pseudopotential file. Raises: `PseudoParserError` if fileformat is not supported. """ if filename.endswith(".xml"): raise self.Error("XML pseudo not supported yet") else: # Assume file with the abinit header. lines = _read_nlines(filename, 80) for (lineno, line) in enumerate(lines): if lineno == 2: try: tokens = line.split() pspcod, pspxc = map(int, tokens[:2]) except: msg = "%s: Cannot parse pspcod, pspxc in line\n %s" % (filename, line) sys.stderr.write(msg) return None #if tokens[-1].strip().replace(" ","") not in ["pspcod,pspxc,lmax,lloc,mmax,r2well", # "pspcod,pspxc,lmax,llocal,mmax,r2well"]: # raise self.Error("%s: Invalid line\n %s" % (filename, line)) # return None if pspcod not in self._PSPCODES: raise self.Error("%s: Don't know how to handle pspcod %s\n" % (filename, pspcod)) ppdesc = self._PSPCODES[pspcod] if pspcod == 7: # PAW -> need to know the format pspfmt tokens = lines[lineno+1].split() pspfmt, creatorID = tokens[:2] #if tokens[-1].strip() != "pspfmt,creatorID": # raise self.Error("%s: Invalid line\n %s" % (filename, line)) # return None ppdesc = ppdesc._replace(format = pspfmt) return ppdesc return None def parse(self, filename): """ Read and parse a pseudopotential file. Main entry point for client code. Returns: pseudopotential object or None if filename is not a valid pseudopotential file. """ path = os.path.abspath(filename) # Only PAW supports XML at present. if filename.endswith(".xml"): return PawXmlSetup(path) ppdesc = self.read_ppdesc(path) if ppdesc is None: return None psp_type = ppdesc.psp_type parsers = { "FHI" : NcAbinitHeader.fhi_header, "GTH" : NcAbinitHeader.gth_header, "TM" : NcAbinitHeader.tm_header, "HGH" : NcAbinitHeader.hgh_header, "HGHK" : NcAbinitHeader.hgh_header, "ONCVPSP" : NcAbinitHeader.oncvpsp_header, "PAW_abinit_text": PawAbinitHeader.paw_header, } try: header = parsers[ppdesc.name](path, ppdesc) except Exception as exc: raise self.Error(path + ":\n" + straceback()) root, ext = os.path.splitext(path) if psp_type == "NC": pseudo = NcAbinitPseudo(path, header) elif psp_type == "PAW": pseudo = PawAbinitPseudo(path, header) else: raise NotImplementedError("psp_type not in [NC, PAW]") return pseudo #TODO use RadialFunction from pseudo_dojo. class RadialFunction(collections.namedtuple("RadialFunction", "mesh values")): pass class PawXmlSetup(Pseudo, PawPseudo): def __init__(self, filepath): # FIXME self.dojo_report = {} self.path = os.path.abspath(filepath) # Get the XML root (this trick is used to that the object is pickleable). root = self.root # Get the version of the XML format self.paw_setup_version = root.get("version") # Info on the atom. atom_attrib = root.find("atom").attrib #self._symbol = atom_attrib["symbol"] self._zatom = int(float(atom_attrib["Z"])) self.core, self.valence = map(float, [atom_attrib["core"], atom_attrib["valence"]]) #xc_info = root.find("atom").attrib #self.xc_type, self.xc_name = xc_info["type"], xc_info["name"] #self.ae_energy = {k: float(v) for k,v in root.find("ae_energy").attrib.items()} # Old XML files do not define this field! # In this case we set the PAW radius to None. #self._paw_radius = float(root.find("PAW_radius").attrib["rpaw"]) pawr_element = root.find("PAW_radius") self._paw_radius = None if pawr_element is not None: self._paw_radius = float(pawr_element.attrib["rpaw"]) #<valence_states> # <state n="2" l="0" f="2" rc="1.10" e="-0.6766" id="N-2s"/> # <state n="2" l="1" f="3" rc="1.10" e="-0.2660" id="N-2p"/> # <state l="0" rc="1.10" e=" 0.3234" id="N-s1"/> # <state l="1" rc="1.10" e=" 0.7340" id="N-p1"/> # <state l="2" rc="1.10" e=" 0.0000" id="N-d1"/> #</valence_states> # # The valence_states element contains several state elements. # For this setup, the first two lines describe bound eigenstates # with occupation numbers and principal quantum numbers. # Notice, that the three additional unbound states should have no f and n attributes. # In this way, we know that only the first two bound states (with f and n attributes) # should be used for constructing an initial guess for the wave functions. self.valence_states = {} for node in root.find("valence_states"): attrib = AttrDict(node.attrib) assert attrib.id not in self.valence_states self.valence_states[attrib.id] = attrib #print(self.valence_states) # Parse the radial grids self.rad_grids = {} for node in root.findall("radial_grid"): grid_params = node.attrib gid = grid_params["id"] assert gid not in self.rad_grids self.rad_grids[id] = self._eval_grid(grid_params) def __getstate__(self): """ Return state is pickled as the contents for the instance. In this case we just remove the XML root element process since Element object cannot be pickled. """ return {k: v for k, v in self.__dict__.items() if k not in ["_root"]} @property def root(self): try: return self._root except AttributeError: from xml.etree import cElementTree as Et tree = Et.parse(self.filepath) self._root = tree.getroot() return self._root @property def Z(self): return self._zatom @property def Z_val(self): """Number of valence electrons.""" return self.valence # FIXME @property def l_max(self): """Maximum angular momentum.""" return None @property def l_local(self): """Angular momentum used for the local part.""" return None @property def summary(self): """String summarizing the most important properties.""" return "" @property def paw_radius(self): return self._paw_radius @staticmethod def _eval_grid(grid_params): """ This function receives a dictionary with the parameters defining the radial mesh and returns a `ndarray` with the mesh """ eq = grid_params.get("eq").replace(" ", "") istart, iend = int(grid_params.get("istart")), int(grid_params.get("iend")) indices = list(range(istart, iend+1)) if eq == 'r=a*exp(d*i)': a, d = float(grid_params['a']), float(grid_params['d']) mesh = [a * np.exp(d * i) for i in indices] elif eq == 'r=a*i/(n-i)': a, n = float(grid_params['a']), float(grid_params['n']) mesh = [a * i / (n - i) for i in indices] elif eq == 'r=a*(exp(d*i)-1)': a, d = float(grid_params['a']), float(grid_params['d']) mesh = [a * (np.exp(d * i) - 1.0) for i in indices] elif eq == 'r=d*i': d = float(grid_params['d']) mesh = [d * i for i in indices] elif eq == 'r=(i/n+a)^5/a-a^4': a, n = float(grid_params['a']), float(grid_params['n']) mesh = [(i / n + a)**5 / a - a**4 for i in indices] else: raise ValueError('Unknown grid type: %s' % eq) return np.array(mesh) def _parse_radfunc(self, func_name): """Parse the first occurence of func_name in the XML file.""" node = self.root.find(func_name) grid = node.attrib["grid"] values = np.array([float(s) for s in node.text.split()]) return self.rad_grids[grid], values, node.attrib def _parse_all_radfuncs(self, func_name): """Parse all the nodes with tag func_name in the XML file.""" for node in self.root.findall(func_name): grid = node.attrib["grid"] values = np.array([float(s) for s in node.text.split()]) yield self.rad_grids[grid], values, node.attrib @property def ae_core_density(self): """The all-electron radial density.""" try: return self._ae_core_density except AttributeError: mesh, values, attrib = self._parse_radfunc("ae_core_density") self._ae_core_density = RadialFunction(mesh, values) return self._ae_core_density @property def pseudo_core_density(self): """The pseudized radial density.""" try: return self._pseudo_core_density except AttributeError: mesh, values, attrib = self._parse_radfunc("pseudo_core_density") self._pseudo_core_density = RadialFunction(mesh, values) return self._pseudo_core_density @property def ae_partial_waves(self): """Dictionary with the AE partial waves indexed by state.""" try: return self._ae_partial_waves except AttributeError: self._ae_partial_waves = {} for (mesh, values, attrib) in self._parse_all_radfuncs("ae_partial_wave"): state = attrib["state"] val_state = self.valence_states[state] self._ae_partial_waves[state] = RadialFunction(mesh, values) #print("val_state", val_state) return self._ae_partial_waves @property def pseudo_partial_waves(self): """Dictionary with the pseudo partial waves indexed by state.""" try: return self._pseudo_partial_waves except AttributeError: self._pseudo_partial_waves = {} for (mesh, values, attrib) in self._parse_all_radfuncs("pseudo_partial_wave"): state = attrib["state"] val_state = self.valence_states[state] self._pseudo_partial_waves[state] = RadialFunction(mesh, values) return self._pseudo_partial_waves @property def projector_functions(self): """Dictionary with the PAW projectors indexed by state.""" try: return self._projector_functions except AttributeError: self._projector_functions = {} for (mesh, values, attrib) in self._parse_all_radfuncs("projector_function"): state = attrib["state"] val_state = self.valence_states[state] self._projector_functions[state] = RadialFunction(mesh, values) return self._projector_functions @add_fig_kwargs def plot_densities(self, ax=None, **kwargs): """ Plot the PAW densities. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure """ ax, fig, plt = get_ax_fig_plt(ax) ax.grid(True) ax.set_xlabel('r [Bohr]') #ax.set_ylabel('density') for i, den_name in enumerate(["ae_core_density", "pseudo_core_density"]): rden = getattr(self, den_name) label = "$n_c$" if i == 1 else "$\\tilde{n}_c$" ax.plot(rden.mesh, rden.mesh * rden.values, label=label, lw=2) plt.legend(loc="best") return fig @add_fig_kwargs def plot_waves(self, ax=None, **kwargs): """ Plot the AE and the pseudo partial waves. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure """ ax, fig, plt = get_ax_fig_plt(ax) ax.grid(True) ax.set_xlabel("r [Bohr]") ax.set_ylabel("$r\phi,\\, r\\tilde\phi\, [Bohr]^{-\\frac{1}{2}}$") ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle="--") #ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1)) for state, rfunc in self.pseudo_partial_waves.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="PS-WAVE: " + state) for state, rfunc in self.ae_partial_waves.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label="AE-WAVE: " + state) ax.legend(loc="best") return fig @add_fig_kwargs def plot_projectors(self, ax=None, **kwargs): """ Plot the PAW projectors. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure """ ax, fig, plt = get_ax_fig_plt(ax) title = kwargs.pop("title", "Projectors") ax.grid(True) ax.set_xlabel('r [Bohr]') ax.set_ylabel("$r\\tilde p\, [Bohr]^{-\\frac{1}{2}}$") ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle="--") #ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1)) for state, rfunc in self.projector_functions.items(): ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, label="TPROJ: " + state) ax.legend(loc="best") return fig #@add_fig_kwargs #def plot_potentials(self, **kwargs): # """ # ================ ============================================================== # kwargs Meaning # ================ ============================================================== # title Title of the plot (Default: None). # show True to show the figure (Default). # savefig 'abc.png' or 'abc.eps' to save the figure to a file. # ================ ============================================================== # Returns: # `matplotlib` figure # """ # title = kwargs.pop("title", "Potentials") # show = kwargs.pop("show", True) # savefig = kwargs.pop("savefig", None) # import matplotlib.pyplot as plt # fig = plt.figure() # ax = fig.add_subplot(1,1,1) # ax.grid(True) # ax.set_xlabel('r [Bohr]') # ax.set_ylabel('density') # ax.axvline(x=self.paw_radius, linewidth=2, color='k', linestyle="--") # ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1)) # for state, rfunc in self.potentials.items(): # ax.plot(rfunc.mesh, rfunc.values, label="TPROJ: " + state) # plt.legend(loc="best") # if title is not None: fig.suptitle(title) # if show: plt.show() # if savefig: fig.savefig(savefig) # return fig class PseudoTable(six.with_metaclass(abc.ABCMeta, collections.Sequence, PMGSONable, object)): """ Define the pseudopotentials from the element table. Individidual elements are accessed by name, symbol or atomic number. For example, the following all retrieve iron: print elements[26] Fe print elements.Fe Fe print elements.symbol('Fe') Fe print elements.name('iron') Fe print elements.isotope('Fe') Fe """ @classmethod def as_table(cls, items): """ Return an instance of :class:`PseudoTable` from the iterable items. """ if isinstance(items, cls): return items return cls(items) @classmethod def from_dir(cls, top, exts=None, exclude_dirs="_*"): """ Find all pseudos in the directory tree starting from top. Args: top: Top of the directory tree exts: List of files extensions. if exts == "all_files" we try to open all files in top exclude_dirs: Wildcard used to exclude directories. return: :class:`PseudoTable` sorted by atomic number Z. """ pseudos = [] if exts == "all_files": for f in [os.path.join(path, fn) for fn in os.listdir(top)]: if os.path.isfile(f): try: p = Pseudo.from_file(f) if p: pseudos.append(p) else: logger.info('Skipping file %s' % f) except: logger.info('Skipping file %s' % f) if not pseudos: logger.warning('No pseudopotentials parsed from folder %s' % top) return None logger.info('Creating PseudoTable with %i pseudopotentials' % len(pseudos)) else: if exts is None: exts=("psp8",) for p in find_exts(top, exts, exclude_dirs=exclude_dirs): try: pseudos.append(Pseudo.from_file(p)) except Exception as exc: logger.critical("Error in %s:\n%s" % (p, exc)) return cls(pseudos).sort_by_z() #@pmg_serialize #def as_dict(self, **kwargs): # return {pseudo.as_dict() for pseudo in self} #@classmethod #def from_dict(cls, d): # pseudos = [p.from_dict(d) for k, p in cls.as_dict().items() if not k.startswith("@")] # print(pseudos) # #return cls(pseudos) def __init__(self, pseudos): """ Args: pseudos: List of pseudopotentials or filepaths """ # Store pseudos in a default dictionary with z as key. # Note that we can have more than one pseudo for given z. # hence the values are lists of pseudos. if not isinstance(pseudos, collections.Iterable): pseudos = [pseudos] if len(pseudos) and is_string(pseudos[0]): pseudos = list_strings(pseudos) self._pseudos_with_z = collections.defaultdict(list) for pseudo in pseudos: p = pseudo if not isinstance(pseudo, Pseudo): p = Pseudo.from_file(pseudo) self._pseudos_with_z[p.Z].append(p) for z in self.zlist: pseudo_list = self._pseudos_with_z[z] symbols = [p.symbol for p in pseudo_list] symbol = symbols[0] if any(symb != symbol for symb in symbols): raise ValueError("All symbols must be equal while they are: %s" % str(symbols)) setattr(self, symbol, pseudo_list) def __getitem__(self, Z): """ Retrieve pseudos for the atomic number z. Accepts both int and slice objects. """ if isinstance(Z, slice): assert Z.stop is not None pseudos = [] for znum in iterator_from_slice(Z): pseudos.extend(self._pseudos_with_z[znum]) return self.__class__(pseudos) else: return self.__class__(self._pseudos_with_z[Z]) def __len__(self): return len(list(self.__iter__())) def __iter__(self): """Process the elements in Z order.""" for z in self.zlist: for pseudo in self._pseudos_with_z[z]: yield pseudo def __repr__(self): return "<%s at %s>" % (self.__class__.__name__, id(self)) def __str__(self): lines = [] app = lines.append app("<%s, len=%d>" % (self.__class__.__name__, len(self))) for pseudo in self: app(str(pseudo)) return "\n".join(lines) @property def allnc(self): """True if all pseudos are norm-conserving.""" return all(p.isnc for p in self) @property def allpaw(self): """True if all pseudos are PAW.""" return all(p.ispaw for p in self) @property def zlist(self): """Ordered list with the atomic numbers available in the table.""" return sorted(list(self._pseudos_with_z.keys())) def as_dict(self, **kwargs): d = {} for p in self: k, count = p.basename, 1 # Handle multiple-pseudos with the same name! while k in d: k += k.split("#")[0] + "#" + str(count) count += 1 d.update({k: p.as_dict()}) d['@module'] = self.__class__.__module__ d['@class'] = self.__class__.__name__ return d @classmethod def from_dict(cls, d): pseudos = [] dec = MontyDecoder() for k, v in d.items(): pseudos.extend(dec.process_decoded(v)) return cls(pseudos) def is_complete(self, zmax=118): """ True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential """ for z in range(1, zmax): if not self[z]: return False return True def pseudo_with_symbol(self, symbol): """ Return the pseudo with the given chemical symbol. Raises: ValueError if symbol is not found or multiple occurences are present. """ pseudos = self.select_symbols(symbol, ret_list=True) if not pseudos or len(pseudos) > 1: raise ValueError("Found %d occurrences of symbol %s" % (len(pseudos), symbol)) return pseudos[0] def pseudos_with_symbols(self, symbols): """ Return the pseudos with the given chemical symbols. Raises: ValueError if one of the symbols is not found or multiple occurences are present. """ pseudos = self.select_symbols(symbols, ret_list=True) found_symbols = [p.symbol for p in pseudos] duplicated_elements = [s for s, o in collections.Counter(found_symbols).items() if o > 1] if duplicated_elements: raise ValueError("Found multiple occurrences of symbol(s) %s" % ', '.join(duplicated_elements)) missing_symbols = [s for s in symbols if s not in found_symbols] if missing_symbols: raise ValueError("Missing data for symbol(s) %s" % ', '.join(missing_symbols)) return pseudos def select_symbols(self, symbols, ret_list=False): """ Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list: if True a list of pseudos is returned instead of a :class:`PseudoTable` """ symbols = list_strings(symbols) exclude = symbols[0].startswith("-") if exclude: if not all(s.startswith("-") for s in symbols): raise ValueError("When excluding symbols, all strings must start with `-`") symbols = [s[1:] for s in symbols] #print(symbols) symbols = set(symbols) pseudos = [] for p in self: if exclude: if p.symbol in symbols: continue else: if p.symbol not in symbols: continue pseudos.append(p) if ret_list: return pseudos else: return self.__class__(pseudos) def get_pseudos_for_structure(self, structure): """ Return the list of :class:`Pseudo` objects to be used for this :class:`Structure`. Args: structure: pymatgen :class:`Structure`. Raises: `ValueError` if one of the chemical symbols is not found or multiple occurences are present in the table. """ symbols = structure.symbol_set return self.pseudos_with_symbols(symbols) #def list_properties(self, *props, **kw): # """ # Print a list of elements with the given set of properties. # Args: # *prop1*, *prop2*, ... : string # Name of the properties to print # *format*: string # Template for displaying the element properties, with one # % for each property. # For example, print a table of mass and density. # from periodictable import elements # elements.list_properties('symbol','mass','density', format="%-2s: %6.2f u %5.2f g/cm^3") # H : 1.01 u 0.07 g/cm^3 # He: 4.00 u 0.12 g/cm^3 # Li: 6.94 u 0.53 g/cm^3 # ... # Bk: 247.00 u 14.00 g/cm^3 # """ # format = kw.pop('format', None) # assert len(kw) == 0 # for pseudo in self: # try: # values = tuple(getattr(pseudo, p) for p in props) # except AttributeError: # # Skip elements which don't define all the attributes # continue # # Skip elements with a value of None # if any(v is None for v in values): # continue # if format is None: # print(" ".join(str(p) for p in values)) # else: # try: # print(format % values) # except: # print("format",format,"args",values) # raise #def print_table(self, stream=sys.stdout, filter_function=None): # """ # A pretty ASCII printer for the periodic table, based on some filter_function. # Args: # filter_function: # A filtering function that take a Pseudo as input and returns a boolean. # For example, setting filter_function = lambda el: el.Z_val > 2 will print # a periodic table containing only pseudos with Z_val > 2. # """ # for row in range(1, 10): # rowstr = [] # for group in range(1, 19): # el = Element.from_row_and_group(row, group) # if el and ((not filter_function) or filter_function(el)): # rowstr.append("{:3s}".format(el.symbol)) # else: # rowstr.append(" ") # print(" ".join(rowstr)) def sorted(self, attrname, reverse=False): """ Sort the table according to the value of attribute attrname. Return: New class:`PseudoTable` object """ attrs = [] for i, pseudo in self: try: a = getattr(pseudo, attrname) except AttributeError: a = np.inf attrs.append((i, a)) # Sort attrs, and build new table with sorted pseudos. return self.__class__([self[a[0]] for a in sorted(attrs, key=lambda t: t[1], reverse=reverse)]) def sort_by_z(self): """Return a new :class:`PseudoTable` with pseudos sorted by Z""" return self.__class__(sorted(self, key=lambda p: p.Z)) def select(self, condition): """ Select only those pseudopotentials for which condition is True. Return new class:`PseudoTable` object. Args: condition: Function that accepts a :class:`Pseudo` object and returns True or False. """ return self.__class__([p for p in self if condition(p)]) def with_dojo_report(self): """Select pseudos containing the DOJO_REPORT section. Return new class:`PseudoTable` object.""" return self.select(condition=lambda p: p.has_dojo_report) def get_dojo_dataframe(self, **kwargs): """ Buid a pandas :class:`DataFrame` with the most important parameters extracted from the `DOJO_REPORT` section of each pseudo in the table. Returns: frame, errors where frame is the pandas :class:`DataFrame` and errors is a list of errors encountered while trying to read the `DOJO_REPORT` from the pseudopotential file. """ accuracies = ["low", "normal", "high"] trial2keys = { "deltafactor": ["dfact_meV", "dfactprime_meV"] + ["v0", "b0_GPa", "b1"], "gbrv_bcc": ["a0_rel_err"], "gbrv_fcc": ["a0_rel_err"], } rows, names, errors = [], [], [] for p in self: report = p.dojo_report assert "version" in report #if "version" not in report: # print("ignoring old report in ", p.basename) # continue d = {"symbol": p.symbol, "Z": p.Z} names.append(p.basename) # FIXME ecut_acc = dict( low=report.ecuts[0], normal=report.ecuts[4], high=report.ecuts[-1], ) for acc in accuracies: d[acc + "_ecut"] = ecut_acc[acc] try: for trial, keys in trial2keys.items(): data = report.get(trial, None) if data is None: continue for acc in accuracies: ecut = ecut_acc[acc] if trial.startswith("gbrv"): d.update({acc + "_" + trial + "_" + k: float(data[ecut][k]) for k in keys}) else: d.update({acc + "_" + k: float(data[ecut][k]) for k in keys}) except Exception as exc: logger.warning("%s raised %s" % (p.basename, exc)) errors.append((p.basename, str(exc))) #print(d) rows.append(d) # Build sub-class of pandas.DataFrame return DojoDataFrame(rows, index=names), errors def select_rows(self, rows): """ Return new class:`PseudoTable` object with pseudos in the given rows of the periodic table. rows can be either a int or a list of integers. """ if not isinstance(rows, (list, tuple)): rows = [rows] return self.__class__([p for p in self if p.element.row in rows]) def select_family(self, family): # e.g element.is_alkaline return self.__class__([p for p in self if getattr(p.element, "is_" + family)]) def dojo_compare(self, what="all", **kwargs): """Compare ecut convergence and Deltafactor, GBRV results""" import matplotlib.pyplot as plt show = kwargs.pop("show", True) what = list_strings(what) figs = [] if all(p.dojo_report.has_trial("deltafactor") for p in self) and \ any(k in what for k in ("all", "ecut")): fig_etotal, ax_list = plt.subplots(nrows=len(self), ncols=1, sharex=True, squeeze=True) #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(self), ncols=1, sharex=True, squeeze=True) figs.append(fig_etotal) for ax, pseudo in zip(ax_list, self): pseudo.dojo_report.plot_etotal_vs_ecut(ax=ax, show=False, label=pseudo.basename) if show: plt.show() if all(p.dojo_report.has_trial("deltafactor") for p in self) and \ any(k in what for k in ("all", "df", "deltafactor")): fig_deltafactor, ax_grid = plt.subplots(nrows=5, ncols=len(self), sharex=True, sharey="row", squeeze=False) #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=5, ncols=len(self), sharex=True, sharey="row", squeeze=False)) figs.append(fig_deltafactor) for ax_list, pseudo in zip(ax_grid.T, self): pseudo.dojo_report.plot_deltafactor_convergence(ax_list=ax_list, show=False) fig_deltafactor.suptitle(" vs ".join(p.basename for p in self)) if show: plt.show() # Compare GBRV results if all(p.dojo_report.has_trial("gbrv_bcc") for p in self) and \ any(k in what for k in ("all", "gbrv")): fig_gbrv, ax_grid = plt.subplots(nrows=2, ncols=len(self), sharex=True, sharey="row", squeeze=False) figs.append(fig_gbrv) #ax_list, fig, plt = get_axarray_fig_plt(ax_list, ncols=len(self), sharex=True, sharey="row", squeeze=False)) for ax_list, pseudo in zip(ax_grid.T, self): pseudo.dojo_report.plot_gbrv_convergence(ax_list=ax_list, show=False) fig_gbrv.suptitle(" vs ".join(p.basename for p in self)) if show: plt.show() return figs @classmethod @deprecated(replacement=from_dir) def from_directory(cls, path): pseudos = [] for f in [os.path.join(path, fn) for fn in os.listdir(path)]: if os.path.isfile(f): try: p = Pseudo.from_file(f) if p: pseudos.append(p) else: logger.info('Skipping file %s' % f) except: logger.info('Skipping file %s' % f) if not pseudos: logger.warning('No pseudopotentials parsed from folder %s' % path) return None logger.info('Creating PseudoTable with %i pseudopotentials' % len(pseudos)) return cls(pseudos) try: from pandas import DataFrame except ImportError: DataFrame = object class DojoDataFrame(DataFrame): ALL_ACCURACIES = ("low", "normal", "high") ALL_TRIALS = ( "ecut", "deltafactor", "gbrv_bcc", "gbrv_fcc", ) _TRIALS2KEY = { "ecut": "ecut", "deltafactor": "dfact_meV", "gbrv_bcc": "gbrv_bcc_a0_rel_err", "gbrv_fcc": "gbrv_fcc_a0_rel_err", } _TRIALS2YLABEL = { "ecut": "Ecut [Ha]", "deltafactor": "$\Delta$-factor [meV]", "gbrv_bcc": "BCC $\Delta a_0$ (%)", "gbrv_fcc": "FCC $\Delta a_0$ (%)", } ACC2PLTOPTS = dict( low=dict(color="red"), normal=dict(color="blue"), high=dict(color="green"), ) for v in ACC2PLTOPTS.values(): v.update(linewidth=2, linestyle='dashed', marker='o', markersize=8) def tabulate(self, columns=None, stream=sys.stdout): from tabulate import tabulate if columns is None: accuracies = self.ALL_ACCURACIES columns = [acc + "_dfact_meV" for acc in accuracies] columns += [acc + "_ecut" for acc in accuracies] columns += [acc + "_gbrv_fcc_a0_rel_err" for acc in accuracies] columns += [acc + "_gbrv_bcc_a0_rel_err" for acc in accuracies] #return self[columns].to_html() tablefmt = "grid" floatfmt=".2f" stream.write(tabulate(self[columns], headers="keys", tablefmt=tablefmt, floatfmt=floatfmt)) def get_accuracy(self, accuracy): columns = [c for c in self if c.startswith(accuracy)] return self.__class__(data=self[columns]) def get_trials(self, accuracies="all"): accuracies = self.ALL_ACCURACIES if accuracies == "all" else list_strings(accuracies) columns = [acc + "_dfact_meV" for acc in accuracies] columns += [acc + "_ecut" for acc in accuracies] columns += [acc + "_gbrv_fcc_a0_rel_err" for acc in accuracies] columns += [acc + "_gbrv_bcc_a0_rel_err" for acc in accuracies] return self.__class__(data=self[columns]) def select_rows(self, rows): if not isinstance(rows, (list, tuple)): rows = [rows] data = [] for index, entry in self.iterrows(): element = _PTABLE[entry.Z] if element.row in rows: data.append(entry) return self.__class__(data=data) def select_family(self, family): data = [] for index, entry in self.iterrows(): element = _PTABLE[entry.Z] # e.g element.is_alkaline if getattr(element, "is_" + family): data.append(entry) return self.__class__(data=data) @add_fig_kwargs def plot_hist(self, what="dfact_meV", bins=400, **kwargs): import matplotlib.pyplot as plt fig, ax_list = plt.subplots(nrows=len(self.ALL_ACCURACIES), ncols=1, sharex=True, sharey=False, squeeze=True) #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(self.ALL_ACCURACIES), ncols=1, sharex=True, sharey=False, squeeze=True) for acc, ax in zip(self.ALL_ACCURACIES, ax_list): col = acc + "_" + what #print(col) #self[col].hist(ax=ax, bins=bins, label=col) self[col].plot(ax=ax, kind="bar", label=col) return fig @add_fig_kwargs def plot_trials(self, trials="all", accuracies="all", **kwargs): import matplotlib.pyplot as plt trials = self.ALL_TRIALS if trials == "all" else list_strings(trials) accuracies = self.ALL_ACCURACIES if accuracies == "all" else list_strings(accuracies) fig, ax_list = plt.subplots(nrows=len(trials), ncols=1, sharex=True, sharey=False, squeeze=True) #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(trials), ncols=1, sharex=True, sharey=False, squeeze=True) # See also http://matplotlib.org/examples/pylab_examples/barchart_demo.html for i, (trial, ax) in enumerate(zip(trials, ax_list)): what = self._TRIALS2KEY[trial] ax.set_ylabel(self._TRIALS2YLABEL[trial]) minval, maxval = np.inf, -np.inf for acc in accuracies: col = acc + "_" + what legend = i == 0 data = self[col] minval, maxval = min(minval, data.min()), max(maxval, data.max()) data.plot(ax=ax, legend=legend, use_index=True, label=acc, **self.ACC2PLTOPTS[acc]) #data.plot(ax=ax, kind="bar") if i == 0: ax.legend(loc='best', shadow=True, frameon=True) #fancybox=True) ax.set_xticks(range(len(data.index))) ax.set_xticklabels(data.index) #ax.set_xticklabels([root for root, ext in map(os.path.splitext, data.index)]) # Set ylimits #stepsize = None #if "gbrv" in trial: # ax.hlines(0.0, 0, len(data.index)) # #start, end = -0.6, +0.6 # start, end = max(-0.6, minval), min(+0.6, maxval) # if end - start < 0.05: end = start + 0.1 # ax.set_ylim(start, end) # ax.yaxis.set_ticks(np.arange(start, end, 0.05)) if trial == "deltafactor": #start, end = 0.0, 15 start, end = 0.0, min(15, maxval) ax.set_ylim(start, end) #ax.yaxis.set_ticks(np.arange(start, end, 0.1)) #if stepsize is not None: # start, end = ax.get_ylim() # ax.yaxis.set_ticks(np.arange(start, end, stepsize)) plt.setp(ax.xaxis.get_majorticklabels(), rotation=25) return fig #def sns_plot(self): # import seaborn as sns # import matplotlib.pyplot as plt # #self.plot(x="symbol", y="high_dfact_meV", use_index=True) # #data = calc_rerrors(data) # g = sns.PairGrid(self, x_vars="Z", y_vars=[ # "low_ecut", # "low_dfact_meV", # #"high_dfact_meV", # #"low_v0_rerr", "low_b0_GPa_rerr", "low_b1_rerr", # ] # ) #, hue="smoker") # g.map(plt.scatter) # g.add_legend() # plt.show() class DojoReport(dict): """Dict-like object with the dojo report.""" _TRIALS2KEY = { "deltafactor": "dfact_meV", "gbrv_bcc": "a0_rel_err", "gbrv_fcc": "a0_rel_err", } ALL_ACCURACIES = ("low", "normal", "high") ALL_TRIALS = ( "deltafactor", "gbrv_bcc", "gbrv_fcc", ) ATOLS = (0.2, 0.1, 0.01) @classmethod def from_file(cls, filepath): """Read the DojoReport from file.""" with open(filepath, "r") as fh: lines = fh.readlines() try: start = lines.index("<DOJO_REPORT>\n") except ValueError: return {} stop = lines.index("</DOJO_REPORT>\n") d = json.loads("".join(lines[start+1:stop])) return cls(**d) @classmethod def from_hints(cls, ppgen_ecut, symbol): """Initialize the DojoReport from an initial value of ecut in Hartree.""" dense_right = np.arange(ppgen_ecut, ppgen_ecut + 6*2, step=2) dense_left = np.arange(max(ppgen_ecut-6, 2), ppgen_ecut, step=2) coarse_high = np.arange(ppgen_ecut + 15, ppgen_ecut + 35, step=5) ecut_list = list(dense_left) + list(dense_right) + list(coarse_high) return cls(ecut_list=ecut_list, symbol=symbol) #, **{k: {}: for k in self.ALL_TRIALS}) def __init__(self, *args, **kwargs): super(DojoReport, self).__init__(*args, **kwargs) for trial in self.ALL_TRIALS: # Convert ecut to float and build an OrderedDict (results are indexed by ecut in ascending order) try: d = self[trial] except KeyError: continue ecuts_keys = sorted([(float(k), k) for k in d], key=lambda t:t[0]) ord = OrderedDict([(t[0], d[t[1]]) for t in ecuts_keys]) self[trial] = ord def __str__(self): stream = six.moves.StringIO() pprint.pprint(self, stream=stream, indent=2, width=80) return stream.getvalue() def has_exceptions(self): problems = {} for trial in self.ALL_TRIALS: for accuracy in self.ALL_ACCURACIES: excs = self[trial][accuracy].get("_exceptions", None) if excs is not None: if trial not in problems: problems[trial] = {} problems[trial][accuracy] = excs return problems @property def symbol(self): """Chemical symbol.""" return self["symbol"] @property def element(self): return Element(self.symbol) @property def has_hints(self): """True if hints are present.""" return "hints" in self @lazy_property def ecuts(self): return np.array(self["ecuts"]) #@property #def is_validated(self) # return bool(self.get("validated", False)) @property def trials(self): """List of strings with the trials present in the report.""" return [k for k in self.keys() if k != "hints"] def has_trial(self, dojo_trial, ecut=None): """ True if the dojo_report contains dojo_trial with the given ecut. If ecut is not, we test if dojo_trial is present. """ if ecut is None: return dojo_trial in self else: try: self[dojo_trial][ecut] return True except KeyError: return False #def missing_ecuts(self, trial): # computed_ecuts = self[trial].keys() # return [e for e in self.ecuts if e not in computed_ecuts] #def add_ecuts(self, ecuts): # Be careful with the format here! it should be %.1f #new_ecuts = np.array(new_ecuts.split(",")) #def validate(self, hints): # Add md5 hash value # self["validated"] = True def check(self): """ check the DojoReport. Test if each trial contains an ecut entry. Return a dictionary trial: [missing_ecut] """ d = {} for trial in self.ALL_TRIALS: data = self.get(trial, None) if data is None: # Gbrv results do not contain noble gases so ignore the error if "gbrv" in trial and self.element.is_noble_gas: assert data is None continue d[trial] = self.ecuts else: computed_ecuts = self[trial].keys() for e in self.ecuts: if e not in computed_ecuts: if trial not in d: d[trial] = [] d[trial].append(e) if not d: assert len(computed_ecuts) == len(self.ecuts) return d #def get_dataframe(self, **kwargs): # """ # =========== =============== =============== =============== # Trial low normal high # =========== =============== =============== =============== # deltafactor value (rel_err) value (rel_err) value (rel_err) # gbrv_fcc ... ... ... # =========== =============== =============== =============== # """ # # Build the header # if kwargs.pop("with_hints", True): # ecut_acc = {acc: self["hints"][acc]["ecut"] for acc in self.ALL_ACCURACIES} # l = ["%s (%s Ha)" % (acc, ecut_acc[acc]) for acc in self.ALL_ACCURACIES] # else: # l = list(self.ALL_ACCURACIES) # rows = [["Trial"] + l] # for trial in self.ALL_TRIALS: # row = [trial] # for accuracy in self.ALL_ACCURACIES: # if not self.has_trial(trial, accuracy): # row.append("N/A") # else: # d = self[trial][accuracy] # value = d[self._TRIALS2KEY[trial]] # s = "%.4f" % value # row.append(s) # rows.append(row) # #import pandas as pd # #return pd.DataFrame(rows, index=names, columns=columns) # return rows def print_table(self, stream=sys.stdout): from monty.pprint import pprint_table pprint_table(self.get_dataframe(), out=stream) @add_fig_kwargs def plot_etotal_vs_ecut(self, ax=None, inv_ecut=False, **kwargs): """ plot the convergence of the total energy as function of the energy cutoff ecut Args: ax: matplotlib Axes, if ax is None a new figure is created. Returns: `matplotlib` figure. """ # Extract the total energy of the AE relaxed structure (4). d = OrderedDict([(ecut, data["etotals"][4]) for ecut, data in self["deltafactor"].items()]) # Ecut mesh in Ha ecuts = np.array(d.keys()) ecut_min, ecut_max = np.min(ecuts), np.max(ecuts) # Energies per atom in meV and difference wrt 'converged' value num_sites = [v["num_sites"] for v in self["deltafactor"].values()][0] etotals_mev = np.array([d[e] for e in ecuts]) * 1000 / num_sites ediffs = etotals_mev - etotals_mev[-1] ax, fig, plt = get_ax_fig_plt(ax) #ax.yaxis.set_view_interval(-5, 5) lines, legends = [], [] xs = 1/ecuts if inv_ecut else ecuts ys = etotals_mev if inv_ecut else ediffs line, = ax.plot(xs, ys, "-->", color="blue", linewidth=3.0, markersize=15) lines.append(line) label = kwargs.pop("label", None) if label is not None: ax.legend(lines, [label], loc='best', shadow=True) high_hint = self["ppgen_hints"]["high"]["ecut"] #ax.vlines(high_hint, min(ediffs), max(ediffs)) #ax.vlines(high_hint, 0.5, 1.5) #ax.scatter([high_hint], [1.0], s=20) #, c='b', marker='o', cmap=None, norm=None) #ax.arrow(high_hint, 1, 0, 0.2, head_width=0.05, head_length=0.1, fc='k', ec='k',head_starts_at_zero=False) #ax.hlines(5, ecut_min, ecut_max, label="5.0") #ax.hlines(1, ecut_min, ecut_max, label="1.0") #ax.hlines(0.5, ecut_min, ecut_max, label="0.2") # Set xticks and labels. ax.grid(True) ax.set_xlabel("Ecut [Ha]") ax.set_xticks(xs) ax.set_ylabel("Delta Etotal/natom [meV]") #ax.set_xlim(0, max(xs)) # Use logscale if possible. if all(ediffs[:-1] > 0): ax.set_yscale("log") ax.set_xlim(xs[0]-1, xs[-2]+1) return fig @add_fig_kwargs def plot_deltafactor_eos(self, ax=None, **kwargs): """ plot the EOS computed with the deltafactor setup. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. ================ ============================================================== kwargs Meaning ================ ============================================================== cmap Color map. default `jet` ================ ============================================================== Returns: `matplotlib` figure. """ ax, fig, plt = get_ax_fig_plt(ax) trial = "deltafactor" ecuts = self[trial].keys() num_ecuts = len(ecuts) cmap = kwargs.pop("cmap", None) if cmap is None: cmap = plt.get_cmap("jet") for i, ecut in enumerate(ecuts): d = self[trial][ecut] num_sites, volumes, etotals = d["num_sites"], np.array(d["volumes"]), np.array(d["etotals"]) # Use same fit as the one employed for the deltafactor. eos_fit = EOS.DeltaFactor().fit(volumes/num_sites, etotals/num_sites) label = "ecut %.1f" % ecut if i % 2 == 0 else "" label = "ecut %.1f" % ecut eos_fit.plot(ax=ax, text=False, label=label, color=cmap(i/num_ecuts, alpha=1), show=False) return fig def get_ecut_dfactprime(self): data = self["deltafactor"] ecuts, values= data.keys(), [] values = np.array([data[e]["dfactprime_meV"] for e in ecuts]) return np.array(ecuts), values def compute_hints(self): ecuts, dfacts = self.get_ecut_dfactprime() abs_diffs = np.abs((dfacts - dfacts[-1])) #print(list(zip(ecuts, dfacts))) #print(abs_diffs) hints = 3 * [None] for ecut, adiff in zip(ecuts, abs_diffs): for i in range(3): if adiff <= self.ATOLS[i] and hints[i] is None: hints[i] = ecut return hints @add_fig_kwargs def plot_deltafactor_convergence(self, code="WIEN2k", what=None, ax_list=None, **kwargs): """ plot the convergence of the deltafactor parameters wrt ecut. Args: code: Reference code ax_list: List of matplotlib Axes, if ax_list is None a new figure is created Returns: `matplotlib` figure. """ all = ["dfact_meV", "dfactprime_meV", "v0", "b0_GPa", "b1"] if what is None: keys = all else: what = list_strings(what) if what[0].startswith("-"): # Exclude keys #print([type(w) for w in what]) what = [w[1:] for w in what] keys = [k for k in all if k not in what] else: keys = what # get reference entry from pseudo_dojo.refdata.deltafactor import df_database reference = df_database().get_entry(symbol=self.symbol, code=code) d = self["deltafactor"] ecuts = d.keys() import matplotlib.pyplot as plt if ax_list is None: fig, ax_list = plt.subplots(nrows=len(keys), ncols=1, sharex=True, squeeze=False) ax_list = ax_list.ravel() else: fig = plt.gcf() #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(keys), ncols=1, sharex=True, squeeze=False) if len(keys) != len(ax_list): raise ValueError("len(keys)=%s != len(ax_list)=%s" % (len(keys), len(ax_list))) for i, (ax, key) in enumerate(zip(ax_list, keys)): values = np.array([float(d[ecut][key]) for ecut in ecuts]) #try: refval = getattr(reference, key) #except AttributeError: # refval = 0.0 # Plot difference pseudo - ref. ax.plot(ecuts, values - refval, "bo-") ax.grid(True) ax.set_ylabel("$\Delta$" + key) if i == len(keys) - 1: ax.set_xlabel("Ecut [Ha]") if key == "dfactprime_meV": # Add horizontal lines (used to find hints for ecut). last = values[-1] xmin, xmax = min(ecuts), max(ecuts) for pad, color in zip(self.ATOLS, ("green", "red", "violet")): ax.hlines(y=last + pad, xmin=xmin, xmax=xmax, colors=color, linewidth=1, linestyles='dotted') ax.hlines(y=last - pad, xmin=xmin, xmax=xmax, colors=color, linewidth=1, linestyles='dotted') return fig @add_fig_kwargs def plot_gbrv_eos(self, struct_type, ax=None, **kwargs): """ Uses Matplotlib to plot the EOS computed with the GBRV setup Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. ================ ============================================================== kwargs Meaning ================ ============================================================== cmap Color map. default `jet` ================ ============================================================== Returns: `matplotlib` figure or None if the GBRV test is not present """ ax, fig, plt = get_ax_fig_plt(ax) trial = "gbrv_" + struct_type # Handle missing entries: noble gases, Hg ... if trial not in self: return None ecuts = self[trial].keys() num_ecuts = len(ecuts) cmap = kwargs.pop("cmap", None) if cmap is None: cmap = plt.get_cmap("jet") for i, ecut in enumerate(ecuts): d = self[trial][ecut] volumes, etotals = np.array(d["volumes"]), np.array(d["etotals"]) eos_fit = EOS.Quadratic().fit(volumes, etotals) label = "ecut %.1f" % ecut if i % 2 == 0 else "" label = "ecut %.1f" % ecut eos_fit.plot(ax=ax, text=False, label=label, color=cmap(i/num_ecuts, alpha=1), show=False) return fig @add_fig_kwargs def plot_gbrv_convergence(self, ax_list=None, **kwargs): """ Uses Matplotlib to plot the convergence of the GBRV parameters wrt ecut. Args: ax_list: List of matplotlib Axes, if ax_list is None a new figure is created ================ ============================================================== kwargs Meaning ================ ============================================================== ================ ============================================================== Returns: `matplotlib` figure. """ import matplotlib.pyplot as plt stypes = ("fcc", "bcc") if ax_list is None: fig, ax_list = plt.subplots(nrows=len(stypes), ncols=1, sharex=True, squeeze=False) ax_list = ax_list.ravel() else: fig = plt.gcf() #ax_list, fig, plt = get_axarray_fig_plt(ax_list, nrows=len(stypes), ncols=1, sharex=True, squeeze=False) if len(stypes) != len(ax_list): raise ValueError("len(stypes)=%s != len(ax_list)=%s" % (len(stypes), len(ax_list))) for i, (ax, stype) in enumerate(zip(ax_list, stypes)): trial = "gbrv_" + stype d = self[trial] ecuts = d.keys() values = np.array([float(d[ecut]["a0_rel_err"]) for ecut in ecuts]) ax.grid(True) ax.set_ylabel("$\Delta$" + trial + "a0_rel_err") # Plot difference pseudo - ref. ax.plot(ecuts, values, "bo-") #ax.hlines(y=0.0, xmin=min(ecuts), xmax=max(ecuts), color="red") if i == len(ax_list) - 1: ax.set_xlabel("Ecut [Ha]") return fig
Dioptas/pymatgen
pymatgen/io/abinitio/pseudos.py
Python
mit
90,927
[ "ABINIT", "WIEN2k", "pymatgen" ]
0e87ca095816223a4096315172bef33b0a292f22e8547d68fb19cd6e1b30da64