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
########################################################################### # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################### # # This code generated (see starthinker/scripts for possible source): # - Command: "python starthinker_ui/manage.py airflow" # ########################################################################### ''' -------------------------------------------------------------- Before running this Airflow module... Install StarThinker in cloud composer ( recommended ): From Release: pip install starthinker From Open Source: pip install git+https://github.com/google/starthinker Or push local code to the cloud composer plugins directory ( if pushing local code changes ): source install/deploy.sh 4) Composer Menu l) Install All -------------------------------------------------------------- If any recipe task has "auth" set to "user" add user credentials: 1. Ensure an RECIPE['setup']['auth']['user'] = [User Credentials JSON] OR 1. Visit Airflow UI > Admin > Connections. 2. Add an Entry called "starthinker_user", fill in the following fields. Last step paste JSON from authentication. - Conn Type: Google Cloud Platform - Project: Get from https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md - Keyfile JSON: Get from: https://github.com/google/starthinker/blob/master/tutorials/deploy_commandline.md#optional-setup-user-credentials -------------------------------------------------------------- If any recipe task has "auth" set to "service" add service credentials: 1. Ensure an RECIPE['setup']['auth']['service'] = [Service Credentials JSON] OR 1. Visit Airflow UI > Admin > Connections. 2. Add an Entry called "starthinker_service", fill in the following fields. Last step paste JSON from authentication. - Conn Type: Google Cloud Platform - Project: Get from https://github.com/google/starthinker/blob/master/tutorials/cloud_project.md - Keyfile JSON: Get from: https://github.com/google/starthinker/blob/master/tutorials/cloud_service.md -------------------------------------------------------------- SA360 Web Query Report Download SA360 reports into a Google Sheet. - Add this card to a recipe and save it. - Then click Run Now to deploy. - Follow the 1-instructions for setup. 1-instructions: https://docs.google.com/spreadsheets/d/1S9os1VO3dBW_EUFvAq4SxlxddZYAdUkvr5H9iTPQT_s/edit?resourcekey=0-jdR3mdYYWSVSAEmwuxMKbQ#gid=0 -------------------------------------------------------------- This StarThinker DAG can be extended with any additional tasks from the following sources: - https://google.github.io/starthinker/ - https://github.com/google/starthinker/tree/master/dags ''' from starthinker.airflow.factory import DAG_Factory INPUTS = { 'recipe_name':'', # Name of document to deploy to. } RECIPE = { 'setup':{ 'day':[ ], 'hour':[ ] }, 'tasks':[ { 'drive':{ 'auth':'user', 'hour':[ ], 'copy':{ 'source':'https://docs.google.com/spreadsheets/d/1S9os1VO3dBW_EUFvAq4SxlxddZYAdUkvr5H9iTPQT_s/edit?resourcekey=0-jdR3mdYYWSVSAEmwuxMKbQ#gid=0', 'destination':{'field':{'name':'recipe_name','prefix':'CM User Editor For ','kind':'string','order':1,'description':'Name of document to deploy to.','default':''}} } } } ] } dag_maker = DAG_Factory('sa360_web_query', RECIPE, INPUTS) dag = dag_maker.generate() if __name__ == "__main__": dag_maker.print_commandline()
google/starthinker
dags/sa360_web_query_dag.py
Python
apache-2.0
4,184
[ "VisIt" ]
cc8ef572d41cf6fb7573707eb4402373ca6ea7ff670b6f3d4efd1f125fbe44d3
#!/usr/bin/env python # coding: utf-8 # # Advanced: Convert Posterior Distributions from EMCEE # # **IMPORTANT**: this tutorial assumes basic knowledge (and uses a file resulting from) the [emcee tutorial](./emcee.ipynb). # # **NOTE**: a bug in the latex labels when *converting to univariate distributions* was fixed in 2.3.12. Running this notebook on earlier versions will raise an error near the end. # ## Setup # # Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). # In[1]: #!pip install -I "phoebe>=2.3,<2.4" # In[2]: import phoebe from phoebe import u # units import numpy as np logger = phoebe.logger('error') # We'll then start with the bundle from the end of the [emcee tutorial](./emcee.ipynb). If you're running this notebook locally, you will need to run that first to create the `emcee_advanced_tutorials.bundle` file that we will use here. # In[3]: b = phoebe.load('emcee_advanced_tutorials.bundle') # # how posteriors are represented # # The emcee solution object contains all the samples from all chains during the MCMC run. This is then "trimmed" based on the set or passed values of `burnin`, `thin`, and `lnprob_cutoff` to create a [distl MVSamples](https://distl.readthedocs.io/en/latest/api/MVSamples/) object - which is capable of plotting the histogram representation of all these samples as a corner plot, while still retaining (and ultimately drawing from) the full underlying set of samples. This is the most "true" representation of the underlying information, but requires maintaining the full set of "trimmed" samples and can be expensive for a large number of walkers/iterations. # # We can access the underlying [distl MVSamples](https://distl.readthedocs.io/en/latest/api/MVSamples/) object with [b.get_distribution_collection](../api/phoebe.frontend.bundle.Bundle.get_distribution_collection.md) and can see that it has a [dc.samples](https://distl.readthedocs.io/en/latest/api/MVSamples.samples/) property containing this underlying data. # In[4]: dc, twigs = b.get_distribution_collection(solution='emcee_sol') # In[5]: dc # We could convert this object manually using distl, using [dc.to_mvgaussian](https://distl.readthedocs.io/en/latest/api/MVSamples.to_mvgaussian/), for example. This is much more lightweight, as it only stores the means and covariance matrix, but is really only fair if the samples can be well-represented by a multivariate gaussian. # In[6]: dc.to_mvgaussian() # PHOEBE provides an interface to do these conversions (using distl) under-the-hood so that all the plotting and adopting infrastructure still works seemlesly. This brings us to the `distributions_convert` parameter. # # distributions_convert parameter # # The `distributions_convert` parameter (or as an override keyword argument) will convert the underlying [distl MVSamples](https://distl.readthedocs.io/en/latest/api/MVSamples/) object to the desired distribution type whenever calling [adopt_solution](../api/phoebe.frontend.bundle.Bundle.adopt_solution.md), [get_distribution_collection](../api/phoebe.frontend.bundle.Bundle.get_distribution_collection.md), [sample_distribution_collection](../api/phoebe.frontend.bundle.Bundle.sample_distribution_collection.md), [uncertainties_from_distribution_collection](../api/phoebe.frontend.bundle.Bundle.uncertainties_from_distribution_collection.md), [plot_distribution_collection](../api/phoebe.frontend.bundle.Bundle.plot_distribution_collection.md), or [plot](../phoebe.parameters.ParameterSet.plot.md) (with `style='corner'` or `'failed'`). # # If we examine the `distributions_convert` parameter (in the emcee solution), we can see its description and available choices. # In[7]: print(b.get_parameter(qualifier='distributions_convert', solution='emcee_sol')) # If we don't pass `distributions_convert` to `plot`, then the value from the parameter will be used. In this case, it will keep the distribution as a multivariate samples. # In[8]: _ = b.plot(solution='emcee_sol', style='corner', show=True) # By converting to [MVHistogram](https://distl.readthedocs.io/en/latest/api/MVHistogram/), the data is stored as an N-dimensional histogram. In this case, with a 6 parameters and a default of 20 bins per dimension (when `distributions_convert` is set to `'mvhistogram'` or `'histogram'`, a new `distributions_bins` parameter becomes visible to override the default), this is actually more expensive to store than the underlying samples. But in cases with few parameters and a large number of walkers/iterations, the binned version may be cheaper to manage. # In[9]: _ = b.plot(solution='emcee_sol', style='corner', distributions_convert='mvhistogram', show=True) # By converting to [MVGaussian](https://distl.readthedocs.io/en/latest/api/MVGaussian/), the data is stored as means and a covariance matrix. This is extremely cheap to store, but should **only** be used if the underlying distribution is gaussian (probably not the case here, especially for the last parameter). # In[10]: _ = b.plot(solution='emcee_sol', style='corner', distributions_convert='mvgaussian', show=True) # Even cheaper yet, we can convert to non-multivariate distribution types and drop information about the covariances between parameters. Here if we convert to a collection of [Gaussian](https://distl.readthedocs.io/en/latest/api/Gaussian/) distributions, only the means and sigmas are stored. # # **NOTE**: a bug in the latex labels when *converting to univariate distributions* was fixed in 2.3.12. Running this notebook on earlier versions will raise an error near the end # In[11]: _ = b.plot(solution='emcee_sol', style='corner', distributions_convert='gaussian', show=True) # If we look at the actual [distl DistributionCollection](https://distl.readthedocs.io/en/latest/api/DistributionCollection/) object, we can see that it now contains a list of independent gaussian distributions. # In[12]: dc, twigs = b.get_distribution_collection(solution='emcee_sol', distributions_convert='gaussian') # In[13]: print(dc) # In[14]: print(dc.dists) # ## See Also # # See the following for even more advanced use cases of emcee. # # * [Advanced: continuing emcee from a previous run](./emcee_continue_from.ipynb) # * [Advanced: resampling emcee from a previous run](./emcee_resample.ipynb)
phoebe-project/phoebe2-docs
2.3/tutorials/emcee_distributions_convert.py
Python
gpl-3.0
6,472
[ "Gaussian" ]
f356966ed3d900aef401960658088915657e8a6e5add4ffbf762533e657045aa
#!/usr/bin/env python # -*- coding:utf-8 mode:python; tab-width:4; indent-tabs-mode:nil; py-indent-offset:4 -*- ## """ test_energy_semiempirical_mopac7 ~~~~~~~~~~~~~~ Test MOPAC 7 semiempirical implementation for energy. """ import sys import geoprep from adapters import mopac7 from tests.common_testcode import runSuite from tests import energy_semiempirical as es from tests import reference_values class MOPACEnergyTestCase(es.SemiempiricalEnergyTestCase): def setUp(self): self.G = geoprep.Geotool() self.C = mopac7.Mopac7() def test_energy_mindo3_methane(self): methane = self.G.make_system("C") job = self.C.make_energy_job(methane, "semiempirical:mindo/3") job.run() self.assertNearMatch(reference_values.methane_mindo3_hof, job.heat_of_formation, places=5) def runTests(): try: test_name = sys.argv[1] except IndexError: test_name = None if test_name: result = runSuite(MOPACEnergyTestCase, name = test_name) else: result = runSuite(MOPACEnergyTestCase) return result if __name__ == "__main__": runTests()
mattbernst/polyhartree
tests/test_energy_semiempirical_mopac7.py
Python
gpl-3.0
1,188
[ "MOPAC" ]
340c67ea456c1d8fe308e66a8cef480b662bd68f21914e25e1202c935720b028
""" ASE interface to pmd. """ from __future__ import print_function import os import subprocess import numpy as np from ase.calculators.calculator import FileIOCalculator,Calculator import nappy from nappy.interface.ase.pmdio import get_fmvs from nappy.napsys import NAPSystem __author__ = "Ryo KOBAYASHI" __version__ = "160605" __LICENSE__ = "MIT" CALC_END_MARK = "Job finished " some_changes = ['positions', 'numbers', 'cell',] class PMD(FileIOCalculator): """ Class for PMD calculation for ASE. calc = PMD(label='pmd') """ implemented_properties = ['energy', 'forces', 'relaxed_scaled_positions', 'stress', 'num_step_relax', 'relaxed_cell'] command = 'pmd' default_parameters = { 'num_nodes_x': -1, 'num_nodes_y': -1, 'num_nodes_z': -1, 'num_omp_threads': 4, 'io_format': 'ascii', 'print_level': 1, 'time_interval': 1.0, 'num_iteration': 0, 'min_iteration': 0, 'num_out_energy': 10, 'flag_out_pmd': 2, 'num_out_pmd': 1, 'flag_sort': 1, 'force_type': None, 'cutoff_radius': 5.0, 'cutoff_buffer': 0.0, 'flag_damping': 0, 'damping_coeff': 0.95, 'converge_eps': 1e-4, 'converge_num': 3, 'initial_temperature': -10.0, 'final_temperature': -10.0, 'temperature_control': 'none', 'temperature_target': [300.0, 100.0,], 'temperature_relax_time': 100.0, 'flag_temp_dist': 'F', 'factor_direction':[[1.0, 1.0, 1.0], [1.0, 0.0, 1.0]], 'stress_control': 'none', 'pressure_target': 0.0, 'stress_target': [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], 'stress_relax_time': 20.0, 'flag_compute_stress': 'T', # 'mass': {'W':183.14, 'H':1.008,}, 'zload_type': 'none', 'final_strain': 0.0, 'boundary': 'ppp', } def __init__(self, restart=None, ignore_bad_restart_file=False, label='pmd', atoms=None, command='pmd > out.pmd', dimension=(True,True,True), specorder=None, **kwargs): """Construct PMD-calculator object. Parameters ========== label: str Prefix to use for filenames (in.label, erg.label, ...). [Default: 'pmd'] command: str Command string to execute pmd. [Default: 'pmd > out.pmd'] force_type: str or tuple/list Force fields to be used, which must be set. [Default: None] specorder: list Order of species. This is probably very important, since the order of species is usually fixed in pmd whereas not in ASE atoms object. [Default: None] Examples ======== Use default values: >>> h = Atoms('H', calculator=PMD(label='pmd',force_type='NN')) >>> e = h.get_potential_energy() """ Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) if label not in ['pmd']: raise RuntimeError('label must be pmd.') if self.parameters['force_type'] is None: raise RuntimeError('force_type must be specified.') if command is None: self.command = self.label+' > out.'+self.label elif '>' in command: self.command = command.split('>')[0] +' > out.'+self.label else: self.command = command +' > out.'+self.label self.specorder= specorder self.dimension = dimension def set(self, **kwargs): changed_parameters = FileIOCalculator.set(self, **kwargs) if changed_parameters: self.reset() def calculate(self, atoms=None, properties=['energy'], system_changes=some_changes): Calculator.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) olddir = os.getcwd() try: os.chdir(self.directory) errorcode = subprocess.call(self.command, shell=True) finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results() def relax(self, atoms=None, properties=['energy'], system_changes=some_changes, flag_damping=1,damping_coeff=0.95, converge_eps=1.0e-3,num_iteration=100,min_iteration=5, converge_num=3,time_interval=0.5, initial_temperature=10.0, stress_control='none', pressure_target=0.0, stress_target=[[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]]): """ Relax atom positions by running damped MD in pmd instead of using optimize module in ASE. """ self.set(flag_damping=flag_damping, damping_coeff=damping_coeff, converge_eps=converge_eps, num_iteration=num_iteration, min_iteration=min_iteration, num_out_energy=num_iteration, converge_num=converge_num, time_interval=time_interval, initial_temperature=initial_temperature, stress_control=stress_control, stress_target=stress_target, flag_sort=1) Calculator.calculate(self, atoms, properties, system_changes) self.write_input(self.atoms, properties, system_changes) olddir = os.getcwd() try: os.chdir(self.directory) errorcode = subprocess.call(self.command, shell=True) finally: os.chdir(olddir) if errorcode: raise RuntimeError('%s returned an error: %d' % (self.name, errorcode)) self.read_results(relax=True) def write_input(self, atoms, properties=None, system_changes=None): """Write input parameters to in.pmd file.""" FileIOCalculator.write_input(self, atoms, properties, system_changes) if self.label == 'pmd': infname = 'in.pmd' # write_pmd(atoms,fname='pmdini',specorder=self.specorder) #nsys = NAPSystem.from_ase_atoms(atoms,specorder=self.specorder) nsys = nappy.io.from_ase(atoms,specorder=self.specorder) nappy.io.write_pmd(nsys,fname='pmdini') with open(infname,'w') as f: fmvs,ifmvs = get_fmvs(atoms) for i in range(len(fmvs)): for ii in range(3): if fmvs[i][ii] > 0.1 and not self.dimension[ii]: fmvs[i][ii] = 0.0 f.write(get_input_txt(self.parameters,fmvs)) def read_results(self,relax=False): """ Only erg.pmd and frc.pmd are to be read. """ outfname= 'out.'+self.label ergfname= 'erg.'+self.label frcfname= 'frc.'+self.label strfname= 'strs.'+self.label if not os.path.exists(outfname): raise RuntimeError(outfname+' does not exists.') if not os.path.exists(ergfname): raise RuntimeError(ergfname+' does not exists.') if not os.path.exists(frcfname): raise RuntimeError(frcfname+' does not exists.') if not os.path.exists(strfname): print('Warning: '+strfname+' does not exists.') self.results={ k : None for k in self.implemented_properties} fout= open(outfname,'r') lines= fout.readlines() if CALC_END_MARK not in lines[-1]: raise RuntimeError(self.label+' seems to stop somewhere..') if relax: relax_converged = False num_step_relax = -1 for line in lines: if 'Damped MD converged with' in line: relax_converged = True num_step_relax = int(line.split()[4]) break if not relax_converged: print('') print('** Warning: pmd relaxation does not' +\ ' seem to be converged**') print('') self.results['num_step_relax'] = num_step_relax fout.close() with open(ergfname,'r') as f: erg = float(f.readline().split()[0]) self.results['energy'] = erg with open(frcfname,'r') as f: num= int(f.readline().split()[0]) frcs= np.zeros((num,3)) for i in range(num): data= [ float(x) for x in f.readline().split() ] frcs[i,0:3] = data[0:3] self.results['forces'] = frcs if os.path.exists(strfname): try: with open(strfname,'r') as f: strs = np.array([ float(x) for x in f.readline().split() ]) self.results['stress'] = strs except: self.results['srress'] = None if relax: posfile = 'pmdfin' #nsys = NAPSystem(fname=posfile,specorder=self.specorder) nsys = nappy.io.read(fname=posfile,specorder=self.specorder) #tmpatoms = read_pmd(fname=posfile,specorder=self.specorder) tmpatoms = nsys.to_ase_atoms() self.results['relaxed_scaled_positions'] \ = tmpatoms.get_scaled_positions() self.results['relaxed_cell'] = tmpatoms.get_cell() def get_relaxed_scaled_positions(self): return self.results['relaxed_scaled_positions'] def get_relaxed_cell(self): return self.results['relaxed_cell'] def get_input_txt(params,fmvs): txt = '' order=['num_nodes_x','num_nodes_y','num_nodes_z','num_omp_threads','', 'io_format','print_level','', 'time_interval','num_iteration','min_iteration','num_out_energy','', 'flag_out_pmd','num_out_pmd','flag_sort','', 'force_type','cutoff_radius','cutoff_buffer','', 'flag_damping','damping_coeff','converge_eps','converge_num','', 'initial_temperature','final_temperature', 'temperature_control','temperature_target', 'temperature_relax_time','flag_temp_dist','', 'factor_direction','', 'stress_control','pressure_target','stress_target', 'stress_relax_time','flag_compute_stress','', 'overlay','overlay_type','', 'zload_type','final_strain','', 'boundary'] int_keys=['num_nodes_x','num_nodes_y','num_nodes_z','num_omp_threads', 'num_iteration','num_out_energy','flag_out_pmd', 'num_out_pmd','flag_damping','print_level', 'converge_num','min_iteration','flag_sort'] float_keys=['time_interval','cutoff_radius','cutoff_buffer', 'damping_coeff','initial_temperature', 'final_temperature', 'temperature_relax_time','pressure_target', 'stress_relax_time','shear_stress', 'converge_eps','final_strain'] str_keys=['io_format','force_type','temperature_control', 'stress_control','flag_temp_dist', 'flag_compute_stress','zload_type','boundary', 'overlay_type'] for key in order: # special keys first if key == '': txt += '\n' elif key not in params: continue elif key == 'force_type': vals = params[key] txt += '{0:25s} '.format('force_type') if isinstance(vals,str): txt += ' {0:s}'.format(vals) elif type(vals) in (list,tuple): for v in vals: txt += ' {0:s}'.format(v) txt += '\n' elif key == 'temperature_target': vals = params[key] for i,v in enumerate(vals): txt += '{0:25s} {1:2d} {2:6.1f}\n'.format(key,i+1,v) elif key == 'factor_direction': # vals = params[key] vals= fmvs txt += '{0:25s} 3 {1:d}\n'.format(key,len(vals)) for i,v in enumerate(vals): txt += ' {0:6.2f} {1:6.2f} {2:6.2f}\n'.format(v[0],v[1],v[2]) elif key == 'stress_target': vals = params[key] txt += '{0:25s}\n'.format(key) for i in range(3): v = vals[i] txt += ' {0:6.2f} {1:6.2f} {2:6.2f}\n'.format(v[0],v[1],v[2]) # elif key == 'mass': # masses = params[key] # for k,v in masses.items(): # txt += '{0:25s} {1:3s} {2:10.4f}\n'.format(key,k,v) elif key == 'converge_eps': txt += '{0:25s} {1:10.1e}\n'.format(key,params[key]) elif key == 'overlay': ols = params[key] for k,v in ols.items(): txt += '{0:25s} {1:3s} {2:6.2f} {3:6.2f}\n'.format(key,k,v[0],v[1]) elif key in int_keys: txt += '{0:25s} {1:3d}\n'.format(key,params[key]) elif key in float_keys: if key == 'cutoff_radius' or key == 'damping_coeff': txt += '{0:25s} {1:8.4f}\n'.format(key,params[key]) else: txt += '{0:25s} {1:6.1f}\n'.format(key,params[key]) elif key in str_keys: txt += '{0:25s} {1:s}\n'.format(key,params[key]) else: raise RuntimeError('Input parameter '+key+' is not defined.') return txt
ryokbys/nap
nappy/interface/ase/pmdrun.py
Python
mit
13,768
[ "ASE" ]
6bc62bada7ebc8fa38247039a22cd67c435ca81a1c0f0eb152ccb8b090ddc286
# gridDataFormats --- python modules to read and write gridded data # Copyright (c) 2009-2014 Oliver Beckstein <orbeckst@gmail.com> # Released under the GNU Lesser General Public License, version 3 or later. # # Part of the documentation and format specification: Copyright CSC, 2005 """ :mod:`gOpenMol` --- the gOpenMol plt format =========================================== .. _gOpenMol: http://www.csc.fi/english/pages/g0penMol The module provides a simple implementation of a reader for gOpenMol_ *plt* files. Plt files are binary files. The :class:`Plt` reader tries to guess the endianess of the file, but this can fail (with a :exc:`TypeError`); you are on your own in this case. Only the reader is implemented. If you want to write gridded data use a format that is more standard, such as OpenDX (see :mod:`OpenDX`). Background ---------- gOpenMol http://www.csc.fi/english/pages/g0penMol plt format. Used to be documented at http://www.csc.fi/gopenmol/developers/plt_format.phtml but currently this is only accessible through the internet archive at http://web.archive.org/web/20061011125817/http://www.csc.fi/gopenmol/developers/plt_format.phtml Grid data plt file format ------------------------- Copyright CSC, 2005. Last modified: September 23, 2003 09:18:50 Plot file (plt) format The plot files are regular 3D grid files for plotting of molecular orbitals, electron densities or other molecular properties. The plot files are produced by several programs. It is also possible to format/unformat plot files using the pltfile program in the utility directory. It is also possible to produce plot files with external (own) programs. Produce first a formatted text file and use then the pltfile program to unformat the file for gOpenMol. The format for the plot files are very simple and a description of the format can be found elsewhere in this manual. gOpenMol can read binary plot files from different hardware platforms independent of the system type (little or big endian machines). Format of the binary ``*.plt`` file ................................... The ``*.plt`` file binary and formatted file formats are very simple but please observe that unformatted files written with a FORTRAN program are not pure binary files because there are file records between the values while pure binary files do not have any records between the values. gOpenMol should be able to figure out if the file is pure binary or FORTRAN unformatted but it is not very well tested. Binary ``*.plt`` (grid) file format ................................... Record number and meaning:: #1: Integer, rank value must always be = 3 #2: Integer, possible values are 1 ... 50. This value is not used but it can be used to define the type of surface! Values used (you can use your own value between 1... 50): 1: VSS surface 2: Orbital/density surface 3: Probe surface 200: Gaussian 94/98 201: Jaguar 202: Gamess 203: AutoDock 204: Delphi/Insight 205: Grid Value 100 is reserved for grid data coming from OpenMol! #3: Integer, number of points in z direction #4: Integer, number of points in y direction #5: Integer, number of points in x direction #6: Float, zmin value #7: Float, zmax value #8: Float, ymin value #9: Float, ymax value #10: Float, xmin value #11: Float, xmax value #12 ... Float, grid data values running (x is inner loop, then y and last z): 1. Loop in the z direction 2. Loop in the y direction 3. Loop in the x direction Example:: nx=2 ny=1 nz=3 0,0,0 1,0,0 y=0, z=0 0,0,1 1,0,0 y=0, z=1 0,0,2 1,0,2 y=0, z=2 The formatted (the first few lines) file can look like:: 3 2 65 65 65 -3.300000e+001 3.200000e+001 -3.300000e+001 3.200000e+001 -3.300000e+001 3.200000e+001 -1.625609e+001 -1.644741e+001 -1.663923e+001 -1.683115e+001 -1.702274e+001 -1.721340e+001 -1.740280e+001 -1.759018e+001 -1.777478e+001 -1.795639e+001 -1.813387e+001 -1.830635e+001 ... Formatted ``*.plt`` (grid) file format ...................................... Line numbers and variables on the line:: line #1: Integer, Integer. Rank and type of surface (rank is always = 3) line #2: Integer, Integer, Integer. Zdim, Ydim, Xdim (number of points in the z,y,x directions) line #3: Float, Float, Float, Float, Float, Float. Zmin, Zmax, Ymin, Ymax, Xmin,Xmax (min and max values) line #4: ... Float. Grid data values running (x is inner loop, then y and last z) with one or several values per line: 1. Loop in the z direction 2. Loop in the y direction 3. Loop in the x direction Classes ------- """ from __future__ import with_statement import warnings import struct import numpy class Record(object): def __init__(self, key, bintype, values=None): self.key = key self.bintype = bintype self.values = values # dict(value='comment', ...) def is_legal(self, value): if self.values is None: return True return value in self.values def is_legal_dict(self, d): return self.is_legal(d[self.key]) def __repr__(self): return "Record(%(key)r,%(bintype)r,...)" % vars(self) class Plt(object): """A class to represent a gOpenMol_ plt file. Only reading is implemented; either supply a filename to the constructor >>> G = Plt(filename) or load the file with the read method >>> G = Plt() >>> G.read(filename) The data is held in :attr:`GOpenMol.array` and all header information is in the dict :attr:`GOpenMol.header`. :attr:`Plt.shape` D-tuplet describing size in each dimension :attr:`Plt.origin` coordinates of the centre of the grid cell with index 0,0,...,0 :attr:`Plt.delta` DxD array describing the deltas """ _header_struct = (Record('rank', 'I', {3:'dimension'}), Record('surface','I', {1: 'VSS surface', 2: 'Orbital/density surface', 3: 'Probe surface', 42: 'gridcount', 100: 'OpenMol', 200: 'Gaussian 94/98', 201: 'Jaguar', 202: 'Gamess', 203: 'AutoDock', 204: 'Delphi/Insight', 205: 'Grid', }), # update in init with all user defined values Record('nz', 'I'), Record('ny', 'I'), Record('nx', 'I'), Record('zmin', 'f'), Record('zmax', 'f'), Record('ymin', 'f'), Record('ymax', 'f'), Record('xmin', 'f'), Record('xmax', 'f')) _data_bintype = 'f' # write(&value,sizeof(float),1L,output); def __init__(self, filename=None): self.filename = filename # fix header_struct because I cannot do {...}.update() rec_surf = [r for r in self._header_struct if r.key == 'surface'][0] rec_surf.values.update(dict((k,'user-defined') for k in xrange(4,51) if k != 42)) # assemble format self._headerfmt = "".join([r.bintype for r in self._header_struct]) if not filename is None: self.read(filename) def read(self, filename): """Populate the instance from the plt file *filename*.""" from struct import calcsize, unpack if not filename is None: self.filename = filename with open(self.filename, 'rb') as plt: h = self.header = self._read_header(plt) nentries = h['nx'] * h['ny'] * h['nz'] # quick and dirty... slurp it all in one go datafmt = h['bsaflag']+str(nentries)+self._data_bintype a = numpy.array(unpack(datafmt, plt.read(calcsize(datafmt)))) self.header['filename'] = self.filename self.array = a.reshape(h['nz'], h['ny'], h['nx']).transpose() # unpack plt in reverse!! self.delta = self._delta() self.origin = numpy.array([h['xmin'], h['ymin'], h['zmin']]) + 0.5*numpy.diagonal(self.delta) self.rank = h['rank'] @property def shape(self): return self.array.shape @property def edges(self): """Edges of the grid cells, origin at centre of 0,0,..,0 grid cell. Only works for regular, orthonormal grids. """ return [self.delta[d,d] * numpy.arange(self.shape[d]+1) + self.origin[d]\ - 0.5*self.delta[d,d] for d in xrange(self.rank)] def _delta(self): h = self.header qmin = numpy.array([h['xmin'],h['ymin'],h['zmin']]) qmax = numpy.array([h['xmax'],h['ymax'],h['zmax']]) delta = numpy.abs(qmax - qmin) / self.shape return numpy.diag(delta) def _read_header(self, pltfile): """Read header bytes, try all possibilities for byte order/size/alignment.""" nheader = struct.calcsize(self._headerfmt) names = [r.key for r in self._header_struct] binheader = pltfile.read(nheader) def decode_header(bsaflag='@'): h = dict(zip(names, struct.unpack(bsaflag+self._headerfmt, binheader))) h['bsaflag'] = bsaflag return h for flag in '@=<>': # try all endinaness and alignment options until we find something that looks sensible header = decode_header(flag) if header['rank'] == 3: break # only legal value according to spec header = None if header is None: raise TypeError("Cannot decode header --- corrupted or wrong format?") for rec in self._header_struct: if not rec.is_legal_dict(header): warnings.warn("Key %s: Illegal value %r" % (rec.key, header[rec.key])) return header def histogramdd(self): """Return array data as (edges,grid), i.e. a numpy nD histogram.""" return (self.array, self.edges)
holocronweaver/GridDataFormats
gridData/gOpenMol.py
Python
gpl-3.0
10,392
[ "GAMESS", "Gaussian", "Jaguar" ]
5c91ea7da5fd137222fa5067126d1145cc889efe60c664796f59c5e4a7f6287d
#!/usr/bin/env python # extract HOT-region analysis from R script outputs! import sys import time import optparse import general import numpy import scipy import pickle import pdb import metrn import modencode import fasta import random import shutil import os from runner import * print "Command:", " ".join(sys.argv) print "Timestamp:", time.asctime(time.localtime()) # define a function to generate chromosome coordinates: def genomeCoords(chrms, chrm_size_dict): coord_dict = dict() coord_base = 1 for chrm in chrms: coord_dict[chrm] = [coord_base, coord_base + chrm_size_dict[chrm]] coord_base += chrm_size_dict[chrm] coord_base += 1 coord_min, coord_max = 1, coord_base return coord_dict, coord_min, coord_max, coord_dict """" define a function to generate region coordinates """ def regionCoords(chrms, region_size_dict, splitTag=":"): coord_dict, edge_dict = dict(), dict() coord_base = 1 for chrm in chrms: if chrm in region_size_dict: if not chrm in coord_dict: coord_dict[chrm] = dict() edgeStart = coord_base for start in sorted(region_size_dict[chrm]): for end in sorted(region_size_dict[chrm][start]): coordStart, coordStop = coord_base, coord_base + region_size_dict[chrm][start][end] if not coord_base in coord_dict[chrm]: coord_dict[chrm][coordStart] = dict() if not coordStop in coord_dict[chrm][coordStart]: coord_dict[chrm][coordStart][coordStop] = sorted([start, end]) coord_base += region_size_dict[chrm][start][end] coord_base += 1 edgeStop = coord_base edge_dict[chrm] = [edgeStart, edgeStop] coord_min, coord_max = 1, coord_base return coord_dict, coord_min, coord_max, edge_dict """ define a function to randomly select bases in the genome based on a coordinate dictionary """ def randomBase(coord_dict, coord_min, coord_max, edge_dict, mode="random.genomic"): coord = random.randrange(coord_min, coord_max) if mode == "random.genomic": for chrm in coord_dict: start, stop = coord_dict[chrm] if coord >= start and coord <= stop: return chrm, coord-start + 1 elif mode == "random.regions": for chrm in coord_dict: chrmStart, chrmStop = edge_dict[chrm] if coord >= chrmStart and coord <= chrmStop: for start in sorted(coord_dict[chrm]): if coord >= start and coord <= max(coord_dict[chrm][start].keys()): for stop in sorted(coord_dict[chrm][start]): if coord <= stop: start, stop = coord_dict[chrm][start][stop] return chrm, coord-start + 1 elif mode == "random.focused": for chrm in coord_dict: chrmStart, chrmStop = edge_dict[chrm] if coord >= chrmStart and coord <= chrmStop: start = random.choice(coord_dict[chrm].keys()) stop = random.choice(coord_dict[chrm][start].keys()) start, stop = coord_dict[chrm][start][stop] return chrm, coord-start + 1 """ define a function to... """ def indexColumns(infile, column, base="", header=True, extension=".idx", append=False, start=1, sep="\t"): index = start inlines = open(infile).readlines() outfile = open(infile + extension, "w") if header: header_line = inlines.pop(0) header_dict = general.build_header_dict(header_line, mode="line") column = header_dict[column] print >>outfile, header_line.strip() for inline in inlines: initems = inline.strip().split(sep) if append: outitems = initems[:column-1] + [base + str(index) + "." + initems[column]] + initems[column:] else: outitems = initems[:column-1] + [base + str(index)] + initems[column:] print >>outfile, sep.join(outitems) index += 1 outfile.close() """ define a function to count peaks in a gffkde output file """ def densityPeakCounter(indata, mode="file", gffkde="OFF"): if mode == "file": processed, inlines = list(), open(indata).readlines() elif mode == "list": processed, inlines = list(), indata for inline in inlines: if gffkde == "ON": for peakData in inline.strip().split("\t")[7].rstrip(";").split(";")[1:]: processed.append(peakData.split(",")[0]) else: for peakData in inline.strip().split("\t")[10].rstrip(";").split(";")[1:]: processed.append(peakData.split(",")[0]) return len(list(set(processed))) """ define a function to scan regions for peaks from the same dataset """ def gffkdeDuplicateScanner(indata, mode="file"): if mode == "file": processed, inlines = list(), open(indata).readlines() elif mode == "list": processed, inlines = list(), indata r, k = 0, 0 for inline in inlines: datasets = list() for peakData in inline.strip().split("\t")[7].rstrip(";").split(";")[1:]: processed.append(peakData.split(",")[0]) datasets.append(peakData.split(",")[0].split("_peaks_")[0]) if (len(datasets) - len(set(datasets))) > 0: duplicates = list() for dataset in sorted(list(set(datasets))): if datasets.count(dataset) > 1: duplicates.append(dataset) print len(duplicates), len(datasets) - len(set(datasets)), ", ".join(duplicates) k += 1 r += 1 return len(list(set(processed))), r, k, round(float(k)/r, 2) """ define a function to scan regions for peaks from the same dataset """ def gffkde2bed(indata, mode="file", outfile="", chrmID="chrm"): if mode == "file": processed, inlines = list(), open(indata).readlines() elif mode == "list": processed, inlines = list(), indata if outfile: f_output = open(outfile, "w") else: f_output = open(indata + ".bed", "w") k = 1 for inline in inlines: #IV InferredHS300bw HOTspot 59650 59950 1.00030548632118 . . 1,1;OP64_HLH-1_EM_yale_stn_peaks_Rank_1068,59800,1; chrm, method, feature, start, stop, score, strand, period, info = inline.strip().split("\t") feature = feature + "." + str(k) if chrmID == "feature": chrm, start, stop = feature, str(1), str(int(stop)-int(start)) rounded = str(round(numpy.ceil(float(score)))) print >>f_output, "\t".join([chrm, start, stop, feature, rounded, "+", score, info]) k += 1 f_output.close() """ define a function to scan regions for peaks from the same dataset """ def gffkde2sizes(indata, mode="file", outfile=""): if mode == "file": processed, inlines = list(), open(indata).readlines() elif mode == "list": processed, inlines = list(), indata if outfile: f_output = open(outfile, "w") else: f_output = open(indata + "_sizes.txt", "w") for inline in inlines: #IV InferredHS300bw HOTspot 59650 59950 1.00030548632118 . . 1,1;OP64_HLH-1_EM_yale_stn_peaks_Rank_1068,59800,1; chrm, method, feature, start, stop, score, strand, period, info = inline.strip().split("\t") feature = feature + "." + str(k) chrm, size = feature, stop print >>f_output, "\t".join([chrm, size]) k += 1 f_output.close() """ define a function that converts a local user path to SCG3 or GS server paths """ def serverPath(inpath, server="ON"): if server == "ON": return inpath.replace("/Users/claraya/", "/srv/gs1/projects/snyder/claraya/") elif server == "GS": return inpath.replace("/Users/claraya/", "/net/fields/vol1/home/araya/") def main(): parser = optparse.OptionParser() parser.add_option("--path", action = "store", type = "string", dest = "path", help = "Path from script to files") parser.add_option("--organism", action = "store", type = "string", dest = "organism", help = "Target organism for operations...", default="OFF") parser.add_option("--mode", action = "store", type = "string", dest = "mode", help = "Type of operations to be performed: scan or filter") parser.add_option("--peaks", action = "store", type = "string", dest = "peaks", help = "Basename for target peaks", default="OFF") parser.add_option("--infile", action = "store", type = "string", dest = "infile", help = "Input HOT-regions peak/density file") parser.add_option("--target", action = "store", type = "string", dest = "target", help = "How should the detail splitting be performed?", default="peaks") parser.add_option("--contribution", action = "store", type = "float", dest = "contribution", help = "Minimum contribution cutoff", default=0) parser.add_option("--significance", action = "store", type = "string", dest = "significance", help = "Significance density cutoff (mode:scan) or file of HOT regions to exclude (mode:filter)!", default="OFF") parser.add_option("--cutoff", action = "store", type = "string", dest = "cutoff", help = "Maximum density cutoff (mode:scan) or file of HOT regions to exclude (mode:filter)!", default="OFF") parser.add_option("--limits", action = "store", type = "string", dest = "limits", help = "Additional text cutoffs for detail filtering!", default="OFF") parser.add_option("--metric", action = "store", type = "string", dest = "metric", help = "Metric: occupancy, density, or complexity", default="occupancy") parser.add_option("--minOccupancy", action = "store", type = "string", dest = "minOccupancy", help = "Minimum occupancy required for filtering (mode:scan)", default=2) parser.add_option("--name", action = "store", type = "string", dest = "name", help = "Output file name-tag.", default="OFF") parser.add_option("--overlap", action = "store", type = "string", dest = "overlap", help = "Overlap comparison names", default="OFF") parser.add_option("--source", action = "store", type = "string", dest = "source", help = "Path of peaks to be filtered or other files...") parser.add_option("--contexts", action = "store", type = "string", dest = "contexts", help = "What contexts of development to track in 'temperature' mode.", default="total.extended") parser.add_option("--regions", action = "store", type = "string", dest = "regions", help = "Regions for Monte-Carlo simulations", default="OFF") parser.add_option("--start", action = "store", type = "int", dest = "start", help = "Start simulation index for Monte-Carlo simulations", default=1) parser.add_option("--stop", action = "store", type = "int", dest = "stop", help = "End simulation index for Monte-Carlo simulations", default=1000) parser.add_option("--total", action = "store", type = "int", dest = "total", help = "Total simulations (indexes) for Monte-Carlo simulations", default=1000) parser.add_option("--shuffle", action = "store", type = "string", dest = "shuffle", help = "Should region selection be size-based (OFF; slow) or shuffle (ON; faster)", default="ON") parser.add_option("--scramble", action = "store", type = "string", dest = "scramble", help = "Scramble regions in which to simulate peaks? Note that this can create overlapping regions so its best not to activate.", default="ON") parser.add_option("--adjust", action = "store", type = "string", dest = "adjust", help = "Increase binding regions for simulations by X bases?", default="OFF") parser.add_option("--overwrite", action = "store", type = "string", dest = "overwrite", help = "Overwrite stuff?", default="OFF") parser.add_option("--round", action = "store", type = "string", dest = "round", help = "Decimal numbers to which the 'density' metrics should be rounded.", default="2") parser.add_option("--nuclear", action = "store", type = "string", dest = "nuclear", help = "Peaks are only nuclear?", default="ON") parser.add_option("--gffkde", action = "store", type = "string", dest = "gffkde", help = "Should we perform GFFKDE-analysis?", default="OFF") parser.add_option("--bw", action = "store", type = "string", dest = "bw", help = "GFFKDE-analysis bandwidth", default="300") parser.add_option("--cs", action = "store", type = "string", dest = "cs", help = "GFFKDE-analysis cutoff-score", default="0.1") parser.add_option("--cp", action = "store", type = "string", dest = "cp", help = "GFFKDE-analysis cutoff-peak", default="0.00001") parser.add_option("--pl", action = "store", type = "string", dest = "pl", help = "GFFKDE-analysis peak local optima", default="30") parser.add_option("--parameters", action = "store", type = "string", dest = "parameters", help = "Variable parameters...", default="") parser.add_option("--threads", action = "store", type = "int", dest = "threads", help = "Parallel processing threads", default=1) parser.add_option("--chunks", action = "store", type = "int", dest = "chunks", help = "", default=100) parser.add_option("--module", action = "store", type = "string", dest = "module", help = "", default="md1") parser.add_option("--qsub", action = "store", type = "string", dest = "qsub", help = "Qsub configuration header", default="OFF") parser.add_option("--server", action = "store", type = "string", dest = "server", help = "Are we on the server?", default="OFF") parser.add_option("--job", action = "store", type = "string", dest = "job", help = "Job name for cluster", default="OFF") parser.add_option("--copy", action = "store", type = "string", dest = "copy", help = "Copy simulated peaks to analysis folder?", default="OFF") parser.add_option("--tag", action = "store", type = "string", dest = "tag", help = "Add tag to TFBS?", default="") (option, args) = parser.parse_args() # import paths: if option.server == "OFF": path_dict = modencode.configBuild(option.path + "/input/" + "configure_path.txt") elif option.server == "ON": path_dict = modencode.configBuild(option.path + "/input/" + "configure_server.txt") elif option.server == "GS": path_dict = modencode.configBuild(option.path + "/input/" + "configure_nexus.txt") # specify input and output paths: inpath = path_dict["input"] extraspath = path_dict["extras"] pythonpath = path_dict["python"] scriptspath = path_dict["scripts"] downloadpath = path_dict["download"] fastqpath = path_dict["fastq"] bowtiepath = path_dict["bowtie"] bwapath = path_dict["bwa"] macspath = path_dict["macs"] memepath = path_dict["meme"] idrpath = path_dict["idr"] igvpath = path_dict["igv"] testpath = path_dict["test"] processingpath = path_dict["processing"] annotationspath = path_dict["annotations"] peakspath = path_dict["peaks"] gopath = path_dict["go"] hotpath = path_dict["hot"] qsubpath = path_dict["qsub"] # standardize paths for analysis: alignerpath = bwapath indexpath = alignerpath + "index/" alignmentpath = alignerpath + "alignment/" qcfilterpath = alignerpath + "qcfilter/" qcmergepath = alignerpath + "qcmerge/" # import configuration dictionaries: source_dict = modencode.configBuild(inpath + "configure_source.txt") method_dict = modencode.configBuild(inpath + "configure_method.txt") context_dict = modencode.configBuild(inpath + "configure_context.txt") # define organism parameters: if option.organism == "hs" or option.organism == "h.sapiens": organismTag = "hs" #organismIGV = "ce6" elif option.organism == "mm" or option.organism == "m.musculus": organismTag = "mm" #organismIGV = "ce6" elif option.organism == "ce" or option.organism == "c.elegans": organismTag = "ce" #organismIGV = "ce6" elif option.organism == "dm" or option.organism == "d.melanogaster": organismTag = "dm" #organismIGV = "dm5" # specify genome size file: if option.nuclear == "ON": chromosomes = metrn.chromosomes[organismTag]["nuclear"] genome_size_file = option.path + "/input/" + metrn.reference[organismTag]["nuclear_sizes"] genome_size_dict = general.build_config(genome_size_file, mode="single", separator="\t", spaceReplace=True) else: chromosomes = metrn.chromosomes[organismTag]["complete"] genome_size_file = option.path + "/input/" + metrn.reference[organismTag]["complete_sizes"] genome_size_dict = general.build_config(genome_size_file, mode="single", separator="\t", spaceReplace=True) # predefine and prebuild input/output paths: densitypath = hotpath + "density/" analysispath = hotpath + "analysis/" comparepath = hotpath + "compare/" overlappath = hotpath + "overlap/" simulationpath = hotpath + "simulation/" regionspath = hotpath + "regions/" temperaturepath = hotpath + "temperature/" general.pathGenerator(densitypath) general.pathGenerator(analysispath) general.pathGenerator(comparepath) general.pathGenerator(overlappath) general.pathGenerator(simulationpath) general.pathGenerator(regionspath) general.pathGenerator(temperaturepath) # generate gffkde handle: gffkde_handle = "_bw" + option.bw.replace("0.","") + "_cs" + option.cs.replace("0.","") + "_cp" + option.cp.replace("0.","") + "_pl" + option.pl.replace("0.","") # check that the index range is coherent: if option.stop > option.total: print print "Error: Range exceeded! Stop index is larger than total." print return # master mode: if "master:" in option.mode: # capture master mode: master, mode = option.mode.split(":") # determine whether peaks should cluster on a predefined number of regions: if option.shuffle == "OFF" and option.regions == "OFF": regions_flag = "random.genomic" regions = False elif option.shuffle == "OFF" and option.regions == "ON": regions_flag = "random.regions" regions = True elif option.shuffle == "ON" and option.regions == "OFF": regions_flag = "shuffle.genomic" regions = True elif option.shuffle == "ON" and option.regions != "OFF": regions_flag = "shuffle.regions" regions = True # prepare for qsub: bash_path = str(option.path + "/data/hot/simulation/runs/").replace("//","/") bash_base = "_".join([mode, regions_flag, option.peaks, option.name]) + "-M" qsub_base = "_".join([mode, regions_flag, option.peaks, option.name]) general.pathGenerator(bash_path) if option.qsub != "OFF": qsub_header = open(qsubpath + option.qsub).read() qsub = True else: qsub_header = "" qsub = False if option.job == "QSUB": qsub_header = qsub_header.replace("qsubRunner", "qsub-" + qsub_base) elif option.job != "OFF": qsub_header = qsub_header.replace("qsubRunner", "qsub-" + option.job) bash_base = option.job + "-M" # update server path: if option.qsub != "OFF": option.path = serverPath(option.path, server=option.server) if option.server != "OFF": bash_mode = "" # prepare slave modules: m, modules, commands, sequences, chunks, start, complete = 1, list(), list(), list(), option.chunks, option.start, False for index in range(option.start, option.stop+1): run = "mc" + general.indexTag(index, option.total) # montecarlo peak simulation mode: if mode == "montecarlo": command = "python <<CODEPATH>>mapHOT.py --path <<PATH>> --organism <<ORGANISM>> --mode <<MODE>> --peaks <<PEAKS>> --start <<START>> --stop <<STOP>> --total <<TOTAL>> --contexts <<CONTEXTS>> --regions <<REGIONS>> --shuffle <<SHUFFLE>> --metric <<METRIC>> --scramble <<SCRAMBLE>> --adjust <<ADJUST>> --overwrite <<OVERWRITE>> --round <<ROUND>> --name <<NAME>> --qsub <<QSUB>> --server <<SERVER>> --copy <<COPY>> --module <<MODULE>>" command = command.replace("<<CODEPATH>>", option.path + "/python/") command = command.replace("<<PATH>>", option.path) command = command.replace("<<ORGANISM>>", option.organism) command = command.replace("<<MODE>>", mode) command = command.replace("<<PEAKS>>", option.peaks) command = command.replace("<<START>>", str(start)) command = command.replace("<<STOP>>", str(index)) command = command.replace("<<TOTAL>>", str(option.total)) command = command.replace("<<CONTEXTS>>", option.contexts) command = command.replace("<<REGIONS>>", option.regions) command = command.replace("<<SHUFFLE>>", option.shuffle) command = command.replace("<<METRIC>>", option.metric) command = command.replace("<<SCRAMBLE>>", option.scramble) command = command.replace("<<ADJUST>>", option.adjust) command = command.replace("<<OVERWRITE>>", option.overwrite) command = command.replace("<<ROUND>>", option.round) command = command.replace("<<NAME>>", option.name) command = command.replace("<<QSUB>>", option.qsub) command = command.replace("<<SERVER>>", option.server) command = command.replace("<<COPY>>", option.copy) command = command.replace("<<MODULE>>", "md" + str(m)) # simulation analysis mode: if mode == "simulation": command = "python <<CODEPATH>>mapHOT.py --path <<PATH>> --organism <<ORGANISM>> --mode <<MODE>> --peaks <<PEAKS>> --start <<START>> --stop <<STOP>> --total <<TOTAL>> --contexts <<CONTEXTS>> --regions <<REGIONS>> --shuffle <<SHUFFLE>> --metric <<METRIC>> --scramble <<SCRAMBLE>> --adjust <<ADJUST>> --overwrite <<OVERWRITE>> --round <<ROUND>> --name <<NAME>> --qsub <<QSUB>> --server <<SERVER>> --copy <<COPY>> --module <<MODULE>>" command = command.replace("<<CODEPATH>>", option.path + "/python/") command = command.replace("<<PATH>>", option.path) command = command.replace("<<ORGANISM>>", option.organism) command = command.replace("<<MODE>>", mode) command = command.replace("<<PEAKS>>", option.peaks) command = command.replace("<<START>>", str(start)) command = command.replace("<<STOP>>", str(index)) command = command.replace("<<TOTAL>>", str(option.total)) command = command.replace("<<CONTEXTS>>", option.contexts) command = command.replace("<<REGIONS>>", option.regions) command = command.replace("<<SHUFFLE>>", option.shuffle) command = command.replace("<<METRIC>>", option.metric) command = command.replace("<<SCRAMBLE>>", option.scramble) command = command.replace("<<ADJUST>>", option.adjust) command = command.replace("<<OVERWRITE>>", option.overwrite) command = command.replace("<<ROUND>>", option.round) command = command.replace("<<NAME>>", option.name) command = command.replace("<<QSUB>>", option.qsub) command = command.replace("<<SERVER>>", option.server) command = command.replace("<<COPY>>", option.copy) command = command.replace("<<MODULE>>", "md" + str(m)) # simulation collecting mode: if mode == "collecting": command = "python <<CODEPATH>>mapHOT.py --path <<PATH>> --organism <<ORGANISM>> --mode <<MODE>> --peaks <<PEAKS>> --start <<START>> --stop <<STOP>> --total <<TOTAL>> --contexts <<CONTEXTS>> --regions <<REGIONS>> --shuffle <<SHUFFLE>> --metric <<METRIC>> --scramble <<SCRAMBLE>> --adjust <<ADJUST>> --overwrite <<OVERWRITE>> --round <<ROUND>> --name <<NAME>> --qsub <<QSUB>> --server <<SERVER>> --copy <<COPY>> --module <<MODULE>>" command = command.replace("<<CODEPATH>>", option.path + "/python/") command = command.replace("<<PATH>>", option.path) command = command.replace("<<ORGANISM>>", option.organism) command = command.replace("<<MODE>>", mode) command = command.replace("<<PEAKS>>", option.peaks) command = command.replace("<<START>>", str(option.start)) command = command.replace("<<STOP>>", str(option.stop)) command = command.replace("<<TOTAL>>", str(option.total)) command = command.replace("<<CONTEXTS>>", option.contexts) command = command.replace("<<REGIONS>>", option.regions) command = command.replace("<<SHUFFLE>>", option.shuffle) command = command.replace("<<METRIC>>", option.metric) command = command.replace("<<SCRAMBLE>>", option.scramble) command = command.replace("<<ADJUST>>", option.adjust) command = command.replace("<<OVERWRITE>>", option.overwrite) command = command.replace("<<ROUND>>", option.round) command = command.replace("<<NAME>>", option.name) command = command.replace("<<QSUB>>", option.qsub) command = command.replace("<<SERVER>>", option.server) command = command.replace("<<COPY>>", option.copy) command = command.replace("<<MODULE>>", "md" + str(m)) break # is it time to export a chunk? if index-start+1 == chunks: # update start, modules, commands, and module count (m): start = index + 1 commands.append(command) modules.append(commands) commands = list() complete = True m += 1 # store whether the most recent index/command has been stored: else: complete = False # update if there are additional commands: if not complete: commands.append(command) modules.append(commands) m += 1 # launch commands: print print "Launching comparisons:", len(modules) #for module in modules: # for command in module: # print command runCommands(modules, threads=option.threads, mode="module.run", run_mode="verbose", run_path=bash_path, run_base=bash_base, record=True, qsub_header=qsub_header, qsub=qsub) print "Comparisons performed:", len(modules) print # perform Monte-Carlo simulation of peaks: elif option.mode == "montecarlo": # prepare chromosome sizes: chrm_size_dict, chrm_base_dict = dict(), dict() for chrm in chromosomes: chrm_size_dict[chrm] = genome_size_dict[chrm] chrm_base_dict[chrm] = [1, genome_size_dict[chrm]] # get context code and target contexts: contextCode, contextTargets = metrn.contexts[organismTag]["list"][option.contexts] # determine whether peaks should cluster on a predefined number of regions: if option.shuffle == "OFF" and option.regions == "OFF": regions_flag = "random.genomic" regions = False elif option.shuffle == "OFF" and option.regions == "ON": regions_flag = "random.regions" regions = True elif option.shuffle == "ON" and option.regions == "OFF": regions_flag = "shuffle.genomic" regions = True elif option.shuffle == "ON" and option.regions != "OFF": regions_flag = "shuffle.regions" regions = True # shuffle-based methods: if option.shuffle == "ON": # define simulation setup path: carbonpath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" general.pathGenerator(carbonpath) # prebuild overlap regions if necessary: print print "Preparing configuration files..." if regions_flag == "shuffle.regions": # define density file (gffkde), regions file (bed), annexed file (bed), overlap file (bed): kdensityfile = densitypath + "gffkde2_" + option.regions + gffkde_handle + ".Peaks.Extended" regionalfile = carbonpath + "maphot_montecarlo_master_regional." + option.module + ".bed" completefile = carbonpath + "maphot_montecarlo_master_complete." + option.module + ".bed" collapsefile = carbonpath + "maphot_montecarlo_master_collapse." + option.module + ".bed" compiledfile = carbonpath + "maphot_montecarlo_master_compiled." + option.module + ".bed" #gffkde2bed(kdensityfile, mode="file", outfile=regionalfile) metrn.completeBed(peakspath + option.peaks + "/", outfile=completefile) # make overlap regions (collapse peaks): command = "mergeBed -i " + completefile + " -nms > " + collapsefile os.system(command) # generate a density-style analysis file: metrn.densityBed(collapsefile, compiledfile) # simulate peaks per factor: print "Launching simulations:", time.asctime(time.localtime()) for i in range(option.start, option.stop+1): run = "mc" + general.indexTag(i, option.total) print print "\tSimulation:", run if option.overwrite == "ON" or not run in os.listdir(carbonpath): # define simulation paths: randompath = carbonpath + run + "/random/" configpath = carbonpath + run + "/config/" resultpath = carbonpath + run + "/result/" # clear prexisting simulations: if run in os.listdir(carbonpath): command = "rm -rf " + randompath os.system(command) # generate output paths: general.pathGenerator(randompath) general.pathGenerator(configpath) general.pathGenerator(resultpath) c = 0 # generate exclusion regions if necessary: if regions_flag == "shuffle.regions": # define shuffle file (bed), exclude file (bed): shufflefile = configpath + "maphot_montecarlo_" + run + "_shuffle.bed" regionsfile = configpath + "maphot_montecarlo_" + run + "_regions.bed" excludefile = configpath + "maphot_montecarlo_" + run + "_exclude.bed" # make shuffled regions: if option.scramble == "ON": command = "shuffleBed -i " + collapsefile + " -g " + genome_size_file + " -chrom > " + shufflefile os.system(command) else: shufflefile = collapsefile # make adjusted regions: if option.adjust != "OFF": command = "slopBed -i " + shufflefile + " -g " + genome_size_file + " -b " + option.adjust + " > " + regionsfile os.system(command) else: regionsfile = shufflefile # make excluded regions: command = "complementBed -i " + regionsfile + " -g " + genome_size_file + " > " + excludefile os.system(command) # simulate the peaks: for peak_file in os.listdir(peakspath + option.peaks): organism, strain, factor, context, institute, method = metrn.labelComponents(peak_file) if option.contexts in ["all","any","XX","total.extended","total.condense"] or context in contextTargets and ".bed" in peak_file: c += 1 dataset = peak_file.split("_peaks.")[0] strain, factor, context, institute, method = peak_file.split("_")[:5] inpeakfile = peakspath + option.peaks + "/" + peak_file randomfile = randompath + peak_file.replace("_peaks.bed", "_random.bed") print "\t", run, ":", peak_file # genomic shuffling: if regions_flag == "shuffle.genomic": command = "shuffleBed -i " + inpeakfile + " -g " + genome_size_file + " -chrom > " + randomfile os.system(command) # regions shuffling: elif regions_flag == "shuffle.regions": command = "shuffleBed -i " + inpeakfile + " -g " + genome_size_file + " -excl " + excludefile + " > " + randomfile os.system(command) # define run complete and collapsed files: completerun = resultpath + "maphot_montecarlo_" + run + "_complete.bed" collapserun = resultpath + "maphot_montecarlo_" + run + "_collapse.bed" # make run complete and collapsed files: metrn.completeBed(randompath, outfile=completerun) command = "mergeBed -i " + completerun + " -nms > " + collapserun os.system(command) # non-shuffle methods: elif option.shuffle == "OFF": # prepare peak size and peak score dictionaries: maxSize = 0 peak_size_dict, peak_score_dict = dict(), dict() for peak_file in os.listdir(peakspath + option.peaks): strain, factor, context, institute, method = peak_file.split("_")[:5] if option.contexts in ["all","any","XX"] or context in contextTargets and ".bed" in peak_file: inlines = open(peakspath + option.peaks + "/" + peak_file).readlines() for inline in inlines: chrm, start, end, feature, score = inline.strip().split("\t")[:5] if not peak_file in peak_size_dict: peak_size_dict[peak_file] = list() peak_score_dict[peak_file] = list() peak_size_dict[peak_file].append(int(end)-int(start)) peak_score_dict[peak_file].append(int(float(score))) if int(end)-int(start) > maxSize: maxSize = int(end)-int(start) # determine whether peak should cluster on a predefined number of regions: if regions: # match density file: process = False for densityfile in os.listdir(densitypath): if "gffkde2_" + option.regions + "_bw" in densityfile and ".Peaks.Detail" in densityfile: process = True print "Matched density file:", densityfile break print "Preparing region dictionaries..." if process: region_size_dict, region_base_dict = dict(), dict() inlines = open(densitypath + densityfile).readlines() for inline in inlines: if inline[0] != "#": chrm, parameters, hotspot, start, end = inline.strip().split("\t")[:5] chrm, start, end = chrm.replace("MTDNA","MtDNA"), int(start), int(end) start, end = sorted([start, end]) if not chrm in region_size_dict: region_size_dict[chrm] = dict() region_base_dict[chrm] = dict() if not start in region_size_dict[chrm]: region_size_dict[chrm][start] = dict() region_base_dict[chrm][start] = dict() region_size_dict[chrm][start][end] = abs(end-start) region_base_dict[chrm][start][end] = [start, end] else: raise "Error: Density file not found!" # generate coordinate system: print "Generating coordinate dictionaries..." if option.regions == "OFF": coord_dict, coord_min, coord_max, edge_dict = genomeCoords(chromosomes, chrm_size_dict) base_dict = chrm_base_dict else: coord_dict, coord_min, coord_max, edge_dict = regionCoords(chromosomes, region_size_dict) base_dict = region_base_dict # simulate peaks per factor: print "Starting simulations:", time.asctime(time.localtime()) for i in range(option.start, option.stop+1): run = "mc" + general.indexTag(i, option.total) print "Simulation index:", run # define simulation paths: randompath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" + run + "/random/" configpath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" + run + "/config/" general.pathGenerator(randompath) general.pathGenerator(configpath) c = 0 for peak_file in peak_size_dict: c += 1 dataset = peak_file.split("_peaks.")[0] strain, factor, context, institute, method = peak_file.split("_")[:5] f_output = open(montecarlopath + peak_file, "w") k = 1 #print "Processing:", peak_file, len(peak_file), "peaks" for size in peak_size_dict[peak_file]: #print "Size:", size chrm, base = randomBase(coord_dict, coord_min, coord_max, edge_dict, mode=regions_flag) #print "Random:", chrm, base while (size > maxSize and chrm == "MtDNA") or (base + size > chrm_size_dict[chrm]): chrm, base = randomBase(coord_dict, coord_min, coord_max, edge_dict, mode=regions_flag) #print "Repeat:", chrm, base score = peak_score_dict[peak_file][k-1] code = dataset + ".Random_peak_" + str(k) peak = "Random_peak_" + str(k) output = [chrm, base, base + size, code, score, "+", strain, factor, context, institute, method, peak] print >>f_output, "\t".join(map(str, output)) k += 1 #pdb.set_trace() f_output.close() print "Simulations complete!" print # perform simulation sampling peaks from pre-computed random peaks (monte-carlo): elif option.mode == "simulation": # prepare chromosome sizes: chrm_size_dict, chrm_base_dict = dict(), dict() for chrm in chromosomes: chrm_size_dict[chrm] = genome_size_dict[chrm] chrm_base_dict[chrm] = [1, genome_size_dict[chrm]] # get context code and target contexts: contextCode, contextTargets = metrn.contexts[organismTag]["list"][option.contexts] # determine whether peaks should cluster on a predefined number of regions: if option.shuffle == "OFF" and option.regions == "OFF": regions_flag = "random.genomic" regions = False elif option.shuffle == "OFF" and option.regions == "ON": regions_flag = "random.regions" regions = True elif option.shuffle == "ON" and option.regions == "OFF": regions_flag = "shuffle.genomic" regions = True elif option.shuffle == "ON" and option.regions != "OFF": regions_flag = "shuffle.regions" regions = True # setup montecarlo simulation (source) path: carbonpath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" # define configuration files: completefile = "maphot_montecarlo_master_complete.bed" collapsefile = "maphot_montecarlo_master_collapse.bed" compiledfile = "maphot_montecarlo_master_compiled.bed" # condense (remove replicate modules): if not completefile in os.listdir(carbonpath): command = "cp " + carbonpath + completefile.replace(".bed", ".md1.bed") + " " + carbonpath + completefile os.system(command) if not collapsefile in os.listdir(carbonpath): command = "cp " + carbonpath + collapsefile.replace(".bed", ".md1.bed") + " " + carbonpath + collapsefile os.system(command) if not compiledfile in os.listdir(carbonpath): command = "cp " + carbonpath + compiledfile.replace(".bed", ".md1.bed") + " " + carbonpath + compiledfile os.system(command) command = "rm -rf " + carbonpath + "maphot_montecarlo_master_complete.md*bed" os.system(command) command = "rm -rf " + carbonpath + "maphot_montecarlo_master_collapse.md*bed" os.system(command) command = "rm -rf " + carbonpath + "maphot_montecarlo_master_compiled.md*bed" os.system(command) # transfer simulated peaks and execute density analysis: print for i in range(option.start, option.stop+1): run = "mc" + general.indexTag(i, option.total) print "\tSimulation:", run # define simulation paths: randompath = carbonpath + run + "/random/" configpath = carbonpath + run + "/config/" resultpath = carbonpath + run + "/result/" #general.pathGenerator(randompath) #general.pathGenerator(configpath) #general.pathGenerator(resultpath) # define analysis paths: subsetpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/subset/" gffkdepath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/gffkde/" mergedpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/merged/" general.pathGenerator(subsetpath) general.pathGenerator(gffkdepath) general.pathGenerator(mergedpath) # define complete peaks file and merged (collapse) peaks file: completefile = mergedpath + "maphot_montecarlo_" + run + "_complete.bed" collapsefile = mergedpath + "maphot_montecarlo_" + run + "_collapse.bed" compiledfile = mergedpath + "maphot_montecarlo_" + run + "_compiled.bed" c = 0 # scan simulation peaks: for randomfile in os.listdir(randompath): strain, factor, context, institute, method = randomfile.split("_")[:5] dataset = "_".join([strain, factor, context, institute, method]) if option.contexts in ["all","any","XX","total.extended","total.condense"] or context in contextTargets and ".bed" in randomfile: c += 1 # transfer simulated peaks: #command = "cp " + randompath + randomfile + " " + subsetpath + randomfile #os.system(command) """ This section added to regenerate compiledfile... """ # make complete simulated peaks file (complete peaks): #metrn.completeBed(subsetpath, outfile=completefile) # make overlap regions (collapse peaks): #command = "mergeBed -i " + completefile + " -nms > " + collapsefile #os.system(command) # generate a density-style analysis file: metrn.densityBed(collapsefile, compiledfile) """ # launch kernel-density analysis (if desired): if option.gffkde == "ON": command = "perl <<SCRIPTSPATH>>GFFKDE2.pl <<RANDOMPATH>> <<BW>> <<CS>> <<CP>> <<PL>> <<GFFKDEPATH>>gffkde2_<<NAME>><<GFFKDEHANDLE>>" command = command.replace("<<SCRIPTSPATH>>", scriptspath) command = command.replace("<<RANDOMPATH>>", randompath) command = command.replace("<<GFFKDEPATH>>", gffkdepath) command = command.replace("<<GFFKDEHANDLE>>", gffkde_handle) command = command.replace("<<BW>>", option.bw) command = command.replace("<<CS>>", option.cs) command = command.replace("<<CP>>", option.cp) command = command.replace("<<PL>>", option.pl) command = command.replace("<<NAME>>", option.name) print command os.system(command) print # remove large density file: command = "rm -rf <<GFFKDEPATH>>gffkde2_<<NAME>><<GFFKDEHANDLE>>.Density" command = command.replace("<<GFFKDEPATH>>", gffkdepath) command = command.replace("<<GFFKDEHANDLE>>", gffkde_handle) command = command.replace("<<NAME>>", option.name) os.system(command) # remove unwanted region file: command = "rm -rf <<GFFKDEPATH>>gffkde2_<<NAME>><<GFFKDEHANDLE>>.Peaks" command = command.replace("<<GFFKDEPATH>>", gffkdepath) command = command.replace("<<GFFKDEHANDLE>>", gffkde_handle) command = command.replace("<<NAME>>", option.name) os.system(command) # remove unwanted detail file: command = "rm -rf <<GFFKDEPATH>>gffkde2_<<NAME>><<GFFKDEHANDLE>>.Peaks.Detail" command = command.replace("<<GFFKDEPATH>>", gffkdepath) command = command.replace("<<GFFKDEHANDLE>>", gffkde_handle) command = command.replace("<<NAME>>", option.name) os.system(command) # copy (keep) or remove the used peaks? if option.copy == "OFF": command = "rm -rf " + subsetpath + "*.bed" os.system(command) """ # collect results from simulated binding regions with random peaks (monte-carlo, simulation): elif option.mode == "collecting": # set analysis metric and flag: if option.metric == "occupancy": metric_flag = "_occupan" elif option.metric == "density": metric_flag = "_density" elif option.metric == "complexity": metric_flag = "_complex" # determine whether peaks should cluster on a predefined number of regions: if option.shuffle == "OFF" and option.regions == "OFF": regions_flag = "random.genomic" regions = False elif option.shuffle == "OFF" and option.regions == "ON": regions_flag = "random.regions" regions = True elif option.shuffle == "ON" and option.regions == "OFF": regions_flag = "shuffle.genomic" regions = True elif option.shuffle == "ON" and option.regions != "OFF": regions_flag = "shuffle.regions" regions = True # setup montecarlo simulation (source) path: carbonpath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" # get context code and target contexts: contextCode, contextTargets = metrn.contexts[organismTag]["list"][option.contexts] # transfer analyzed mergedBed compiled (density) file to density path: compiledfile = carbonpath + "maphot_montecarlo_master_compiled.bed" densityfile = "mergeBed_" + option.peaks + "_compiled.bed" if not densityfile in os.listdir(densitypath): command = "cp " + compiledfile + " " + densitypath + densityfile os.system(command) # define analysis path: reportpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" # prepare region reports: f_output = open(reportpath + "maphot_simulation_report" + metric_flag + "_region.txt", "w") # gather density frequencies from simulations: print value_dict, simulation_dict, regions_dict, dataset_dict, factor_dict, context_dict = dict(), dict(), dict(), dict(), dict(), dict() for i in range(option.start, option.stop+1): run = "mc" + general.indexTag(i, option.total) #print "\tSimulation:", run sys.stdout.write("\rCollecting densities from simulations: {0}".format(run)) sys.stdout.flush() # define simulation paths: randompath = carbonpath + run + "/random/" configpath = carbonpath + run + "/config/" # define analysis paths: subsetpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/subset/" gffkdepath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/gffkde/" mergedpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" + run + "/merged/" general.pathGenerator(reportpath) # define complete peaks file, merged (collapse) peaks file, and GFFKDE density file: kdensityfile = gffkdepath + "gffkde2_<<NAME>><<GFFKDEHANDLE>>.Peaks.Extended".replace("<<NAME>>", option.name).replace("<<GFFKDEHANDLE>>", gffkde_handle) completefile = mergedpath + "maphot_montecarlo_" + run + "_complete.bed" collapsefile = mergedpath + "maphot_montecarlo_" + run + "_collapse.bed" compiledfile = mergedpath + "maphot_montecarlo_" + run + "_compiled.bed" # load kernel-density data (if desired): if option.gffkde == "ON": # load densities for individual simulation: inlines = open(kdensityfile).readlines() for inline in inlines: chrm, method, feature, start, stop, score, strand, period, info = inline.strip().split("\t") # set analysis metric and flag: if option.metric == "occupancy": value = int(round(float(score))) elif option.metric == "density": size = int(stop) - int(start) + 1 value = 1000*float(int(round(float(score))))/size if option.round != "OFF": value = round(value, int(option.round)) elif option.metric == "complexity": raise "Error: metric not implemented!" # store simulation value: if not run in simulation_dict: simulation_dict[run] = dict() if not value in simulation_dict[run]: simulation_dict[run][value] = 0 simulation_dict[run][value] += 1 # load mergedBed density data: else: # load densities for individual simulation: inlines = open(compiledfile).readlines() index = 1 for inline in inlines: chrm, start, stop, feature, occupancy, strand, density, datasetCount, factorCount, contextCount, info = inline.strip().split("\t") # set analysis metric and flag: if option.metric == "occupancy": value = int(occupancy) elif option.metric == "density": value = float(density) if option.round != "OFF": value = round(value, int(option.round)) elif option.metric == "complexity": value = int(datasetCount) # store simulation value: if not run in simulation_dict: simulation_dict[run] = dict() if not value in simulation_dict[run]: simulation_dict[run][value] = 0 simulation_dict[run][value] += 1 # export simulated region data: size = str(int(stop) - int(start) + 1) complexity = datasetCount regularity = str(1000*float(datasetCount)/int(size)) print >>f_output, "\t".join([run + "." + str(index), occupancy, density, complexity, regularity, size]) index += 1 # load densities for simulation summary: for value in simulation_dict[run]: if not value in value_dict: value_dict[value] = list() value_dict[value].append(simulation_dict[run][value]) # load region count for individual simulation summary: regions_dict[run] = len(inlines) # determine number of regions and simulations analyzed: regions = sum(regions_dict.values()) simulations = len(simulation_dict) # prepare density reports: g_output = open(reportpath + "maphot_simulation_report" + metric_flag + "_global.txt", "w") s_output = open(reportpath + "maphot_simulation_report" + metric_flag + "_single.txt", "w") v_output = open(reportpath + "maphot_simulation_report" + metric_flag + "_values.txt", "w") # print headers: print >>g_output, "\t".join(["value", "regions.sum", "regions.mean", "regions.median", "regions.std", "regions.total", "simulations"]) print >>s_output, "\t".join(["simulation", "value", "regions.sum", "regions.mean", "regions.median", "regions.std", "regions.total", "simulations"]) print >>v_output, "\t".join(["simulation", "value"]) # export global simulation density report: print "\nExporting global simulation data..." for value in sorted(value_dict.keys()): values = value_dict[value] print >>g_output, "\t".join(map(str, [value, sum(values), numpy.mean(values), int(numpy.median(values)), numpy.std(values), regions, simulations])) # export single simulation density report: print "Exporting individual simulation data..." for simulation in sorted(simulation_dict.keys()): values = list() for value in sorted(simulation_dict[simulation].keys()): observations = [value]*simulation_dict[simulation][value] values += observations for observation in observations: print >>v_output, "\t".join([simulation, str(observation)]) for value in sorted(simulation_dict[simulation].keys()): print >>s_output, "\t".join(map(str, [simulation, value, simulation_dict[simulation][value], numpy.mean(values), int(numpy.median(values)), numpy.std(values), sum(simulation_dict[simulation].values()), simulations])) # close output files: f_output.close() g_output.close() s_output.close() v_output.close() print # download results of simulated binding regions from cluster: elif option.mode == "downloader": # determine whether peaks should cluster on a predefined number of regions: if option.shuffle == "OFF" and option.regions == "OFF": regions_flag = "random.genomic" regions = False elif option.shuffle == "OFF" and option.regions == "ON": regions_flag = "random.regions" regions = True elif option.shuffle == "ON" and option.regions == "OFF": regions_flag = "shuffle.genomic" regions = True elif option.shuffle == "ON" and option.regions != "OFF": regions_flag = "shuffle.regions" regions = True # define server path dictionary: server_dict = modencode.configBuild(option.path + "/input/" + "configure_server.txt") # define simulation (source) paths, remote (serverpath) and local (reportpath): serverpath = server_dict["hot"] + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" reportpath = hotpath + "simulation/analysis/" + option.peaks + "/" + regions_flag + "/" + option.name + "/" general.pathGenerator(reportpath) # recover server login base: command = "rsync -avz " + option.parameters + ":" + serverpath + "maphot_* " + reportpath os.system(command) # recover density (source) paths, remote (serverpath) and local (reportpath): serverpath = server_dict["hot"] + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" reportpath = hotpath + "simulation/montecarlo/" + option.peaks + "/" + regions_flag + "/" general.pathGenerator(reportpath) # recover server login base: command = "rsync -avz " + option.parameters + ":" + serverpath + "maphot_* " + reportpath os.system(command) # perform scan to pull-out HOT regions: elif option.mode == "scan": # determine input density file: if option.gffkde == "ON": densityfile = "gffkde2_" + option.peaks + gffkde_handle + ".Peaks.Extended" else: densityfile = "mergeBed_" + option.peaks + "_compiled.bed" # set analysis metric and flag: if option.metric == "occupancy": metric_flag = "_occupan" elif option.metric == "density": metric_flag = "_density" elif option.metric == "complexity": metric_flag = "_complex" elif option.metric == "combined": metric_flag = "_combine" # set contribution behavior: if option.contribution == 0: contribution_handle = "_con" + "XX" else: contribution_handle = "_con" + "%.0e" % (float(option.contribution)) # set cutoff behavior: if option.cutoff == "OFF" or option.cutoff == "X": cutoff_status = False cutoff_handle = "_cut" + "XX" elif option.significance != "OFF": cutoff_status = True cutoff_handle = "_sig" + option.significance else: cutoff_status = True cutoff_handle = "_cut" + str(option.cutoff).zfill(3) # set configuration output handles: if option.name == "OFF": configuration_name = "_simple" configuration_handle = "_simple" + cutoff_handle + contribution_handle else: configuration_name = "_" + option.name configuration_handle = "_" + option.name + cutoff_handle + contribution_handle # generate output files: firstPart, lastPart = densityfile.split(option.peaks) p_outfile = "maphot_" + option.target + configuration_name + "_" + firstPart + option.peaks + configuration_handle + lastPart.lower().replace(".bed","").replace(".Peaks.Extended","_compiled").replace("_compiled", metric_flag).replace(".","_") + "_pass.bed" f_outfile = "maphot_" + option.target + configuration_name + "_" + firstPart + option.peaks + configuration_handle + lastPart.lower().replace(".bed","").replace(".Peaks.Extended","_compiled").replace("_compiled", metric_flag).replace(".","_") + "_fail.bed" # open input and output files: p_output = open(analysispath + p_outfile, "w") f_output = open(analysispath + f_outfile, "w") #print >>p_output, "\t".join(["chrm", "start", "end", "feature", "score", "strand", "density", "details"]) #print >>f_output, "\t".join(["chrm", "start", "end", "feature", "score", "strand", "density", "details"]) # scan HOT-region analysis output: fi, pi = 1, 1 inlines = open(densitypath + densityfile).readlines() for inline in inlines: if option.gffkde == "ON": chrm, runMethod, className, start, end, density, unknown, unspecified, details = inline.strip().split("\t") else: chrm, start, end, feature, occupancy, strand, density, datasetCount, factorCount, contextCount, details = inline.strip().split("\t") # parse details: identifiers, datasets, factors, contexts = metrn.parseDetails(details, target=option.target, gffkde=option.gffkde, contributionCutoff=option.contribution) # scan details: catch = False if option.limits != "OFF": for limit in option.limits.split(","): text, limit = limit.split(":") if details.count(text) > int(limit): catch = True # count total hits (density) and unique hits (complexity): size = int(end) - int(start) + 1 occupancy = len(identifiers) density = 1000*float(occupancy)/size datasetCounts = len(set(datasets)) factorCounts = len(set(factors)) contextCounts = len(set(contexts)) # set analysis metric and flag: if option.metric == "occupancy": value = occupancy if value > float(option.cutoff): catch = True elif option.metric == "density": value = density if value > float(option.cutoff) and occupancy >= option.minOccupancy: catch = True elif option.metric == "complexity": value = complexity if value > float(option.cutoff) and occupancy >= option.minOccupancy: catch = True elif option.metric == "combined": maxOccupancy, maxDensity = map(float, option.cutoff.split(",")) if occupancy > maxOccupancy and density > maxDensity: catch = True # apply cutoffs: if catch: print >>f_output, "\t".join([chrm, start, end, "HOT." + str(fi), str(occupancy), "+", str(density), str(datasetCounts), str(factorCounts), str(contextCounts), details]) fi += 1 else: print >>p_output, "\t".join([chrm, start, end, "TFBS." + option.tag + str(pi), str(occupancy), "+", str(density), str(datasetCounts), str(factorCounts), str(contextCounts), details]) pi += 1 # close output file: f_output.close() print print "Regions analyzed:", pi + fi print "Regions passed:", pi, "(" + str(round(100*float(pi)/(pi + fi), 2)) + "%)" print "Regions failed:", fi, "(" + str(round(100*float(fi)/(pi + fi), 2)) + "%)" print # perform comparative analysis with other region files (such as the Yip 2012 HOT regions): if option.mode == "compare": # define query and target files: queryfile = analysispath + option.infile targetfile = option.source # define output files: abOutfile = comparepath + "maphot_compare_" + option.name + "_AB_collapse.bed" baOutfile = comparepath + "maphot_compare_" + option.name + "_BA_collapse.bed" print print "Query:", option.infile print "Target:", option.source.split("/")[len(option.source.split("/"))-1] # determine overlaps: command = "intersectBed -a " + queryfile + " -b " + targetfile + " -u >" + abOutfile os.system(command) command = "intersectBed -a " + targetfile + " -b " + queryfile + " -u >" + baOutfile os.system(command) # measure comparison: qyCount = general.countLines(queryfile) tgCount = general.countLines(targetfile) abCount = general.countLines(abOutfile) baCount = general.countLines(baOutfile) print print "Queries matched:", abCount, "(" + str(round(100*float(abCount)/(qyCount), 2)) + "%)" print "Targets matched:", baCount, "(" + str(round(100*float(baCount)/(tgCount), 2)) + "%)" print # perform overlap analysis amongst HOT region files: if option.mode == "regions": if option.source == "analysis": # define output files: hotfile = regionspath + "maphot_" + option.regions + "_hot.bed" rgbfile = regionspath + "maphot_" + option.regions + "_rgb.bed" print print "Finding HOT-region and RGB-region files..." for infile in sorted(os.listdir(analysispath)): if option.name in infile and "fail.bed" in infile: print "HOT regions:", infile command = "cp " + analysispath + infile + " " + hotfile os.system(command) if option.name in infile and "pass.bed" in infile: print "RGB regions:", infile command = "cp " + analysispath + infile + " " + rgbfile os.system(command) print "Copying files to region folders..." print if option.source == "overlap": # define output files: anyfile = regionspath + "maphot_" + option.regions + "_any.bed" allfile = regionspath + "maphot_" + option.regions + "_all.bed" print print "Finding overlap HOT-region files..." for infile in sorted(os.listdir(overlappath)): if option.name in infile and "_region_global.bed" in infile: print "Global HOT regions (context-dependent):", infile command = "cp " + overlappath + infile + " " + anyfile os.system(command) if option.name in infile and "_region_shared.bed" in infile: print "Shared HOT regions (ubiquitously HOT):", infile command = "cp " + overlappath + infile + " " + allfile os.system(command) print "Copying files to region folders..." print # perform overlap analysis amongst HOT region files: if option.mode == "overlap": # define output files: #j_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_report_chords.txt" f_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_report_matrix.txt" s_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_region_shared.bed" b_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_region_subset.bed" m_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_merged_subset.bed" c_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_region_global.bed" x_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_merged_global.bed" u_outfile = "maphot_" + option.mode + "_" + option.overlap + "_" + option.name + "_region_unique.bed" # prepare output file: f_output = open(overlappath + f_outfile, "w") print >>f_output, "\t".join(["region.a", "region.b", "count.a", "count.b", "overlap", "overlap.max", "overlap.sum"]) # prepare key:target dictionary: key_dict = dict() for target in option.target.split(","): key, target = target.split(":") key_dict[key] = target print print "Print associating keys to HOT-region files..." hotfile_dict = dict() for hotfile in sorted(os.listdir(analysispath)): if option.name in hotfile and "fail.bed" in hotfile: for key in sorted(key_dict.keys()): if key_dict[key] in hotfile: hotfile_dict[key] = hotfile print key, ":", hotfile print print "Preparing HOT-overlap matrix..." matrix_dict, chords_dict = dict(), dict() for keyA in sorted(hotfile_dict.keys()): targetA = key_dict[keyA] if not keyA in matrix_dict: matrix_dict[keyA] = dict() for keyB in sorted(hotfile_dict.keys()): targetB = key_dict[keyB] command = 'grep -v "feature" ' + analysispath + hotfile_dict[keyA] + ' > ' + overlappath + "maphot_targetA.tmp" os.system(command) command = 'grep -v "feature" ' + analysispath + hotfile_dict[keyB] + ' > ' + overlappath + "maphot_targetB.tmp" os.system(command) command = "intersectBed -a " + overlappath + "maphot_targetA.tmp" + " -b " + overlappath + "maphot_targetB.tmp" + " -u > " + overlappath + "maphot_intersect.tmp" os.system(command) regions_a = general.countLines(overlappath + "maphot_targetA.tmp") regions_b = general.countLines(overlappath + "maphot_targetB.tmp") regions_o = general.countLines(overlappath + "maphot_intersect.tmp") overlap = regions_o union = regions_o + regions_a - regions_o + regions_b - regions_o if union == 0: overlap_max =0 overlap_sum =0 else: overlap_max = float(overlap)/max(regions_a, regions_b) overlap_sum = float(overlap)/union output = [keyA, keyB, regions_a, regions_b, overlap, overlap_max, overlap_sum] print >>f_output, "\t".join(map(str, output)) # store overlap for chords-graphing: if not keyA in chords_dict: chords_dict[keyA] = dict() chords_dict[keyA][keyB] = regions_o # find HOT regions that are shared amongst all datasets: print "Finding shared HOT regions..." print processed = list() for key in sorted(hotfile_dict.keys()): command = 'grep -v "feature" ' + analysispath + hotfile_dict[key] + " > " + overlappath + "maphot_source.tmp" os.system(command) # create or update the shared HOT regions: if processed == list(): command = "cp " + overlappath + "maphot_source.tmp" + " " + overlappath + "maphot_shared.tmp" os.system(command) else: command = "intersectBed -a " + overlappath + s_outfile + " -b " + overlappath + "maphot_source.tmp" + " -u > " + overlappath + "maphot_shared.tmp" os.system(command) command = "cp " + overlappath + "maphot_shared.tmp" + " " + overlappath + s_outfile os.system(command) # index/re-name HOT regions with the respective key: indexColumns(overlappath + "maphot_source.tmp", column=4, base="HOT-" + key + ".", header=False, extension="") print "Peaks in", key,"HOT regions:", densityPeakCounter(overlappath + "maphot_source.tmp") # aggregate context HOT regions: if processed == list(): command = "cp " + overlappath + "maphot_source.tmp" + " " + overlappath + "maphot_aggregate.tmp" os.system(command) else: command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + "maphot_current.tmp" os.system(command) command = "cat " + overlappath + "maphot_current.tmp" + " " + overlappath + "maphot_source.tmp" + " > " + overlappath + "maphot_aggregate.tmp" os.system(command) # update processed keys: processed.append(key) # export shared HOT regions (also re-name HOT regions): indexColumns(overlappath + "maphot_shared.tmp", column=4, base="HOT.", header=False, extension="") command = "cp " + overlappath + "maphot_shared.tmp" + " " + overlappath + s_outfile os.system(command) # generate and export chords .json file: #sharedRegions = general.countLines(overlappath + "maphot_shared.tmp") #chords_dict["uHOT"] = dict() #chords_dict["uHOT"]["uHOT"] = 0 #for keyX in chords_dict: # chords_dict[keyX]["uHOT"] = sharedRegions # chords_dict["uHOT"][keyX] = sharedRegions # export json file: #chords_list = list() #for keyA in chords_dict: # keyA_list = list() # for keyB in chords_dict: # keyA_list.append(chords_dict[keyA][keyB]) # chords_list.append(keyA_list) #import simplejson as json #j_output = open(overlappath + j_outfile, "w") #json.dump(chords_list, j_output) #j_output.close() print print "Peaks in shared HOT regions:", densityPeakCounter(overlappath + s_outfile) # collapse context-wide subset HOT regions (not-shared): command = "mergeBed -i " + overlappath + "maphot_aggregate.tmp" + " -nms > " + overlappath + x_outfile os.system(command) # export aggregate context HOT regions: #indexColumns(overlappath + "maphot_aggregate.tmp", column=4, base="HOT.", header=False, extension="") command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + c_outfile os.system(command) print "Peaks across all HOT regions:", densityPeakCounter(overlappath + c_outfile) # find HOT regions that are only in a subset of the datasets (not-shared): print "Finding non-shared (subset) HOT regions..." processed = list() for key in sorted(hotfile_dict.keys()): # create dataset non-shared (subset) HOT regions: command = 'grep -v "feature" ' + analysispath + hotfile_dict[key] + " > " + overlappath + "maphot_source.tmp" os.system(command) command = "intersectBed -a " + overlappath + "maphot_source.tmp" + " -b " + overlappath + "maphot_shared.tmp" + " -v > " + overlappath + "maphot_subset.tmp" os.system(command) # export context-specific subset HOT regions (not-shared): k_outfile = b_outfile.replace("_cx", "_" + key.lower()) command = "cp " + overlappath + "maphot_subset.tmp" + " " + overlappath + k_outfile os.system(command) # index/re-name HOT regions with the respective key: indexColumns(overlappath + "maphot_subset.tmp", column=4, base="HOT-" + key + ".", header=False, extension="") # aggregate subset HOT regions (for context-wide analysis): if processed == list(): command = "cp " + overlappath + "maphot_subset.tmp" + " " + overlappath + "maphot_aggregate.tmp" os.system(command) else: command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + "maphot_current.tmp" os.system(command) command = "cat " + overlappath + "maphot_current.tmp" + " " + overlappath + "maphot_subset.tmp" + " > " + overlappath + "maphot_aggregate.tmp" os.system(command) # update processed keys: processed.append(key) # collapse context-wide subset HOT regions (not-shared): command = "mergeBed -i " + overlappath + "maphot_aggregate.tmp" + " -nms > " + overlappath + m_outfile os.system(command) # export context-wide subset HOT regions (not-shared); employ re-naming: #indexColumns(overlappath + "maphot_aggregate.tmp", column=4, base="HOT.", header=False, extension="") command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + b_outfile os.system(command) print "Peaks in subset HOT regions:", densityPeakCounter(overlappath + b_outfile) # find HOT regions that are unique to individual datasets: print "Finding dataset-specific (unique) HOT regions..." processed = list() for keyA in sorted(hotfile_dict.keys()): # prepare unique HOT regions for dataset A: command = 'grep -v "feature" ' + analysispath + hotfile_dict[keyA] + " > " + overlappath + "maphot_unique.tmp" os.system(command) # filter unique HOT regions for dataset A: for keyB in sorted(hotfile_dict.keys()): if keyA != keyB: # prepare HOT regions for dataset B: command = 'grep -v "feature" ' + analysispath + hotfile_dict[keyB] + " > " + overlappath + "maphot_subset.tmp" os.system(command) command = "cp " + overlappath + "maphot_unique.tmp" + " " + overlappath + "maphot_current.tmp" os.system(command) command = "intersectBed -a " + overlappath + "maphot_current.tmp" + " -b " + overlappath + "maphot_subset.tmp" + " -v > " + overlappath + "maphot_unique.tmp" os.system(command) # export unique HOT regions for dataset A; employ re-naming: k_outfile = u_outfile.replace("_cx", "_" + keyA.lower()) indexColumns(overlappath + "maphot_unique.tmp", column=4, base="HOT.", header=False, extension="") command = "cp " + overlappath + "maphot_unique.tmp" + " " + overlappath + k_outfile os.system(command) # index/re-name HOT regions with the respective key: indexColumns(overlappath + "maphot_unique.tmp", column=4, base="HOT-" + keyA + ".", header=False, extension="") # aggregate unique HOT regions: if processed == list(): command = "cp " + overlappath + "maphot_unique.tmp" + " " + overlappath + "maphot_aggregate.tmp" os.system(command) else: command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + "maphot_current.tmp" os.system(command) command = "cat " + overlappath + "maphot_current.tmp" + " " + overlappath + "maphot_unique.tmp" + " > " + overlappath + "maphot_aggregate.tmp" os.system(command) processed.append(key) # export aggregate unique HOT regions: #indexColumns(overlappath + "maphot_aggregate.tmp", column=4, base="HOT.", header=False, extension="") command = "cp " + overlappath + "maphot_aggregate.tmp" + " " + overlappath + u_outfile os.system(command) print "Peaks in unique HOT regions:", densityPeakCounter(overlappath + u_outfile) print # remove temporary files: command = "rm -rf " + overlappath + "*tmp" os.system(command) # filter or select input HOT regions that overlap with a given set of HOT regions: if "filter" in option.mode: # define filter/select operation flag if option.mode == "filter:remove": mode_flag = option.mode.replace(":","_") operation_flag = " -v" elif option.mode == "filter:select": mode_flag = option.mode.replace(":","_") operation_flag = " -u" elif option.mode == "filter:invert": mode_flag = option.mode.replace(":","_") operation_flag = " -u" # filter peak files... if option.peaks != "OFF": # load peak files: option.source = str(option.source + "/").replace("//","/") infiles = os.listdir(option.source) # update peaks path: peakspath = peakspath + option.peaks + "/" general.pathGenerator(peakspath) # filter peaks: for infile in infiles: if option.mode == "filter:remove": command = "intersectBed -a " + option.source + infile + " -b " + regionspath + option.infile + operation_flag + " > " + peakspath + infile os.system(command) elif option.mode == "filter:select": command = "intersectBed -a " + option.source + infile + " -b " + regionspath + option.infile + operation_flag + " > " + peakspath + infile os.system(command) # filter HOT region files... if option.peaks == "OFF": # update source path: sourcepath = hotpath + option.source + "/" # designate output file: f_outfile = "maphot_" + mode_flag + "_" + option.name + "_" + option.infile.replace("maphot_","") # filter out HOT regions that overlap : print print "Filtering HOT regions that overlap..." command = 'grep -v "feature" ' + analysispath + option.infile + " > " + analysispath + "maphot_infile.tmp" os.system(command) command = 'grep -v "feature" ' + sourcepath + option.target + " > " + analysispath + "maphot_target.tmp" os.system(command) if option.mode == "filter:remove": command = "intersectBed -a " + analysispath + "maphot_infile.tmp" + " -b " + analysispath + "maphot_target.tmp" + operation_flag + " > " + analysispath + "maphot_filtered.tmp" os.system(command) elif option.mode == "filter:select": command = "intersectBed -a " + analysispath + "maphot_infile.tmp" + " -b " + analysispath + "maphot_target.tmp" + operation_flag + " > " + analysispath + "maphot_filtered.tmp" os.system(command) elif option.mode == "filter:invert": command = "intersectBed -a " + analysispath + "maphot_target.tmp" + " -b " + analysispath + "maphot_infile.tmp" + operation_flag + " > " + analysispath + "maphot_filtered.tmp" os.system(command) # export filtered HOT regions: print "Exporting filtered HOT regions..." indexColumns(analysispath + "maphot_filtered.tmp", column=4, base="HOT.", header=False, extension="") # remove temporary files: command = "rm -rf " + analysispath + "*tmp" os.system(command) print # measure temperature of regions across different contexts: if option.mode == "temperature": # determine input density file: if option.gffkde == "ON": densityfile = "gffkde2_" + option.peaks + gffkde_handle + ".Peaks.Extended" else: densityfile = "mergeBed_" + option.peaks + "_compiled.bed" g_infile = densitypath + densityfile # set analysis metric and flag: if option.metric == "occupancy": metric_flag = "_occupan" elif option.metric == "density": metric_flag = "_density" elif option.metric == "complexity": metric_flag = "_complex" elif option.metric == "combined": metric_flag = "_combine" # update source path: sourcepath = hotpath + option.source + "/" # load target contexts: codeContexts, targetContexts = metrn.options_dict["contexts.extended"][option.contexts] # designate and open output file: f_outfile = "maphot_" + option.mode + "_" + option.peaks + "_" + codeContexts + "_" + option.infile.replace("maphot_","").replace(".bed","") + "_counts" n_outfile = "maphot_" + option.mode + "_" + option.peaks + "_" + codeContexts + "_" + option.infile.replace("maphot_","").replace(".bed","") + "_normal" a_outfile = "maphot_" + option.mode + "_" + option.peaks + "_" + codeContexts + "_" + option.infile.replace("maphot_","").replace(".bed","") + "_average" f_output = open(temperaturepath + f_outfile, "w") n_output = open(temperaturepath + n_outfile, "w") a_output = open(temperaturepath + a_outfile, "w") # collapse contexts and export header: header = ["region"] collapsedContexts = list() for context in targetContexts: if context in ["EE", "EM", "LE"]: if not "EX" in collapsedContexts: collapsedContexts.append("EX") else: collapsedContexts.append(context) header += collapsedContexts print >>f_output, "\t".join(header) print >>n_output, "\t".join(header) print >>a_output, "\t".join(["context", "mean", "st.dev", "percentile.75", "percentile.25"]) print print "Targeting contexts (total):", ",".join(targetContexts) print "Targeting contexts (collapsed):", ",".join(collapsedContexts) # generate a copy of the target HOT regions: t_infile = temperaturepath + "maphot_targets.tmp" command = "cp " + g_infile + " " + t_infile os.system(command) # scan HOT-regions! print print "Processing HOT-region overlaps..." hot_dict, k = dict(), 1 for inline in open(sourcepath + option.infile).readlines(): # load HOT-region information (individual region): chrm, start, end, region, occupancy, strand, density, complexity, factorCount, contextCount, infos = inline.strip().split("\t") k += 1 # make current region file: r_infile = temperaturepath + "maphot_region.tmp" r_outfile = open(r_infile, "w") print >>r_outfile, inline.strip() r_outfile.close() # determine overlap between query (genomic regions) and targeted HOT-region (i.e. extract overlap from background regions): #command = "cat " + g_infile + "| awk 'BEGIN{OFS=\"\\t\"; FS=\"\\t\"} {print $1, $4, $5, $3, $6, \"+\", $9}' > " + temperaturepath + "maphot_tinfile.tmp" #os.system(command) #command = "cat " + r_infile + "| awk 'BEGIN{OFS=\"\\t\"; FS=\"\\t\"} {print $1, $2, $3, $4, $5, $6, $7}' > " + temperaturepath + "maphot_rinfile.tmp" #os.system(command) #t_infile = temperaturepath + "maphot_tinfile.tmp" #r_infile = temperaturepath + "maphot_rinfile.tmp" command = "intersectBed -a " + t_infile + " -b " + r_infile + " -u > " + temperaturepath + "maphot_regions.tmp" os.system(command) # scan density in this region across contexts and load into dictionary: hot_dict[region] = dict() inlines = open(temperaturepath + "maphot_regions.tmp").readlines() for inline in inlines: items = inline.strip().split("\t") infos = items[10].split(";") infos.pop(0) for info in infos: if info != "": dataset, peak = info.split(":") organism, strain, factor, context, institute = dataset.split("_") for targetContext in targetContexts: if not targetContext in hot_dict[region]: hot_dict[region][targetContext] = 0 if context == targetContext: hot_dict[region][targetContext] +=1 # export counts and normalized data: #print print "Scoring HOT-region overlaps..." average_dict = dict() for inline in open(sourcepath + option.infile).readlines(): # load HOT-region information (individual region): chrm, start, end, region, occupancy, strand, density, complexity, factorCount, contextCount, infos = inline.strip().split("\t") # prepare matrix entry and store into average dictionary: counts = [region] for context in collapsedContexts: if not context in average_dict: average_dict[context] = list() hits = 0 if context == "EX": hitContexts = ["EE", "EM", "LE"] else: hitContexts = [context] for hitContext in hitContexts: if hitContext in hot_dict[region]: hits += hot_dict[region][hitContext] average_dict[context].append(hits) counts.append(hits) # normalize the counts: normal = [region] for count in counts[1:]: if counts[1] != 0: normal.append(float(count)/counts[1]) else: normal.append(0) # export normalized and unnormalized counts: print >>f_output, "\t".join(map(str, counts)) print >>n_output, "\t".join(map(str, normal)) # export averages : print "Exporting average overlaps..." for context in collapsedContexts: print >>a_output, "\t".join([context, str(numpy.mean(average_dict[context])), str(numpy.std(average_dict[context])), str(scipy.percentile(average_dict[context], 75)), str(scipy.percentile(average_dict[context], 25))]) print # close outputs: f_output.close() n_output.close() a_output.close() # remove temporary files: command = "rm -rf " + temperaturepath + "*tmp" os.system(command) if __name__ == "__main__": main() print "Completed:", time.asctime(time.localtime()) #montecarlo #simulation #collecting #downloader
claraya/meTRN
python/mapHOT.py
Python
mit
77,503
[ "BWA", "Bowtie" ]
16ab70fea5f6610f3bb7822891ec7c933a9e53815c751df75caa05968b2073e0
# -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import time import mock from mock import ANY from nose.tools import eq_ from datetime import datetime, timedelta from webtest import TestApp import bodhi.tests.functional.base from bodhi import main from bodhi.config import config from bodhi.models import ( Build, DBSession, Group, Package, Update, User, UpdateStatus, UpdateRequest, Release, ) YEAR = time.localtime().tm_year mock_valid_requirements = { 'target': 'bodhi.validators._get_valid_requirements', 'return_value': ['rpmlint', 'upgradepath'], } mock_taskotron_results = { 'target': 'bodhi.util.taskotron_results', 'return_value': [{ "outcome": "PASSED", "result_data": {}, "testcase": { "name": "rpmlint", } }], } mock_failed_taskotron_results = { 'target': 'bodhi.util.taskotron_results', 'return_value': [{ "outcome": "FAILED", "result_data": {}, "testcase": { "name": "rpmlint", } }], } mock_absent_taskotron_results = { 'target': 'bodhi.util.taskotron_results', 'return_value': [], } class TestUpdatesService(bodhi.tests.functional.base.BaseWSGICase): def test_home_html(self): resp = self.app.get('/', headers={'Accept': 'text/html'}) self.assertIn('Fedora Updates System', resp) self.assertIn('&copy;', resp) @mock.patch(**mock_valid_requirements) def test_invalid_build_name(self, *args): res = self.app.post_json('/updates/', self.get_update(u'bodhi-2.0-1.fc17,invalidbuild-1.0'), status=400) assert 'Build not in name-version-release format' in res, res @mock.patch(**mock_valid_requirements) def test_empty_build_name(self, *args): res = self.app.post_json('/updates/', self.get_update([u'']), status=400) self.assertEquals(res.json_body['errors'][0]['name'], 'builds.0') self.assertEquals(res.json_body['errors'][0]['description'], 'Required') @mock.patch(**mock_valid_requirements) def test_fail_on_edit_with_empty_build_list(self, *args): update = self.get_update() update['edited'] = update['builds'] # the update title.. update['builds'] = [] res = self.app.post_json('/updates/', update, status=400) self.assertEquals(len(res.json_body['errors']), 2) self.assertEquals(res.json_body['errors'][0]['name'], 'builds') self.assertEquals( res.json_body['errors'][0]['description'], 'You may not specify an empty list of builds.') self.assertEquals(res.json_body['errors'][1]['name'], 'builds') self.assertEquals( res.json_body['errors'][1]['description'], 'ACL validation mechanism was unable to determine ACLs.') @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_unicode_description(self, publish, *args): update = self.get_update('bodhi-2.0.0-2.fc17') update['notes'] = u'This is wünderfül' r = self.app.post_json('/updates/', update) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-2.fc17') self.assertEquals(up['notes'], u'This is wünderfül') self.assertIsNotNone(up['date_submitted']) publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) # FIXME: make it easy to tweak the tag of an update in our buildsys during unit tests #def test_invalid_tag(self): # session = DBSession() # map(session.delete, session.query(Update).all()) # map(session.delete, session.query(Build).all()) # num = session.query(Update).count() # assert num == 0, num # res = self.app.post_json('/updates/', self.get_update(u'bodhi-1.0-1.fc17'), # status=400) # assert 'Invalid tag' in res, res @mock.patch(**mock_valid_requirements) def test_duplicate_build(self, *args): res = self.app.post_json('/updates/', self.get_update([u'bodhi-2.0-2.fc17', u'bodhi-2.0-2.fc17']), status=400) assert 'Duplicate builds' in res, res @mock.patch(**mock_valid_requirements) def test_multiple_builds_of_same_package(self, *args): res = self.app.post_json('/updates/', self.get_update([u'bodhi-2.0-2.fc17', u'bodhi-2.0-3.fc17']), status=400) assert 'Multiple bodhi builds specified' in res, res @mock.patch(**mock_valid_requirements) def test_invalid_autokarma(self, *args): res = self.app.post_json('/updates/', self.get_update(stable_karma=-1), status=400) assert '-1 is less than minimum value 1' in res, res res = self.app.post_json('/updates/', self.get_update(unstable_karma=1), status=400) assert '1 is greater than maximum value -1' in res, res @mock.patch(**mock_valid_requirements) def test_duplicate_update(self, *args): res = self.app.post_json('/updates/', self.get_update(u'bodhi-2.0-1.fc17'), status=400) assert 'Update for bodhi-2.0-1.fc17 already exists' in res, res @mock.patch(**mock_valid_requirements) def test_invalid_requirements(self, *args): update = self.get_update() update['requirements'] = 'rpmlint silly-dilly' res = self.app.post_json('/updates/', update, status=400) assert 'Invalid requirement' in res, res @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_no_privs(self, publish, *args): session = DBSession() user = User(name=u'bodhi') session.add(user) session.flush() app = TestApp(main({}, testing=u'bodhi', **self.app_settings)) res = app.post_json('/updates/', self.get_update(u'bodhi-2.1-1.fc17'), status=400) assert 'bodhi does not have commit access to bodhi' in res, res self.assertEquals(publish.call_args_list, []) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_provenpackager_privs(self, publish, *args): "Ensure provenpackagers can push updates for any package" session = DBSession() user = User(name=u'bodhi') session.add(user) session.flush() group = session.query(Group).filter_by(name=u'provenpackager').one() user.groups.append(group) app = TestApp(main({}, testing=u'bodhi', **self.app_settings)) update = self.get_update(u'bodhi-2.1-1.fc17') update['csrf_token'] = app.get('/csrf').json_body['csrf_token'] res = app.post_json('/updates/', update) assert 'bodhi does not have commit access to bodhi' not in res, res build = session.query(Build).filter_by(nvr=u'bodhi-2.1-1.fc17').one() assert build.update is not None publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_provenpackager_edit_anything(self, publish, *args): "Ensure provenpackagers can edit updates for any package" nvr = u'bodhi-2.1-1.fc17' session = DBSession() user = User(name=u'lloyd') session.add(user) session.add(User(name=u'ralph')) # Add a non proventester session.flush() group = session.query(Group).filter_by(name=u'provenpackager').one() user.groups.append(group) app = TestApp(main({}, testing=u'ralph', **self.app_settings)) up_data = self.get_update(nvr) up_data['csrf_token'] = app.get('/csrf').json_body['csrf_token'] res = app.post_json('/updates/', up_data) assert 'does not have commit access to bodhi' not in res, res publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) app = TestApp(main({}, testing=u'lloyd', **self.app_settings)) update = self.get_update(nvr) update['csrf_token'] = app.get('/csrf').json_body['csrf_token'] update['notes'] = u'testing!!!' update['edited'] = nvr res = app.post_json('/updates/', update) assert 'bodhi does not have commit access to bodhi' not in res, res build = session.query(Build).filter_by(nvr=nvr).one() assert build.update is not None self.assertEquals(build.update.notes, u'testing!!!') #publish.assert_called_once_with( # topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_provenpackager_request_privs(self, publish, *args): "Ensure provenpackagers can change the request for any update" nvr = u'bodhi-2.1-1.fc17' session = DBSession() user = User(name=u'bob') session.add(user) session.add(User(name=u'ralph')) # Add a non proventester session.flush() group = session.query(Group).filter_by(name=u'provenpackager').one() user.groups.append(group) app = TestApp(main({}, testing=u'ralph', **self.app_settings)) up_data = self.get_update(nvr) up_data['csrf_token'] = app.get('/csrf').json_body['csrf_token'] res = app.post_json('/updates/', up_data) assert 'does not have commit access to bodhi' not in res, res publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) build = session.query(Build).filter_by(nvr=nvr).one() eq_(build.update.request, UpdateRequest.testing) # Try and submit the update to stable as a non-provenpackager app = TestApp(main({}, testing=u'ralph', **self.app_settings)) post_data = dict(update=nvr, request='stable', csrf_token=app.get('/csrf').json_body['csrf_token']) res = app.post_json('/updates/%s/request' % nvr, post_data, status=400) # Ensure we can't push it until it meets the requirements eq_(res.json_body['status'], 'error') eq_(res.json_body['errors'][0]['description'], config.get('not_yet_tested_msg')) update = session.query(Update).filter_by(title=nvr).one() eq_(update.stable_karma, 3) eq_(update.locked, False) eq_(update.request, UpdateRequest.testing) # Pretend it was pushed to testing update.request = None update.status = UpdateStatus.testing update.pushed = True session.flush() eq_(update.karma, 0) update.comment(u"foo", 1, u'foo') update = session.query(Update).filter_by(title=nvr).one() eq_(update.karma, 1) eq_(update.request, None) update.comment(u"foo", 1, u'bar') update = session.query(Update).filter_by(title=nvr).one() eq_(update.karma, 2) eq_(update.request, None) update.comment(u"foo", 1, u'biz') update = session.query(Update).filter_by(title=nvr).one() eq_(update.karma, 3) eq_(update.request, UpdateRequest.stable) # Set it back to testing update.request = UpdateRequest.testing # Try and submit the update to stable as a proventester app = TestApp(main({}, testing=u'bob', **self.app_settings)) res = app.post_json('/updates/%s/request' % nvr, dict(update=nvr, request='stable', csrf_token=app.get('/csrf').json_body['csrf_token']), status=200) eq_(res.json_body['update']['request'], 'stable') app = TestApp(main({}, testing=u'bob', **self.app_settings)) res = app.post_json('/updates/%s/request' % nvr, dict(update=nvr, request='obsolete', csrf_token=app.get('/csrf').json_body['csrf_token']), status=200) eq_(res.json_body['update']['request'], None) eq_(update.request, None) eq_(update.status, UpdateStatus.obsolete) @mock.patch(**mock_valid_requirements) def test_pkgdb_outage(self, *args): "Test the case where our call to the pkgdb throws an exception" settings = self.app_settings.copy() settings['acl_system'] = 'pkgdb' settings['pkgdb_url'] = 'invalidurl' app = TestApp(main({}, testing=u'guest', **settings)) update = self.get_update(u'bodhi-2.0-2.fc17') update['csrf_token'] = app.get('/csrf').json_body['csrf_token'] res = app.post_json('/updates/', update, status=400) assert "Unable to access the Package Database" in res, res @mock.patch(**mock_valid_requirements) def test_invalid_acl_system(self, *args): settings = self.app_settings.copy() settings['acl_system'] = 'null' app = TestApp(main({}, testing=u'guest', **settings)) res = app.post_json('/updates/', self.get_update(u'bodhi-2.0-2.fc17'), status=400) assert "guest does not have commit access to bodhi" in res, res def test_404(self): self.app.get('/a', status=404) def test_get_single_update(self): res = self.app.get('/updates/bodhi-2.0-1.fc17') self.assertEquals(res.json_body['update']['title'], 'bodhi-2.0-1.fc17') self.assertIn('application/json', res.headers['Content-Type']) def test_get_single_update_jsonp(self): res = self.app.get('/updates/bodhi-2.0-1.fc17', {'callback': 'callback'}, headers={'Accept': 'application/javascript'}) self.assertIn('application/javascript', res.headers['Content-Type']) self.assertIn('callback', res) self.assertIn('bodhi-2.0-1.fc17', res) def test_get_single_update_rss(self): self.app.get('/updates/bodhi-2.0-1.fc17', headers={'Accept': 'application/atom+xml'}, status=406) def test_get_single_update_html(self): id = 'bodhi-2.0-1.fc17' resp = self.app.get('/updates/%s' % id, headers={'Accept': 'text/html'}) self.assertIn('text/html', resp.headers['Content-Type']) self.assertIn(id, resp) self.assertIn('&copy;', resp) def test_list_updates(self): res = self.app.get('/updates/') body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['submitter'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_jsonp(self): res = self.app.get('/updates/', {'callback': 'callback'}, headers={'Accept': 'application/javascript'}) self.assertIn('application/javascript', res.headers['Content-Type']) self.assertIn('callback', res) self.assertIn('bodhi-2.0-1.fc17', res) def test_list_updates_rss(self): res = self.app.get('/updates/', headers={'Accept': 'application/atom+xml'}) self.assertIn('application/rss+xml', res.headers['Content-Type']) self.assertIn('bodhi-2.0-1.fc17', res) def test_list_updates_html(self): res = self.app.get('/updates/', headers={'Accept': 'text/html'}) self.assertIn('text/html', res.headers['Content-Type']) self.assertIn('bodhi-2.0-1.fc17', res) self.assertIn('&copy;', res) def test_search_updates(self): res = self.app.get('/updates/', {'like': 'odh'}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') res = self.app.get('/updates/', {'like': 'wat'}) body = res.json_body self.assertEquals(len(body['updates']), 0) def test_list_updates_pagination(self): # First, stuff a second update in there self.test_new_update() # Then, test pagination res = self.app.get('/updates/', {"rows_per_page": 1}) body = res.json_body self.assertEquals(len(body['updates']), 1) update1 = body['updates'][0] res = self.app.get('/updates/', {"rows_per_page": 1, "page": 2}) body = res.json_body self.assertEquals(len(body['updates']), 1) update2 = body['updates'][0] self.assertNotEquals(update1, update2) def test_list_updates_by_approved_since(self): now = datetime.utcnow() # Try with no approved updates first res = self.app.get('/updates/', {"approved_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 0) # Now approve one session = DBSession() session.query(Update).first().date_approved = now session.flush() # And try again res = self.app.get('/updates/', {"approved_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_approved'], now.strftime("%Y-%m-%d %H:%M:%S")) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(len(up['bugs']), 1) self.assertEquals(up['bugs'][0]['bug_id'], 12345) # https://github.com/fedora-infra/bodhi/issues/270 self.assertEquals(len(up['test_cases']), 1) self.assertEquals(up['test_cases'][0]['name'], u'Wat') def test_list_updates_by_invalid_approved_since(self): res = self.app.get('/updates/', {"approved_since": "forever"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'approved_since') self.assertEquals(res.json_body['errors'][0]['description'], 'Invalid date') def test_list_updates_by_bugs(self): res = self.app.get('/updates/', {"bugs": '12345'}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(len(up['bugs']), 1) self.assertEquals(up['bugs'][0]['bug_id'], 12345) def test_list_updates_by_invalid_bug(self): res = self.app.get('/updates/', {"bugs": "cockroaches"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'bugs') self.assertEquals(res.json_body['errors'][0]['description'], "Invalid bug ID specified: [u'cockroaches']") def test_list_updates_by_unexisting_bug(self): res = self.app.get('/updates/', {"bugs": "19850110"}) body = res.json_body self.assertEquals(len(body['updates']), 0) def test_list_updates_by_critpath(self): res = self.app.get('/updates/', {"critpath": "false"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_invalid_critpath(self): res = self.app.get('/updates/', {"critpath": "lalala"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'critpath') self.assertEquals(res.json_body['errors'][0]['description'], '"lalala" is neither in (\'false\', \'0\') nor in (\'true\', \'1\')') def test_list_updates_by_cves(self): res = self.app.get("/updates/", {"cves": "CVE-1985-0110"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(up['cves'][0]['cve_id'], "CVE-1985-0110") def test_list_updates_by_unexisting_cve(self): res = self.app.get('/updates/', {"cves": "CVE-2013-1015"}) body = res.json_body self.assertEquals(len(body['updates']), 0) def test_list_updates_by_invalid_cve(self): res = self.app.get('/updates/', {"cves": "WTF-ZOMG-BBQ"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'cves.0') self.assertEquals(res.json_body['errors'][0]['description'], '"WTF-ZOMG-BBQ" is not a valid CVE id') def test_list_updates_by_date_submitted_invalid_date(self): """test filtering by submitted date with an invalid date""" res = self.app.get('/updates/', {"submitted_since": "11-01-1984"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(body['errors'][0]['name'], 'submitted_since') self.assertEquals(body['errors'][0]['description'], 'Invalid date') def test_list_updates_by_date_submitted_future_date(self): """test filtering by submitted date with future date""" tomorrow = datetime.utcnow() + timedelta(days=1) tomorrow = tomorrow.strftime("%Y-%m-%d") res = self.app.get('/updates/', {"submitted_since": tomorrow}) body = res.json_body self.assertEquals(len(body['updates']), 0) def test_list_updates_by_date_submitted_valid(self): """test filtering by submitted date with valid data""" res = self.app.get('/updates/', {"submitted_since": "1984-11-01"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_locked(self): res = self.app.get('/updates/', {"locked": "false"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_invalid_locked(self): res = self.app.get('/updates/', {"locked": "maybe"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'locked') self.assertEquals(res.json_body['errors'][0]['description'], '"maybe" is neither in (\'false\', \'0\') nor in (\'true\', \'1\')') def test_list_updates_by_modified_since(self): now = datetime.utcnow() # Try with no modified updates first res = self.app.get('/updates/', {"modified_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 0) # Now approve one session = DBSession() session.query(Update).first().date_modified = now session.flush() # And try again res = self.app.get('/updates/', {"modified_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], now.strftime("%Y-%m-%d %H:%M:%S")) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(len(up['bugs']), 1) self.assertEquals(up['bugs'][0]['bug_id'], 12345) def test_list_updates_by_invalid_modified_since(self): res = self.app.get('/updates/', {"modified_since": "the dawn of time"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'modified_since') self.assertEquals(res.json_body['errors'][0]['description'], 'Invalid date') def test_list_updates_by_package(self): res = self.app.get('/updates/', {"packages": "bodhi"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_builds(self): res = self.app.get('/updates/', {"builds": "bodhi-3.0-1.fc17"}) body = res.json_body self.assertEquals(len(body['updates']), 0) res = self.app.get('/updates/', {"builds": "bodhi-2.0-1.fc17"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_package(self): res = self.app.get('/updates/', {"packages": "flash-player"}) body = res.json_body self.assertEquals(len(body['updates']), 0) def test_list_updates_by_pushed(self): res = self.app.get('/updates/', {"pushed": "false"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(up['pushed'], False) def test_list_updates_by_invalid_pushed(self): res = self.app.get('/updates/', {"pushed": "who knows?"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'pushed') self.assertEquals(res.json_body['errors'][0]['description'], '"who knows?" is neither in (\'false\', \'0\') nor in (\'true\', \'1\')') def test_list_updates_by_pushed_since(self): now = datetime.utcnow() # Try with no pushed updates first res = self.app.get('/updates/', {"pushed_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 0) # Now approve one session = DBSession() session.query(Update).first().date_pushed = now session.flush() # And try again res = self.app.get('/updates/', {"pushed_since": now.strftime("%Y-%m-%d")}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], now.strftime("%Y-%m-%d %H:%M:%S")) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) self.assertEquals(len(up['bugs']), 1) self.assertEquals(up['bugs'][0]['bug_id'], 12345) def test_list_updates_by_invalid_pushed_since(self): res = self.app.get('/updates/', {"pushed_since": "a while ago"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'pushed_since') self.assertEquals(res.json_body['errors'][0]['description'], 'Invalid date') def test_list_updates_by_release_name(self): res = self.app.get('/updates/', {"releases": "F17"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_release_version(self): res = self.app.get('/updates/', {"releases": "17"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_release(self): res = self.app.get('/updates/', {"releases": "WinXP"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'releases') self.assertEquals(res.json_body['errors'][0]['description'], 'Invalid releases specified: WinXP') def test_list_updates_by_request(self): res = self.app.get('/updates/', {'request': "testing"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_request(self): res = self.app.get('/updates/', {"request": "impossible"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'request') self.assertEquals(res.json_body['errors'][0]['description'], '"impossible" is not one of unpush, testing, revoke,' ' obsolete, stable') def test_list_updates_by_severity(self): res = self.app.get('/updates/', {"severity": "unspecified"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_severity(self): res = self.app.get('/updates/', {"severity": "schoolmaster"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'severity') self.assertEquals(res.json_body['errors'][0]['description'], '"schoolmaster" is not one of high, urgent, medium, low, unspecified') def test_list_updates_by_status(self): res = self.app.get('/updates/', {"status": "pending"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_status(self): res = self.app.get('/updates/', {"status": "single"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'status') self.assertEquals(res.json_body['errors'][0]['description'], '"single" is not one of testing, processing, obsolete, stable, unpushed, pending') def test_list_updates_by_suggest(self): res = self.app.get('/updates/', {"suggest": "unspecified"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_suggest(self): res = self.app.get('/updates/', {"suggest": "no idea"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'suggest') self.assertEquals(res.json_body['errors'][0]['description'], '"no idea" is not one of logout, reboot, unspecified') def test_list_updates_by_type(self): res = self.app.get('/updates/', {"type": "bugfix"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_type(self): res = self.app.get('/updates/', {"type": "not_my"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'type') self.assertEquals(res.json_body['errors'][0]['description'], '"not_my" is not one of newpackage, bugfix, security, enhancement') def test_list_updates_by_username(self): res = self.app.get('/updates/', {"user": "guest"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'Useful details!') self.assertEquals(up['date_submitted'], u'1984-11-02 00:00:00') self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0001' % YEAR) self.assertEquals(up['karma'], 1) def test_list_updates_by_unexisting_username(self): res = self.app.get('/updates/', {"user": "santa"}, status=400) body = res.json_body self.assertEquals(len(body.get('updates', [])), 0) self.assertEquals(res.json_body['errors'][0]['name'], 'user') self.assertEquals(res.json_body['errors'][0]['description'], "Invalid user specified: santa") def test_put_json_update(self): self.app.put_json('/updates/', self.get_update(), status=405) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_post_json_update(self, publish, *args): self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-1.fc17')) publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_new_update(self, publish, *args): r = self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-2.fc17')) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-2.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'this is a test update') self.assertIsNotNone(up['date_submitted']) self.assertEquals(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0002' % YEAR) self.assertEquals(up['karma'], 0) self.assertEquals(up['requirements'], 'rpmlint') publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_new_update_with_multiple_bugs(self, publish, *args): update = self.get_update('bodhi-2.0.0-2.fc17') update['bugs'] = ['1234', '5678'] r = self.app.post_json('/updates/', update) up = r.json_body self.assertEquals(len(up['bugs']), 2) self.assertEquals(up['bugs'][0]['bug_id'], 1234) self.assertEquals(up['bugs'][1]['bug_id'], 5678) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_new_update_with_multiple_bugs_as_str(self, publish, *args): update = self.get_update('bodhi-2.0.0-2.fc17') update['bugs'] = '1234, 5678' r = self.app.post_json('/updates/', update) up = r.json_body self.assertEquals(len(up['bugs']), 2) self.assertEquals(up['bugs'][0]['bug_id'], 1234) self.assertEquals(up['bugs'][1]['bug_id'], 5678) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_new_update_with_invalid_bugs_as_str(self, publish, *args): update = self.get_update('bodhi-2.0.0-2.fc17') update['bugs'] = '1234, blargh' r = self.app.post_json('/updates/', update, status=400) up = r.json_body self.assertEquals(up['status'], 'error') self.assertEquals(up['errors'][0]['description'], "Invalid bug ID specified: [u'1234', u'blargh']") @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_update(self, publish, *args): args = self.get_update('bodhi-2.0.0-2.fc17') r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' args['requirements'] = 'upgradepath' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-3.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['user']['name'], u'guest') self.assertEquals(up['release']['name'], u'F17') self.assertEquals(up['type'], u'bugfix') self.assertEquals(up['severity'], u'unspecified') self.assertEquals(up['suggest'], u'unspecified') self.assertEquals(up['close_bugs'], True) self.assertEquals(up['notes'], u'this is a test update') self.assertIsNotNone(up['date_submitted']) self.assertIsNotNone(up['date_modified'], None) self.assertEquals(up['date_approved'], None) self.assertEquals(up['date_pushed'], None) self.assertEquals(up['locked'], False) self.assertEquals(up['alias'], u'FEDORA-%s-0002' % YEAR) self.assertEquals(up['karma'], 0) self.assertEquals(up['requirements'], 'upgradepath') self.assertEquals(up['comments'][-1]['text'], u'guest edited this update. New build(s): ' + u'bodhi-2.0.0-3.fc17. Removed build(s): bodhi-2.0.0-2.fc17.') self.assertEquals(len(up['builds']), 1) self.assertEquals(up['builds'][0]['nvr'], u'bodhi-2.0.0-3.fc17') self.assertEquals(DBSession.query(Build).filter_by(nvr=u'bodhi-2.0.0-2.fc17').first(), None) self.assertEquals(len(publish.call_args_list), 2) publish.assert_called_with(topic='update.edit', msg=ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_testing_update_with_new_builds(self, publish, *args): nvr = u'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) # Mark it as testing upd = Update.get(nvr, self.db) upd.status = UpdateStatus.testing upd.request = None self.db.flush() args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-3.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') #assert False, '\n'.join([c['text'] for c in up['comments']]) self.assertEquals(up['comments'][-1]['text'], u'This update has been submitted for testing by guest. ') self.assertEquals(up['comments'][-2]['text'], u'guest edited this update. New build(s): ' + u'bodhi-2.0.0-3.fc17. Removed build(s): bodhi-2.0.0-2.fc17.') self.assertEquals(up['comments'][-3]['text'], u'This update has been submitted for testing by guest. ') self.assertEquals(len(up['builds']), 1) self.assertEquals(up['builds'][0]['nvr'], u'bodhi-2.0.0-3.fc17') self.assertEquals(DBSession.query(Build).filter_by(nvr=u'bodhi-2.0.0-2.fc17').first(), None) self.assertEquals(len(publish.call_args_list), 3) publish.assert_called_with(topic='update.edit', msg=ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_testing_update_with_new_builds_with_stable_request(self, publish, *args): nvr = u'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) # Mark it as testing upd = Update.get(nvr, self.db) upd.status = UpdateStatus.testing upd.request = UpdateRequest.stable self.db.flush() args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-3.fc17') self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') self.assertEquals(up['comments'][-1]['text'], u'This update has been submitted for testing by guest. ') self.assertEquals(up['comments'][-2]['text'], u'guest edited this update. New build(s): ' + u'bodhi-2.0.0-3.fc17. Removed build(s): bodhi-2.0.0-2.fc17.') self.assertEquals(up['comments'][-3]['text'], u'This update has been submitted for testing by guest. ') self.assertEquals(len(up['builds']), 1) self.assertEquals(up['builds'][0]['nvr'], u'bodhi-2.0.0-3.fc17') self.assertEquals(DBSession.query(Build).filter_by(nvr=u'bodhi-2.0.0-2.fc17').first(), None) self.assertEquals(len(publish.call_args_list), 3) publish.assert_called_with(topic='update.edit', msg=ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_update_with_different_release(self, publish, *args): """Test editing an update for one release with builds from another.""" nvr = 'bodhi-2.0.0-2.fc17' args = self.get_update('bodhi-2.0.0-2.fc17') r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) # Add another release and package Release._tag_cache = None release = Release( name=u'F18', long_name=u'Fedora 18', id_prefix=u'FEDORA', version=u'18', dist_tag=u'f18', stable_tag=u'f18-updates', testing_tag=u'f18-updates-testing', candidate_tag=u'f18-updates-candidate', pending_testing_tag=u'f18-updates-testing-pending', pending_stable_tag=u'f18-updates-pending', override_tag=u'f18-override', branch=u'f18') DBSession.add(release) pkg = Package(name=u'nethack') DBSession.add(pkg) args = self.get_update('bodhi-2.0.0-2.fc17,nethack-4.0.0-1.fc18') args['edited'] = nvr r = self.app.post_json('/updates/', args, status=400) up = r.json_body self.assertEquals(up['status'], 'error') self.assertEquals(up['errors'][0]['description'], 'Cannot add a F18 build to an F17 update') @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_cascade_package_requirements_to_update(self, publish, *args): package = DBSession.query(Package).filter_by(name=u'bodhi').one() package.requirements = u'upgradepath rpmlint' DBSession.flush() args = self.get_update(u'bodhi-2.0.0-3.fc17') # Don't specify any requirements so that they cascade from the package del args['requirements'] r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['title'], u'bodhi-2.0.0-3.fc17') self.assertEquals(up['requirements'], 'upgradepath rpmlint') publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_stable_update(self, publish, *args): """Make sure we can't edit stable updates""" self.assertEquals(publish.call_args_list, []) # First, create a testing update nvr = 'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) r = self.app.post_json('/updates/', args, status=200) publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) # Then, switch it to stable behind the scenes up = DBSession.query(Update).filter_by(title=nvr).one() up.status = UpdateStatus.stable # Then, try to edit it through the api again args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' r = self.app.post_json('/updates/', args, status=400) up = r.json_body self.assertEquals(up['status'], 'error') self.assertEquals(up['errors'][0]['description'], "Cannot edit stable updates") self.assertEquals(len(publish.call_args_list), 1) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_locked_update(self, publish, *args): """Make sure some changes are prevented""" nvr = 'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) r = self.app.post_json('/updates/', args, status=200) publish.assert_called_with(topic='update.request.testing', msg=ANY) up = DBSession.query(Update).filter_by(title=nvr).one() up.locked = True up.status = UpdateRequest.testing up.request = None up_id = up.id build = DBSession.query(Build).filter_by(nvr=nvr).one() # Changing the notes should work args['edited'] = args['builds'] args['notes'] = 'Some new notes' up = self.app.post_json('/updates/', args, status=200).json_body self.assertEquals(up['notes'], 'Some new notes') # Changing the builds should fail args['notes'] = 'And yet some other notes' args['builds'] = 'bodhi-2.0.0-3.fc17' r = self.app.post_json('/updates/', args, status=400).json_body self.assertEquals(r['status'], 'error') self.assertIn('errors', r) self.assertIn({u'description': u"Can't add builds to a locked update", u'location': u'body', u'name': u'builds'}, r['errors']) up = DBSession.query(Update).get(up_id) self.assertEquals(up.notes, 'Some new notes') self.assertEquals(up.builds, [build]) # Changing the request should fail args['notes'] = 'Still new notes' args['builds'] = args['edited'] args['request'] = 'stable' r = self.app.post_json('/updates/', args, status=400).json_body self.assertEquals(r['status'], 'error') self.assertIn('errors', r) self.assertIn({u'description': u"Can't change the request on a " "locked update", u'location': u'body', u'name': u'builds'}, r['errors']) up = DBSession.query(Update).get(up_id) self.assertEquals(up.notes, 'Some new notes') self.assertEquals(up.builds, [build]) self.assertEquals(up.request, None) # At the end of the day, two fedmsg messages should have gone out. self.assertEquals(len(publish.call_args_list), 2) publish.assert_called_with(topic='update.edit', msg=ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_push_untested_critpath_to_release(self, publish, *args): """ Ensure that we cannot push an untested critpath update directly to stable. """ args = self.get_update('kernel-3.11.5-300.fc17') args['request'] = 'stable' up = self.app.post_json('/updates/', args).json_body self.assertTrue(up['critpath']) self.assertEquals(up['request'], 'testing') publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_obsoletion(self, publish, *args): nvr = 'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) self.app.post_json('/updates/', args) publish.assert_called_once_with( topic='update.request.testing', msg=mock.ANY) publish.call_args_list = [] up = DBSession.query(Update).filter_by(title=nvr).one() up.status = UpdateStatus.testing up.request = None args = self.get_update('bodhi-2.0.0-3.fc17') r = self.app.post_json('/updates/', args).json_body self.assertEquals(r['request'], 'testing') # Since we're obsoleting something owned by someone else. self.assertEquals(r['caveats'][0]['description'], 'This update has obsoleted bodhi-2.0.0-2.fc17, ' 'and has inherited its bugs and notes.') # Check for the comment multiple ways self.assertEquals(r['comments'][-1]['text'], u'This update has obsoleted bodhi-2.0.0-2.fc17, ' 'and has inherited its bugs and notes.') publish.assert_called_with( topic='update.request.testing', msg=mock.ANY) up = DBSession.query(Update).filter_by(title=nvr).one() self.assertEquals(up.status, UpdateStatus.obsolete) self.assertEquals(up.comments[-1].text, u'This update has been obsoleted by bodhi-2.0.0-3.fc17.') @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_obsoletion_with_open_request(self, publish, *args): nvr = 'bodhi-2.0.0-2.fc17' args = self.get_update(nvr) self.app.post_json('/updates/', args) args = self.get_update('bodhi-2.0.0-3.fc17') r = self.app.post_json('/updates/', args).json_body self.assertEquals(r['request'], 'testing') up = DBSession.query(Update).filter_by(title=nvr).one() self.assertEquals(up.status, UpdateStatus.pending) self.assertEquals(up.request, UpdateRequest.testing) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) def test_invalid_request(self, *args): """Test submitting an invalid request""" args = self.get_update() resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'foo','csrf_token': self.get_csrf_token()}, status=400) resp = resp.json_body eq_(resp['status'], 'error') eq_(resp['errors'][0]['description'], u'"foo" is not one of unpush, testing, revoke, obsolete, stable') # Now try with None resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': None, 'csrf_token': self.get_csrf_token()}, status=400) resp = resp.json_body eq_(resp['status'], 'error') eq_(resp['errors'][0]['name'], 'request') eq_(resp['errors'][0]['description'], 'Required') @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_testing_request(self, publish, *args): """Test submitting a valid testing request""" args = self.get_update() args['request'] = None resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'testing', 'csrf_token': self.get_csrf_token()}) eq_(resp.json['update']['request'], 'testing') self.assertEquals(publish.call_args_list, []) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) def test_invalid_stable_request(self, *args): """Test submitting a stable request for an update that has yet to meet the stable requirements""" args = self.get_update() resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'stable', 'csrf_token': self.get_csrf_token()}, status=400) eq_(resp.json['status'], 'error') eq_(resp.json['errors'][0]['description'], config.get('not_yet_tested_msg')) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_stable_request_after_testing(self, publish, *args): """Test submitting a stable request to an update that has met the minimum amount of time in testing""" args = self.get_update('bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) up = DBSession.query(Update).filter_by(title=resp.json['title']).one() up.status = UpdateStatus.testing up.request = None up.comment('This update has been pushed to testing', author='bodhi') up.date_testing = up.comments[-1].timestamp - timedelta(days=7) DBSession.flush() eq_(up.days_in_testing, 7) eq_(up.meets_testing_requirements, True) resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'stable', 'csrf_token': self.get_csrf_token()}) eq_(resp.json['update']['request'], 'stable') publish.assert_called_with( topic='update.request.stable', msg=mock.ANY) @mock.patch(**mock_failed_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_stable_request_failed_taskotron_results(self, publish, *args): """Test submitting a stable request, but with bad taskotron results""" args = self.get_update('bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) up = DBSession.query(Update).filter_by(title=resp.json['title']).one() up.status = UpdateStatus.testing up.request = None up.comment('This update has been pushed to testing', author='bodhi') up.date_testing = up.comments[-1].timestamp - timedelta(days=7) DBSession.flush() eq_(up.days_in_testing, 7) eq_(up.meets_testing_requirements, True) resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'stable', 'csrf_token': self.get_csrf_token()}, status=400) self.assertIn('errors', resp) self.assertIn('Required task', resp) @mock.patch(**mock_absent_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_stable_request_absent_taskotron_results(self, publish, *args): """Test submitting a stable request, but with absent task results""" args = self.get_update('bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) up = DBSession.query(Update).filter_by(title=resp.json['title']).one() up.status = UpdateStatus.testing up.request = None up.comment('This update has been pushed to testing', author='bodhi') up.date_testing = up.comments[-1].timestamp - timedelta(days=7) DBSession.flush() eq_(up.days_in_testing, 7) eq_(up.meets_testing_requirements, True) resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'stable', 'csrf_token': self.get_csrf_token()}, status=400) self.assertIn('errors', resp) self.assertIn('No result found for', resp) @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_stable_request_when_stable(self, publish, *args): """Test submitting a stable request to an update that already been pushed to stable""" args = self.get_update('bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) up = self.db.query(Update).filter_by(title=resp.json['title']).one() up.status = UpdateStatus.stable up.request = None up.comment('This update has been pushed to testing', author='bodhi') up.date_testing = up.comments[-1].timestamp - timedelta(days=14) up.comment('This update has been pushed to stable', author='bodhi') self.db.flush() eq_(up.days_in_testing, 14) eq_(up.meets_testing_requirements, True) resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'stable', 'csrf_token': self.get_csrf_token()}) eq_(resp.json['update']['status'], 'stable') eq_(resp.json['update']['request'], None) try: publish.assert_called_with( topic='update.request.stable', msg=mock.ANY) assert False, "request.stable fedmsg shouldn't have fired" except AssertionError: pass @mock.patch(**mock_taskotron_results) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_testing_request_when_testing(self, publish, *args): """Test submitting a testing request to an update that already been pushed to testing""" args = self.get_update('bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) up = self.db.query(Update).filter_by(title=resp.json['title']).one() up.status = UpdateStatus.testing up.request = None up.comment('This update has been pushed to testing', author='bodhi') up.date_testing = up.comments[-1].timestamp - timedelta(days=14) self.db.flush() eq_(up.days_in_testing, 14) eq_(up.meets_testing_requirements, True) resp = self.app.post_json( '/updates/%s/request' % args['builds'], {'request': 'testing', 'csrf_token': self.get_csrf_token()}) eq_(resp.json['update']['status'], 'testing') eq_(resp.json['update']['request'], None) try: publish.assert_called_with( topic='update.request.testing', msg=mock.ANY) assert False, "request.testing fedmsg shouldn't have fired" except AssertionError: pass @mock.patch(**mock_valid_requirements) def test_new_update_with_existing_build(self, *args): """Test submitting a new update with a build already in the database""" session = DBSession() package = Package.get('bodhi', session) session.add(Build(nvr=u'bodhi-2.0.0-3.fc17', package=package)) session.flush() args = self.get_update(u'bodhi-2.0.0-3.fc17') resp = self.app.post_json('/updates/', args) eq_(resp.json['title'], 'bodhi-2.0.0-3.fc17') @mock.patch(**mock_valid_requirements) def test_update_with_older_build_in_testing_from_diff_user(self, r): """ Test submitting an update for a package that has an older build within a multi-build update currently in testing submitted by a different maintainer. https://github.com/fedora-infra/bodhi/issues/78 """ session = DBSession() title = u'bodhi-2.0-2.fc17 python-3.0-1.fc17' args = self.get_update(title) resp = self.app.post_json('/updates/', args) newuser = User(name=u'bob') session.add(newuser) up = session.query(Update).filter_by(title=title).one() up.status = UpdateStatus.testing up.request = None up.user = newuser session.flush() newtitle = u'bodhi-2.0-3.fc17' args = self.get_update(newtitle) resp = self.app.post_json('/updates/', args) # Note that this does **not** obsolete the other update print resp.json_body['caveats'] self.assertEquals(len(resp.json_body['caveats']), 1) self.assertEquals(resp.json_body['caveats'][0]['description'], "Please be aware that there is another update in " "flight owned by bob, containing " "bodhi-2.0-2.fc17. Are you coordinating with " "them?") # Ensure the second update was created successfully session.query(Update).filter_by(title=newtitle).one() @mock.patch(**mock_valid_requirements) def test_updateid_alias(self, *args): res = self.app.post_json('/updates/', self.get_update(u'bodhi-2.0.0-3.fc17')) json = res.json_body self.assertEquals(json['alias'], json['updateid']) def test_list_updates_by_lowercase_release_name(self): res = self.app.get('/updates/', {"releases": "f17"}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], u'bodhi-2.0-1.fc17') def test_redirect_to_package(self): "When you visit /updates/package, redirect to /updates/?packages=..." res = self.app.get('/updates/bodhi', status=302) target = 'http://localhost/updates/?packages=bodhi' self.assertEquals(res.headers['Location'], target) # But be sure that we don't redirect if the package doesn't exist res = self.app.get('/updates/non-existant', status=404) def test_list_updates_by_alias_and_updateid(self): upd = self.db.query(Update).filter(Update.alias != None).first() res = self.app.get('/updates/', {"alias": upd.alias}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], upd.title) self.assertEquals(up['alias'], upd.alias) res = self.app.get('/updates/', {"updateid": upd.alias}) body = res.json_body self.assertEquals(len(body['updates']), 1) up = body['updates'][0] self.assertEquals(up['title'], upd.title) res = self.app.get('/updates/', {"updateid": 'BLARG'}) body = res.json_body self.assertEquals(len(body['updates']), 0) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_submitting_multi_release_updates(self, publish, *args): """ https://github.com/fedora-infra/bodhi/issues/219 """ # Add another release and package Release._tag_cache = None release = Release( name=u'F18', long_name=u'Fedora 18', id_prefix=u'FEDORA', version=u'18', dist_tag=u'f18', stable_tag=u'f18-updates', testing_tag=u'f18-updates-testing', candidate_tag=u'f18-updates-candidate', pending_testing_tag=u'f18-updates-testing-pending', pending_stable_tag=u'f18-updates-pending', override_tag=u'f18-override', branch=u'f18') DBSession.add(release) pkg = Package(name=u'nethack') DBSession.add(pkg) # A multi-release submission!!! This should create *two* updates args = self.get_update('bodhi-2.0.0-2.fc17,bodhi-2.0.0-2.fc18') r = self.app.post_json('/updates/', args) data = r.json_body self.assertIn('caveats', data) import pprint; pprint.pprint(data['caveats']) self.assertEquals(len(data['caveats']), 1) self.assertEquals(data['caveats'][0]['description'], "Your update is being split into 2, one for each release.") self.assertIn('updates', data) self.assertEquals(len(data['updates']), 2) publish.assert_called_with(topic='update.request.testing', msg=ANY) # Make sure two fedmsg messages were published self.assertEquals(len(publish.call_args_list), 2) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_update_bugs(self, publish, *args): build = 'bodhi-2.0.0-2.fc17' args = self.get_update('bodhi-2.0.0-2.fc17') args['bugs'] = '56789' r = self.app.post_json('/updates/', args) self.assertEquals(len(r.json['bugs']), 1) publish.assert_called_with(topic='update.request.testing', msg=ANY) # Pretend it was pushed to testing update = self.db.query(Update).filter_by(title=build).one() update.request = None update.status = UpdateStatus.testing update.pushed = True self.db.flush() # Mark it as testing args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' args['bugs'] = '56789,98765' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(len(up['bugs']), 2) bug_ids = [bug['bug_id'] for bug in up['bugs']] self.assertIn(56789, bug_ids) self.assertIn(98765, bug_ids) self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') # now remove a bug args['edited'] = args['builds'] args['builds'] = 'bodhi-2.0.0-3.fc17' args['bugs'] = '98765' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(len(up['bugs']), 1) bug_ids = [bug['bug_id'] for bug in up['bugs']] self.assertIn(98765, bug_ids) self.assertEquals(up['status'], u'pending') self.assertEquals(up['request'], u'testing') @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_update_and_disable_features(self, publish, *args): build = 'bodhi-2.0.0-2.fc17' args = self.get_update('bodhi-2.0.0-2.fc17') r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) up = r.json_body self.assertEquals(up['require_testcases'], True) self.assertEquals(up['require_bugs'], False) self.assertEquals(up['stable_karma'], 3) self.assertEquals(up['unstable_karma'], -3) # Pretend it was pushed to testing update = self.db.query(Update).filter_by(title=build).one() update.request = None update.status = UpdateStatus.testing update.pushed = True self.db.flush() # Mark it as testing args['edited'] = args['builds'] # Toggle a bunch of the booleans args['autokarma'] = False args['require_testcases'] = False args['require_bugs'] = True r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['status'], u'testing') self.assertEquals(up['request'], None) self.assertEquals(up['require_bugs'], True) self.assertEquals(up['require_testcases'], False) self.assertEquals(up['stable_karma'], None) self.assertEquals(up['unstable_karma'], None) @mock.patch(**mock_valid_requirements) @mock.patch('bodhi.notifications.publish') def test_edit_update_change_type(self, publish, *args): build = 'bodhi-2.0.0-2.fc17' args = self.get_update('bodhi-2.0.0-2.fc17') args['type'] = 'newpackage' r = self.app.post_json('/updates/', args) publish.assert_called_with(topic='update.request.testing', msg=ANY) up = r.json_body self.assertEquals(up['type'], u'newpackage') # Pretend it was pushed to testing update = self.db.query(Update).filter_by(title=build).one() update.request = None update.status = UpdateStatus.testing update.pushed = True self.db.flush() # Mark it as testing args['edited'] = args['builds'] args['type'] = 'bugfix' r = self.app.post_json('/updates/', args) up = r.json_body self.assertEquals(up['status'], u'testing') self.assertEquals(up['request'], None) self.assertEquals(up['type'], u'bugfix')
Akasurde/bodhi
bodhi/tests/functional/test_updates.py
Python
gpl-2.0
86,419
[ "VisIt" ]
1f36b085e378822f14157171ba17a3d0860da02008a13803cd86e06f3c2d85a0
""" BIANA: Biologic Interactions and Network Analysis Copyright (C) 2009 Javier Garcia-Garcia, Emre Guney, Baldo Oliva 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/>. """ """ File : nr2piana.py Author : Ramon Aragues & Javier Garcia Modified : Javier Garcia October 2007 Creation : 10.2004 Contents : fills up tables in database piana with information from nr Called from : ======================================================================================================= This file implements a program that fills up tables in database piana with information from nr nr can be downloaded from ftp://ftp.ncbi.nih.gov/blast/db/FASTA/nr.gz Before running, taxonomy table of piana must be populated (use taxonomy2piana for that) """ ## STEP 1: IMPORT NECESSARY MODULES #from Bio import Fasta # needed to read the nr file (which is in fasta format) # Not used because error in Windows and many other systems because of Martel package from bianaParser import * class NrParser(BianaParser): """ NCBI nr Parser Class """ name = "nr" description = "This file implements a program that fills up tables in BIANA database with information from nr" external_entity_definition = "A external entity represents a protein" external_entity_relations = "" def __init__(self): # Start with the default values BianaParser.__init__(self, default_db_description = "Non-Redundant NCBI database", default_script_name = "nrParser.py", default_script_description = NrParser.description) self.default_eE_attribute = "proteinSequence" self.initialize_input_file_descriptor() def parse_database(self): """ Method that implements the specific operations of nr parser """ # Read specific parameters verbose_all = 0 self.initialize_input_file_descriptor() # Initialize protein number (to the output printing...) self.protein_number=0 # Counter of total of protein lines in file self.total_entries=0 # Counter of total of sequence-taxid entries in file self.total_inconsistencies=0 # counter of inconsistencies found (inconsistencies with identifiers cross-references) #nr_parser = Fasta.RecordParser() #nr_input_file = self.input_file_fd #nr_iterator = Fasta.Iterator(nr_input_file, nr_parser) #nr_record = nr_iterator.next() self.initialize_input_file_descriptor() if self.verbose: print "Processing file" # get dictionary for gis and tax ids if self.verbose: print "Reading gi/taxonomy information..." dict_name_tax = self.biana_access.get_taxonomy_names_taxID_dict() # Dictionary to save inconsistencies (when a proteinPiana does not exists but exists any external Identifier...) inconsistencies = {} # while record read is not None, parse the record and insert data into piana sequence = [] protein_title_line = None for line in self.input_file_fd: if line[0]==">": if len(sequence)>0: self.parse_nr_record(header_line = protein_title_line, sequence = "".join(sequence)) protein_title_line = line[1:] sequence = [] else: sequence.append(line.strip()) if len(sequence)>0: self.parse_nr_record(header_line = protein_title_line, sequence = "".join(sequence)) def parse_nr_record(self, header_line, sequence): self.protein_number += 1 self.add_to_log("Number of proteins in input file") if self.time_control: if self.protein_number%20000==0: sys.stderr.write("%s proteins\t%s seq-taxid entries\tin %s seconds\n" %(self.protein_number,self.total_entries,time.time()-self.initial_time)) protein_title_line = header_line protein_sequence = sequence #protein_title_line = nr_record.title #protein_sequence = nr_record.sequence.strip() """ Now, we have a proteinPiana that will be asigned to all other codes that we find in the title line """ # title can look like this: gi|1346670|sp|P04175|NCPR_PIG NADPH--cytochrome P450 reductase (CPR) (P450R) # gi|5832586|dbj|BAA84019.1| maturase [Eucharis grandiflora] # gi|223154|prf||0601198A polymerase beta,RNA # gi|17538019|ref|NP_496216.1| surfeit 5 (18.1 kD) (2K591) [Caenorhabditis elegans]$gi|2497033|sp|Q23679|YWM3_CAEEL Hypothetical protein ZK970.3 in chromosome II$gi|3881897|emb|CAA88887.1| Hypothetical protein ZK970.3 [Caenorhabditis elegans]$gi|7511441|pir||T28127 hypothetical protein ZK970.3 - Caenorhabditis elegans # # (character '>' from input file has been removed) # (where character $ is actually octal character 001) # # in nr (as opposed to genpept) a title can have several gi identifiers for the same sequence # however, nr is a mess, so it is easier to get species and so on from genpept (that is why we parse it first) # So, given the messy format of nr, first of all split by octal character 001 to see if there is more than one gi title_entries = protein_title_line.split("\001") # for each of the title entries (normally just one) split it, retrieve information and insert codes, using same sequence for all) for title_entrie in title_entries: nr_object = ExternalEntity( source_database = self.database, type="protein" ) nr_object.add_attribute(ExternalEntityAttribute( attribute_identifier = "proteinsequence", value = ProteinSequence(protein_sequence), type = "unique" )) self.total_entries += 1 gi = None if self.verbose: sys.stderr.write("One entry of the title is: %s\n" %(title_entrie)) title_atoms = title_entrie.split('|') # title_atom[1] (should) is always the gi code #if( title_atoms[0] == "gi" ): # gi_id = int(title_atoms[1]) # # title_atom[2] can be (exhaustive list as of 10.2004): # # - gb: for EMBL accessions # - emb: for EMBL protein id # - pir: for PIR accessions # - sp: for swissprot # - dbj: dna japan # - prf: ??? # - ref: ref_seq # - pdb: pdb code # - tpg: ??? # - tpe: ??? ### UPDATED: February 2007: # - gb: for GenBank acession Number # - emb: for EMBL accession Number # - dbj: for DDBJ, DNA Database of Japan # - pir: for NBRF PIR # - prf: for Protein Research Foundation # - sp: for Swiss-Prot Entries # - pdb: for Brookhaven Protein Data Bank # - pat: for Patents # - bbs: for GenInfo Backbone Id # - gnl: for General database Identifier # - ref: for NCBI Reference Sequence # - lcl: for Local Sequence Identifier # title_atom[3] is the value (a protein id) indicated in title_atom[2] # In theory, only one has to exist... (because of the EMBL/GenBank/DDBJ nucleotide sequence database... #gb_accession = None #embl_accession = None #dbj_accession = None accessionNumber = None uniprot_accession = None uniprot_entry = None ref_seq = None pdb_code = None pdb_chain = None pir = None description = None species_name = None # Read all the interesting cross-references: for i in xrange(len(title_atoms)): if title_atoms[i] == "gi": if gi is None: gi = int(title_atoms[i+1]) nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "gi", value = gi, type = "unique" )) else: sys.stderr.write(" Error parsing... how an entry can have several gi values? \n") elif title_atoms[i] == "gb" or title_atoms[i] == "emb" or title_atoms[i] == "dbj": if accessionNumber is None: accession = re.search("(\w+)\.(\d+)",title_atoms[i+1]) if accession: accessionNumber = accession.group(1) accessionNumber_version = accession.group(2) nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier="accessionNumber", value = accessionNumber, version = accessionNumber_version, type = "unique" )) else: sys.stderr.write(" Error parsing... how an entry can have several accesionNumber.version values? \n") elif title_atoms[i] == "pir": if pir is None: pirRe = re.search("(\w+)\.*",title_atoms[i+2]) if pirRe: pir = pirRe.group(1) nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "pir", value = pir, type = "cross-reference" )) else: sys.stderr.write(" Error parsing... How an entry can have several pir values? \n") elif title_atoms[i] == "sp": if uniprot_accession is None: uniprot_accession = title_atoms[i+1][0:6] else: sys.stderr.write(" There are more than one uniprot accession for the same gi... \n") if uniprot_entry is None: # "Chapuza" because there is one entry that has no uniprotEntry name...and the parser does not work correctly # This entry is: gi|20148613|gb|AAM10197.1| similar to high affinity sulfate transporter 2|sp|P53392 [Arabidopsis thaliana] if len(title_atoms) > (i+2): uniprot_entry = (title_atoms[i+2].split())[0].strip() nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "uniprotentry", value = uniprot_entry, type = "cross-reference")) else: sys.stderr.write(" There are more than one uniprot entry for the same gi... \n") elif title_atoms[i] == "ref": if ref_seq is None: ref_seq = title_atoms[i+1].strip().split(".") nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "refseq", value = ref_seq[0], version = ref_seq[1], type = "cross-reference")) else: sys.stderr.write(" There are more than one uniprot RefSeq for the same gi... \n") elif title_atoms[i] == "pdb": if pdb_code is None: pdb_code = title_atoms[i+1].strip() pdb_chain = title_atoms[i+2][0].strip() nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "pdb", value = pdb_code, additional_fields = { "chain": pdb_chain }, type = "cross-reference")) else: sys.stderr.write(" There are more than one PDB for the same gi... \n") # Take the description # has_description = re.search("\|([^\|]*)\[",title_entrie) # if has_description: # description = has_description.group(1) # if description != "": # description = description.replace('"'," ").replace("\n", " ").replace("'"," ").replace('\\', " ").strip(), # nr_object.add_attribute(ExternalEntityAttribute(attribute_identifier = "description", # value = description )) # TO CHECK: # Take the specie: #has_specie = re.search("\[(.*)\]$",title_entrie) #if has_specie: # species_name = has_specie.group(1).replace('"','').replace("(","").strip() # Now, get the tax_ID associated with the specie # Process species name... starts = [] ends = [] for x in xrange(len(title_entrie)): if title_entrie[x]=='[': starts.append(x) elif title_entrie[x]==']': ends.append(x) starts.reverse() ends.reverse() try: limit = starts[0] for x in xrange(1,len(ends)): if ends[x]>starts[x-1]: limit = starts[x] continue limit = starts[x-1] break species_name = title_entrie[limit+1:-1] try: tax_id_value = dict_name_tax[species_name.lower()] nr_object.add_attribute( ExternalEntityAttribute( attribute_identifier="taxid", value=tax_id_value, type = "unique") ) except: # If not found, try to split by "," or by "=" try: tax_id_value = dict_name_tax[species_name.split(",")[0].lower()] nr_object.add_attribute( ExternalEntityAttribute( attribute_identifier = "taxID", value = tax_id_value, type = "unique")) except: try: tax_id_value = dict_name_tax[species_name.split("=")[0].lower()] nr_object.add_attribute( ExternalEntityAttribute( attribute_identifier = "taxID", value = tax_id_value, type = "unique")) except: if self.verbose: sys.stderr.write("%s not found\n" %(species_name)) nr_object.add_attribute( ExternalEntityAttribute(attribute_identifier = "description", value = title_entrie[:limit].strip() ) ) except: nr_object.add_attribute( ExternalEntityAttribute(attribute_identifier = "description", value = title_entrie.strip())) self.biana_access.insert_new_external_entity( externalEntity = nr_object ) # reading next record if self.verbose: sys.stderr.write( "\n---------------reading next record---------------\n") #nr_record = nr_iterator.next() # END OF while nr_record is not None
emreg00/biana
biana/BianaParser/nrParser.py
Python
gpl-3.0
17,733
[ "BLAST" ]
a97356a0d2d462741be4e7528851b0ef69d88618c31f5f0f76418cd402607045
from .core import UnitedStates from ..registry_tools import iso_register # FIXME: According to wikipedia, Kansas only has all federal holidays, except # the Columbus Day and Washington's Birthday. # Unfortunately, other sources mention XMas Eve for 2018, but not for other # years. # I'm a bit sad here... # # Sources to lookup, if you want to help: # * http://www.admin.ks.gov/docs/default-source/ops/holidays/holidays2018.pdf # * http://www.kansas.gov/employee/documents/2017calendar.pdf # * https://publicholidays.us/kansas/2018-dates/ # * https://en.wikipedia.org/wiki/Public_holidays_in_the_United_States#Kansas # * https://publicholidays.us/kansas/2018-dates/ @iso_register('US-KS') class Kansas(UnitedStates): """Kansas""" include_federal_presidents_day = False include_columbus_day = False
novafloss/workalendar
workalendar/usa/kansas.py
Python
mit
813
[ "COLUMBUS" ]
5800194f7e78f62df7615e137352b69d0d1b4fae374569a47c128ec5fa539fb7
# Copyright 2019 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Double-sided Maxwell distribution class.""" import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python import random as tfp_random from tensorflow_probability.python.bijectors import identity as identity_bijector from tensorflow_probability.python.bijectors import softplus as softplus_bijector from tensorflow_probability.python.distributions import distribution from tensorflow_probability.python.internal import assert_util from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import parameter_properties from tensorflow_probability.python.internal import prefer_static as ps from tensorflow_probability.python.internal import reparameterization from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import tensor_util __all__ = [ 'DoublesidedMaxwell', ] class DoublesidedMaxwell(distribution.AutoCompositeTensorDistribution): r"""Double-sided Maxwell distribution. This distribution is useful to compute measure valued derivatives for Gaussian distributions. See [Mohamed et al. 2019][1] for more details. #### Mathematical details The double-sided Maxwell distribution generalizes the Maxwell distribution to the entire real line. ```none pdf(x; mu, sigma) = 1/(sigma*sqrt(2*pi)) * ((x-mu)/sigma)^2 * exp(-0.5 ((x-mu)/sigma)^2) ``` where `loc = mu` and `scale = sigma`. The DoublesidedMaxwell distribution is a member of the [location-scale family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as, ```none X ~ DoublesidedMaxwell(loc=0, scale=1) Y = loc + scale * X ``` The double-sided Maxwell is a symmetric distribution that extends the one-sided maxwell from R+ to the entire real line. Their densities are therefore the same up to a factor of 0.5. It has several methods for generating random variates from it. The version here uses 3 Gaussian variates and a uniform variate to generate the samples The sampling path is: mu + sigma* sgn(U-0.5)* sqrt(X^2 + Y^2 + Z^2) U~Unif; X,Y,Z ~N(0,1) In the sampling process above, the random variates generated by sqrt(X^2 + Y^2 + Z^2) are samples from the one-sided Maxwell (or Maxwell-Boltzmann) distribution. #### Examples ```python import tensorflow_probability as tfp tfd = tfp.distributions # Define a single scalar DoublesidedMaxwell distribution. dist = tfd.DoublesidedMaxwell(loc=0., scale=3.) # Evaluate the cdf at 1, returning a scalar. dist.cdf(1.) # Define a batch of two scalar valued DoublesidedMaxwells. # The first has mean 1 and standard deviation 11, the second 2 and 22. dist = tfd.DoublesidedMaxwell(loc=[1, 2.], scale=[11, 22.]) # Evaluate the pdf of the first distribution on 0, and the second on 1.5, # returning a length two tensor. dist.prob([0, 1.5]) # Get 3 samples, returning a 3 x 2 tensor. dist.sample([3]) ``` #### References [1]: Mohamed, et all, "Monte Carlo Gradient Estimation in Machine Learning.", 2019 https://arxiv.org/abs/1906.10652 [2] B. Heidergott, et all "Sensitivity estimation for Gaussian systems", 2008. European Journal of Operational Research, vol. 187, pp193-207. [3] G. Pflug. "Optimization of Stochastic Models: The Interface Between Simulation and Optimization", 2002. Chp. 4.2, pg 247. """ def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name='doublesided_maxwell'): """Construct a Double-sided Maxwell distribution with `scale`. Args: loc: Floating point tensor; location of the distribution scale: Floating point tensor; the scales of the distribution Must contain only positive values. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. Default value: `False` (i.e., do not validate args). allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. Default value: `True`. name: Python `str` name prefixed to Ops created by this class. Default value: 'doublesided_maxwell'. """ parameters = dict(locals()) with tf.name_scope(name) as name: dtype = dtype_util.common_dtype([loc, scale], dtype_hint=tf.float32) self._loc = tensor_util.convert_nonref_to_tensor( value=loc, name='loc', dtype=dtype) self._scale = tensor_util.convert_nonref_to_tensor( value=scale, name='scale', dtype=dtype) super(DoublesidedMaxwell, self).__init__( dtype=self._scale.dtype, reparameterization_type=reparameterization.FULLY_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, name=name) @classmethod def _parameter_properties(cls, dtype, num_classes=None): # pylint: disable=g-long-lambda return dict( loc=parameter_properties.ParameterProperties(), scale=parameter_properties.ParameterProperties( default_constraining_bijector_fn=( lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype))))) # pylint: enable=g-long-lambda @property def loc(self): """Distribution parameter for the mean.""" return self._loc @property def scale(self): """Distribution parameter for the scale.""" return self._scale def _event_shape_tensor(self): return tf.constant([], dtype=tf.int32) def _event_shape(self): return tf.TensorShape([]) def _log_prob(self, x): scale = tf.convert_to_tensor(self.scale) z = self._z(x, scale=scale) square_z = tf.square(z) log_unnormalized_prob = -0.5 * square_z + tf.math.log(square_z) log_normalization = 0.5 * np.log(2. * np.pi) + tf.math.log(scale) return log_unnormalized_prob - log_normalization def _z(self, x, scale=None): """Standardize input `x` to a standard maxwell.""" with tf.name_scope('standardize'): return (x - self.loc) / (self.scale if scale is None else scale) def _sample_n(self, n, seed=None): # Generate samples using: # mu + sigma* sgn(U-0.5)* sqrt(X^2 + Y^2 + Z^2) U~Unif; X,Y,Z ~N(0,1) normal_seed, rademacher_seed = samplers.split_seed( seed, salt='DoublesidedMaxwell') loc = tf.convert_to_tensor(self.loc) scale = tf.convert_to_tensor(self.scale) shape = ps.pad( self._batch_shape_tensor(loc=loc, scale=scale), paddings=[[1, 0]], constant_values=n) # Generate one-sided Maxwell variables by using 3 Gaussian variates norm_rvs = samplers.normal( shape=ps.pad(shape, paddings=[[0, 1]], constant_values=3), dtype=self.dtype, seed=normal_seed) maxwell_rvs = tf.norm(norm_rvs, axis=-1) # Generate random signs for the symmetric variates. random_sign = tfp_random.rademacher(shape, seed=rademacher_seed) sampled = random_sign * maxwell_rvs * scale + loc return sampled def _mean(self): return self.loc * tf.ones_like(self.scale) def _stddev(self): return np.sqrt(3.) * self.scale * tf.ones_like(self.loc) def _default_event_space_bijector(self): return identity_bijector.Identity(validate_args=self.validate_args) def _parameter_control_dependencies(self, is_init): assertions = [] if is_init: try: self._batch_shape() except ValueError: raise ValueError( 'Arguments `loc` and `scale` must have compatible shapes; ' 'loc.shape={}, scale.shape={}.'.format( self.loc.shape, self.scale.shape)) # We don't bother checking the shapes in the dynamic case because # all member functions access both arguments anyway. if not self.validate_args: assert not assertions # Should never happen. return [] if is_init != tensor_util.is_ref(self.scale): assertions.append(assert_util.assert_positive( self.scale, message='Argument `scale` must be positive.')) return assertions
tensorflow/probability
tensorflow_probability/python/distributions/doublesided_maxwell.py
Python
apache-2.0
9,164
[ "Gaussian" ]
f57661b7fc00a79f0605e5367f7cb90843f06614813c1d0a4a308c220ab5466b
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under the GNU Public Licence, v2 or any higher version # # Please cite your use of MDAnalysis in published work: # # R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler, # D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein. # MDAnalysis: A Python package for the rapid analysis of molecular dynamics # simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th # Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy. # # N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein. # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # from __future__ import print_function import numpy as np import MDAnalysis import MDAnalysis.analysis.pca as pca from numpy.testing import (assert_almost_equal, assert_equal, dec, assert_array_almost_equal, raises) from MDAnalysisTests.datafiles import (PSF, DCD, RANDOM_WALK, RANDOM_WALK_TOPO, waterPSF, waterDCD) from MDAnalysisTests import module_not_found class TestPCA(object): """ Test the PCA class """ def setUp(self): self.u = MDAnalysis.Universe(PSF, DCD) self.u.transfer_to_memory() self.pca = pca.PCA(self.u, select='backbone and name CA', align=False) self.pca.run() self.n_atoms = self.u.select_atoms('backbone and name CA').n_atoms def test_cov(self): atoms = self.u.select_atoms('backbone and name CA') xyz = np.zeros((self.pca.n_frames, self.pca._n_atoms*3)) for i, ts in enumerate(self.u.trajectory): xyz[i] = atoms.positions.ravel() cov = np.cov(xyz, rowvar=0) assert_array_almost_equal(self.pca.cov, cov, 4) def test_cum_var(self): assert_almost_equal(self.pca.cumulated_variance[-1], 1) l = self.pca.cumulated_variance l = np.sort(l) assert_almost_equal(self.pca.cumulated_variance, l, 5) def test_pcs(self): assert_equal(self.pca.p_components.shape, (self.n_atoms*3, self.n_atoms*3)) def test_different_steps(self): dot = self.pca.transform(self.u.select_atoms('backbone and name CA'), start=5, stop=7, step=1) assert_equal(dot.shape, (2, self.n_atoms*3)) def test_transform(self): ag = self.u.select_atoms('backbone and name CA') pca_space = self.pca.transform(ag, n_components=1) assert_equal(pca_space.shape, (self.u.trajectory.n_frames, 1)) # Accepts universe as input, but shapes are not aligned due to n_atoms @raises(ValueError) def test_transform_mismatch(self): pca_space = self.pca.transform(self.u, n_components=1) assert_equal(pca_space.shape, (self.u.trajectory.n_frames, 1)) @staticmethod def test_transform_universe(): u1 = MDAnalysis.Universe(waterPSF, waterDCD) u2 = MDAnalysis.Universe(waterPSF, waterDCD) pca_test = pca.PCA(u1).run() pca_test.transform(u2) @staticmethod @dec.skipif(module_not_found('scipy'), "Test skipped because scipy is not available.") def test_cosine_content(): rand = MDAnalysis.Universe(RANDOM_WALK_TOPO, RANDOM_WALK) pca_random = pca.PCA(rand).run() dot = pca_random.transform(rand.atoms) content = pca.cosine_content(dot, 0) assert_almost_equal(content, .99, 1)
alejob/mdanalysis
testsuite/MDAnalysisTests/analysis/test_pca.py
Python
gpl-2.0
3,905
[ "MDAnalysis" ]
5057c5fe93e4f2d460bf68196cb7eb1a1f3f43970534f7c41e162e6b92b10045
# (c) 2012-2018, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Ansible Galaxy 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 # Apache License for more details. # # You should have received a copy of the Apache License # along with Galaxy. If not, see <http://www.apache.org/licenses/>. from allauth.account.adapter import DefaultAccountAdapter from allauth.account.signals import password_changed, password_set from django.conf import settings from django.contrib import messages from django.dispatch import receiver @receiver(password_changed) def password_change_callback(sender, request, user, **kwargs): messages.success(request, 'You have successfully changed your password.') @receiver(password_set) def password_set_callback(sender, request, user, **kwargs): messages.success(request, 'You have successfully set your password.') class AccountAdapter(DefaultAccountAdapter): def default_login_redirect_url(self, request): if hasattr(settings, 'LOGIN_REDIRECT_URL'): return settings.LOGIN_REDIRECT_URL else: return '/' def get_login_redirect_url(self, request): if request.user.is_authenticated(): for account in request.user.socialaccount_set.all(): if account.provider == 'github': return self.default_login_redirect_url(request) return '/accounts/connect' else: return self.default_login_redirect_url(request)
chouseknecht/galaxy
galaxy/main/auth/__init__.py
Python
apache-2.0
1,864
[ "Galaxy" ]
02c38fbce26836951b807425d93ea3778a0b746194fb1804a737ed77f71271bc
from tigershark.facade import CompositeAccess from tigershark.facade import ElementAccess from tigershark.facade import ElementSequenceAccess from tigershark.facade import Facade from tigershark.facade import Money from tigershark.facade import SegmentAccess from tigershark.facade import SegmentConversion from tigershark.facade import SegmentSequenceAccess from tigershark.facade import X12LoopBridge from tigershark.facade import X12SegmentBridge from tigershark.facade import XDecimal from tigershark.facade import boolean from tigershark.facade import enum from tigershark.facade.enums.common import delivery_or_calendar_pattern_code from tigershark.facade.enums.common import delivery_time_pattern_code from tigershark.facade.enums.common import quantity_qualifier from tigershark.facade.enums.common import time_period_qualifier from tigershark.facade.enums.eligibility import coverage_level from tigershark.facade.enums.eligibility import eligibility_or_benefit_code from tigershark.facade.enums.eligibility import insurance_type from tigershark.facade.enums.eligibility import reject_reason_code from tigershark.facade.enums.eligibility import service_type_codes from tigershark.facade.f27x import Address from tigershark.facade.f27x import ContactInformation from tigershark.facade.f27x import DateOrTimePeriod from tigershark.facade.f27x import DemographicInformation from tigershark.facade.f27x import Diagnosis from tigershark.facade.f27x import Hierarchy from tigershark.facade.f27x import Header from tigershark.facade.f27x import Location from tigershark.facade.f27x import NamedEntity from tigershark.facade.f27x import ProviderInformation from tigershark.facade.f27x import ReferenceID from tigershark.facade.f27x import Relationship from tigershark.facade.f27x import TraceNumber from tigershark.facade.utils import first class RequestValidation(X12SegmentBridge): valid_request = ElementAccess("AAA", 1, x12type=boolean("Y")) reject_reason = ElementAccess("AAA", 3, x12type=enum(reject_reason_code)) follow_up_action_code = ElementAccess("AAA", 4, x12type=enum({ "C": "Please Correct and Resubmit", "N": "Resubmission Not Allowed", "P": "Please Resubmit Original Transaction", "R": "Resubmission Allowed", "S": "Do Not Resubmit; Inquiry Initiated to a Third Party", "W": "Please Wait 30 Days and Resubmit", "X": "Please Wait 10 Days and Resubmit", "Y": "Do Not Resubmit; We Will Hold Your Request and Respond Again " "Shortly"})) class Source(Facade, X12LoopBridge): """The information source is the entity with the eligibility answers""" loopName = "2000A" hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) class _Information(X12LoopBridge): loopName = "2100A" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) def __init__(self, anX12Message, *args, **kwargs): super(Source, self).__init__(anX12Message, *args, **kwargs) self.source_information = first(self.loops( self._Information, anX12Message)) self.receivers = self.loops(Receiver, anX12Message) class Receiver(Facade, X12LoopBridge): """The entity asking the questions""" loopName = "2000B" hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy)) class _Information(X12LoopBridge): loopName = "2100B" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) def __init__(self, anX12Message, *args, **kwargs): super(Receiver, self).__init__(anX12Message, *args, **kwargs) self.receiver_information = first(self.loops( self._Information, anX12Message)) self.subscribers = self.loops(Subscriber, anX12Message) class EligibilityOrBenefitInformation(X12SegmentBridge): """Eligibility Information.""" information_type = ElementAccess("EB", 1, x12type=enum( eligibility_or_benefit_code)) coverage_level = ElementAccess("EB", 2, x12type=enum( coverage_level)) service_type = ElementAccess("EB", 3, x12type=enum( service_type_codes)) insurance_type = ElementAccess("EB", 4, x12type=enum( insurance_type)) description = ElementAccess("EB", 5) time_period_type = ElementAccess("EB", 6, x12type=enum(time_period_qualifier)) benefit_amount = ElementAccess("EB", 7, x12type=Money) benefit_percent = ElementAccess("EB", 8, x12type=XDecimal) quantity_type = ElementAccess("EB", 9, x12type=enum(quantity_qualifier)) quantity = ElementAccess("EB", 10) authorization_or_certification = ElementAccess("EB", 11, x12type=boolean("Y")) in_plan_network = ElementAccess("EB", 12, x12type=boolean("Y")) both_in_out_network = ElementAccess("EB", 12, x12type=boolean("W")) ada_code = CompositeAccess("EB", "AD", 13) cpt_code = CompositeAccess("EB", "CJ", 13) hcpcs_code = CompositeAccess("EB", "HC", 13) icd_9_cm_code = CompositeAccess("EB", "ID", 13) ndc_code = CompositeAccess("EB", "ND", 13) zz_code = CompositeAccess("EB", "ZZ", 13) class HealthCareServicesDelivery(X12LoopBridge): benefit_quantity_type = ElementAccess("HSD", 1, x12type=enum(quantity_qualifier)) benefit_quantity = ElementAccess("HSD", 2) unit_or_basis_for_measurement = ElementAccess("HSD", 3, x12type=enum({ "DA": "Days", "MO": "Months", "VS": "Visit", "WK": "Week", "YR": "Years"})) sample_selection_modulus = ElementAccess("HSD", 4) time_period_type = ElementAccess("HSD", 5, x12type=enum(time_period_qualifier)) period_count = ElementAccess("HSD", 6) delivery_frequency = ElementAccess("HSD", 7, x12type=enum(delivery_or_calendar_pattern_code)) delivery_time = ElementAccess("HSD", 8, x12type=enum(delivery_time_pattern_code)) class Message(X12LoopBridge): message_text = ElementAccess("MSG", 1) class Subscriber(Facade, X12LoopBridge): """The person uniquely identified by the Source. This person was identified as a member of the Source. Subscriber may or may not be the patient. NOTE: Patient The Patient may be the Subscriber or the Dependent. There are several ways of identifying which type the Patient is, but the two most common are: 1. The Source assigns a unique ID number to each member of the Subscriber's family. In this case all dependents of a Subscriber are uniquely addressable by the Source, and are thus considered proper Subscribers, not Dependents. 2. The Source only gives a unique ID number to the Subscriber, and all family members are identifiable only by giving the Subscriber's and the Dependent's information. In this case both the Subscriber and Dependent will be defined. """ loopName = "2000C" hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy)) trace_numbers = SegmentSequenceAccess("TRN", x12type=SegmentConversion(TraceNumber)) class _Information(X12LoopBridge): loopName = "2100C" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) address_street = SegmentAccess("N3", x12type=SegmentConversion(Address)) address_location = SegmentAccess("N4", x12type=SegmentConversion(Location)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) demographic_information = SegmentAccess("DMG", x12type=SegmentConversion(DemographicInformation)) relationship = SegmentAccess("INS", x12type=SegmentConversion(Relationship)) dates = SegmentSequenceAccess("DTP", x12type=SegmentConversion(DateOrTimePeriod)) class _EligibilityOrBenefitInformation(Facade, X12LoopBridge): loopName = "2110C" coverage_information = SegmentAccess("EB", x12type=SegmentConversion(EligibilityOrBenefitInformation)) services_deliveries = SegmentSequenceAccess("HSD", x12type=SegmentConversion(HealthCareServicesDelivery)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) dates = SegmentSequenceAccess("DTP", x12type=SegmentConversion(DateOrTimePeriod)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) messages = ElementSequenceAccess("MSG", 1) class _AdditionalInformation(X12LoopBridge): loopName = "2115C" diagnosis = SegmentAccess("III", x12type=SegmentConversion(Diagnosis)) class _RelatedEntityInformation(X12LoopBridge): loopName = "2120C" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) address_street = SegmentAccess("N3", x12type=SegmentConversion(Address)) address_location = SegmentAccess("N4", x12type=SegmentConversion(Location)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) provider_information = SegmentAccess("PRV", x12type=SegmentConversion(ProviderInformation)) def __init__(self, anX12Message, *args, **kwargs): super(Subscriber._EligibilityOrBenefitInformation, self).__init__( anX12Message, *args, **kwargs) self.additional_information = self.loops( self._AdditionalInformation, anX12Message) self.benefit_related_entity = first(self.loops( self._RelatedEntityInformation, anX12Message)) def __init__(self, anX12Message, *args, **kwargs): super(Subscriber, self).__init__(anX12Message, *args, **kwargs) self.personal_information = first(self.loops( self._Information, anX12Message)) self.eligibility_or_benefit_information = \ self.loops(self._EligibilityOrBenefitInformation, anX12Message) self.dependents = self.loops(Dependent, anX12Message) class Dependent(Facade, X12LoopBridge): """The Dependent. This person was *NOT* identified as a member of the Source. If this is populated, then this is the patient. """ loopName = "2000D" hierarchy = SegmentAccess("HL", x12type=SegmentConversion(Hierarchy)) trace_numbers = SegmentSequenceAccess("TRN", x12type=SegmentConversion(TraceNumber)) class _Information(X12LoopBridge): loopName = "2100D" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) address_street = SegmentAccess("N3", x12type=SegmentConversion(Address)) address_location = SegmentAccess("N4", x12type=SegmentConversion(Location)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) demographic_information = SegmentAccess("DMG", x12type=SegmentConversion(DemographicInformation)) relationship = SegmentAccess("INS", x12type=SegmentConversion(Relationship)) dates = SegmentSequenceAccess("DTP", x12type=SegmentConversion(DateOrTimePeriod)) class _EligibilityOrBenefitInformation(Facade, X12LoopBridge): loopName = "2110D" coverage_information = SegmentAccess("EB", x12type=SegmentConversion(EligibilityOrBenefitInformation)) services_deliveries = SegmentSequenceAccess("HSD", x12type=SegmentConversion(HealthCareServicesDelivery)) reference_ids = SegmentSequenceAccess("REF", x12type=SegmentConversion(ReferenceID)) dates = SegmentSequenceAccess("DTP", x12type=SegmentConversion(DateOrTimePeriod)) request_validations = SegmentSequenceAccess("AAA", x12type=SegmentConversion(RequestValidation)) messages = ElementSequenceAccess("MSG", 1) class _AdditionalInformation(X12LoopBridge): loopName = "2115C" diagnosis = SegmentAccess("III", x12type=SegmentConversion(Diagnosis)) class _RelatedEntityInformation(X12LoopBridge): loopName = "2120D" name = SegmentAccess("NM1", x12type=SegmentConversion(NamedEntity)) address_street = SegmentAccess("N3", x12type=SegmentConversion(Address)) address_location = SegmentAccess("N4", x12type=SegmentConversion(Location)) contact_information = SegmentSequenceAccess("PER", x12type=SegmentConversion(ContactInformation)) provider_information = SegmentAccess("PRV", x12type=SegmentConversion(ProviderInformation)) def __init__(self, anX12Message, *args, **kwargs): super(Dependent._EligibilityOrBenefitInformation, self).__init__( anX12Message, *args, **kwargs) self.additional_information = self.loops( self._AdditionalInformation, anX12Message) self.benefit_related_entity = first(self.loops( self._RelatedEntityInformation, anX12Message)) def __init__(self, anX12Message, *args, **kwargs): super(Dependent, self).__init__(anX12Message, *args, **kwargs) self.personal_information = first(self.loops( self._Information, anX12Message)) self.eligibility_or_benefit_information = \ self.loops(self._EligibilityOrBenefitInformation, anX12Message) class F271_4010(Facade): def __init__(self, anX12Message): st_loops = anX12Message.descendant('LOOP', name='ST_LOOP') if len(st_loops) > 0: self.facades = [] for loop in st_loops: self.facades.append(F271_4010(loop)) else: self.header = first(self.loops(Header, anX12Message)) self.source = first(self.loops(Source, anX12Message))
sbuss/TigerShark
tigershark/facade/f271.py
Python
bsd-3-clause
15,668
[ "VisIt" ]
c8f7bf1c2a2fee28d216a5d2ef72d702fa14d6e02cfec89305cc28f212da8670
""" Tests for discussion pages """ import datetime from pytz import UTC from uuid import uuid4 from nose.plugins.attrib import attr from .helpers import BaseDiscussionTestCase from ..helpers import UniqueCourseTest from ...pages.lms.auto_auth import AutoAuthPage from ...pages.lms.courseware import CoursewarePage from ...pages.lms.discussion import ( DiscussionTabSingleThreadPage, InlineDiscussionPage, InlineDiscussionThreadPage, DiscussionUserProfilePage, DiscussionTabHomePage, DiscussionSortPreferencePage, ) from ...pages.lms.learner_profile import LearnerProfilePage from ...fixtures.course import CourseFixture, XBlockFixtureDesc from ...fixtures.discussion import ( SingleThreadViewFixture, UserProfileViewFixture, SearchResultFixture, Thread, Response, Comment, SearchResult, ) from .helpers import BaseDiscussionMixin THREAD_CONTENT_WITH_LATEX = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n----------\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. (b).\n\n **(a)** $H_1(e^{j\\omega}) = \\sum_{n=-\\infty}^{\\infty}h_1[n]e^{-j\\omega n} = \\sum_{n=-\\infty} ^{\\infty}h[n]e^{-j\\omega n}+\\delta_2e^{-j\\omega n_0}$ $= H(e^{j\\omega})+\\delta_2e^{-j\\omega n_0}=A_e (e^{j\\omega}) e^{-j\\omega n_0} +\\delta_2e^{-j\\omega n_0}=e^{-j\\omega n_0} (A_e(e^{j\\omega})+\\delta_2) $H_3(e^{j\\omega})=A_e(e^{j\\omega})+\\delta_2$. Dummy $A_e(e^{j\\omega})$ dummy post $. $A_e(e^{j\\omega}) \\ge -\\delta_2$, it follows that $H_3(e^{j\\omega})$ is real and $H_3(e^{j\\omega})\\ge 0$.\n\n**(b)** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur.\n\n **Case 1:** If $re^{j\\theta}$ is a Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n**Case 3:** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem $H_3(e^{j\\omega}) = P(cos\\omega)(cos\\omega - cos\\theta)^k$, Lorem Lorem Lorem Lorem Lorem Lorem $P(cos\\omega)$ has no $(cos\\omega - cos\\theta)$ factor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. $P(cos\\theta) \\neq 0$. Since $P(cos\\omega)$ this is a dummy data post $\\omega$, dummy $\\delta > 0$ such that for all $\\omega$ dummy $|\\omega - \\theta| < \\delta$, $P(cos\\omega)$ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. """ class DiscussionResponsePaginationTestMixin(BaseDiscussionMixin): """ A mixin containing tests for response pagination for use by both inline discussion and the discussion tab """ def assert_response_display_correct(self, response_total, displayed_responses): """ Assert that various aspects of the display of responses are all correct: * Text indicating total number of responses * Presence of "Add a response" button * Number of responses actually displayed * Presence and text of indicator of how many responses are shown * Presence and text of button to load more responses """ self.assertEqual( self.thread_page.get_response_total_text(), str(response_total) + " responses" ) self.assertEqual(self.thread_page.has_add_response_button(), response_total != 0) self.assertEqual(self.thread_page.get_num_displayed_responses(), displayed_responses) self.assertEqual( self.thread_page.get_shown_responses_text(), ( None if response_total == 0 else "Showing all responses" if response_total == displayed_responses else "Showing first {} responses".format(displayed_responses) ) ) self.assertEqual( self.thread_page.get_load_responses_button_text(), ( None if response_total == displayed_responses else "Load all responses" if response_total - displayed_responses < 100 else "Load next 100 responses" ) ) def test_pagination_no_responses(self): self.setup_thread(0) self.assert_response_display_correct(0, 0) def test_pagination_few_responses(self): self.setup_thread(5) self.assert_response_display_correct(5, 5) def test_pagination_two_response_pages(self): self.setup_thread(50) self.assert_response_display_correct(50, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(50, 50) def test_pagination_exactly_two_response_pages(self): self.setup_thread(125) self.assert_response_display_correct(125, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(125, 125) def test_pagination_three_response_pages(self): self.setup_thread(150) self.assert_response_display_correct(150, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 125) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 150) def test_add_response_button(self): self.setup_thread(5) self.assertTrue(self.thread_page.has_add_response_button()) self.thread_page.click_add_response_button() def test_add_response_button_closed_thread(self): self.setup_thread(5, closed=True) self.assertFalse(self.thread_page.has_add_response_button()) @attr('shard_1') class DiscussionHomePageTest(UniqueCourseTest): """ Tests for the discussion home page. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionHomePageTest, self).setUp() CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() def test_new_post_button(self): """ Scenario: I can create new posts from the Discussion home page. Given that I am on the Discussion home page When I click on the 'New Post' button Then I should be shown the new post form """ self.assertIsNotNone(self.page.new_post_button) self.page.click_new_post_button() self.assertIsNotNone(self.page.new_post_form) @attr('shard_1') class DiscussionTabSingleThreadTest(BaseDiscussionTestCase, DiscussionResponsePaginationTestMixin): """ Tests for the discussion page displaying a single thread """ def setUp(self): super(DiscussionTabSingleThreadTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() def setup_thread_page(self, thread_id): self.thread_page = self.create_single_thread_page(thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.visit() def test_mathjax_rendering(self): thread_id = "test_thread_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread( id=thread_id, body=THREAD_CONTENT_WITH_LATEX, commentable_id=self.discussion_id, thread_type="discussion" ) ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertTrue(self.thread_page.is_discussion_body_visible()) self.assertTrue(self.thread_page.is_mathjax_preview_available()) self.assertTrue(self.thread_page.is_mathjax_rendered()) def test_marked_answer_comments(self): thread_id = "test_thread_{}".format(uuid4().hex) response_id = "test_response_{}".format(uuid4().hex) comment_id = "test_comment_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread(id=thread_id, commentable_id=self.discussion_id, thread_type="question") ) thread_fixture.addResponse( Response(id=response_id, endorsed=True), [Comment(id=comment_id)] ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertFalse(self.thread_page.is_comment_visible(comment_id)) self.assertFalse(self.thread_page.is_add_comment_visible(response_id)) self.assertTrue(self.thread_page.is_show_comments_visible(response_id)) self.thread_page.show_comments(response_id) self.assertTrue(self.thread_page.is_comment_visible(comment_id)) self.assertTrue(self.thread_page.is_add_comment_visible(response_id)) self.assertFalse(self.thread_page.is_show_comments_visible(response_id)) @attr('shard_1') class DiscussionOpenClosedThreadTest(BaseDiscussionTestCase): """ Tests for checking the display of attributes on open and closed threads """ def setUp(self): super(DiscussionOpenClosedThreadTest, self).setUp() self.thread_id = "test_thread_{}".format(uuid4().hex) def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self, **thread_kwargs): thread_kwargs.update({'commentable_id': self.discussion_id}) view = SingleThreadViewFixture( Thread(id=self.thread_id, **thread_kwargs) ) view.addResponse(Response(id="response1")) view.push() def setup_openclosed_thread_page(self, closed=False): self.setup_user(roles=['Moderator']) if closed: self.setup_view(closed=True) else: self.setup_view() page = self.create_single_thread_page(self.thread_id) page.visit() page.close_open_thread() return page def test_originally_open_thread_vote_display(self): page = self.setup_openclosed_thread_page() self.assertFalse(page._is_element_visible('.forum-thread-main-wrapper .action-vote')) self.assertTrue(page._is_element_visible('.forum-thread-main-wrapper .display-vote')) self.assertFalse(page._is_element_visible('.response_response1 .action-vote')) self.assertTrue(page._is_element_visible('.response_response1 .display-vote')) def test_originally_closed_thread_vote_display(self): page = self.setup_openclosed_thread_page(True) self.assertTrue(page._is_element_visible('.forum-thread-main-wrapper .action-vote')) self.assertFalse(page._is_element_visible('.forum-thread-main-wrapper .display-vote')) self.assertTrue(page._is_element_visible('.response_response1 .action-vote')) self.assertFalse(page._is_element_visible('.response_response1 .display-vote')) @attr('shard_1') class DiscussionCommentDeletionTest(BaseDiscussionTestCase): """ Tests for deleting comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_deletion_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [Comment(id="comment_other_author", user_id="other"), Comment(id="comment_self_author", user_id=self.user_id)]) view.push() def test_comment_deletion_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") def test_comment_deletion_as_moderator(self): self.setup_user(roles=['Moderator']) self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") page.delete_comment("comment_other_author") @attr('shard_1') class DiscussionResponseEditTest(BaseDiscussionTestCase): """ Tests for editing responses displayed beneath thread in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="response_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response_other_author", user_id="other", thread_id="response_edit_test_thread"), ) view.addResponse( Response(id="response_self_author", user_id=self.user_id, thread_id="response_edit_test_thread"), ) view.push() def edit_response(self, page, response_id): self.assertTrue(page.is_response_editable(response_id)) page.start_response_edit(response_id) new_response = "edited body" page.set_response_editor_value(response_id, new_response) page.submit_response_edit(response_id, new_response) def test_edit_response_as_student(self): """ Scenario: Students should be able to edit the response they created not responses of other users Given that I am on discussion page with student logged in When I try to edit the response created by student Then the response should be edited and rendered successfully And responses from other users should be shown over there And the student should be able to edit the response of other people """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.assertTrue(page.is_response_visible("response_other_author")) self.assertFalse(page.is_response_editable("response_other_author")) self.edit_response(page, "response_self_author") def test_edit_response_as_moderator(self): """ Scenario: Moderator should be able to edit the response they created and responses of other users Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") def test_vote_report_endorse_after_edit(self): """ Scenario: Moderator should be able to vote, report or endorse after editing the response. Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully And I try to vote the response created by moderator Then the response should be voted successfully And I try to vote the response created by other users Then the response should be voted successfully And I try to report the response created by moderator Then the response should be reported successfully And I try to report the response created by other users Then the response should be reported successfully And I try to endorse the response created by moderator Then the response should be endorsed successfully And I try to endorse the response created by other users Then the response should be endorsed successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") page.vote_response('response_self_author') page.vote_response('response_other_author') page.report_response('response_self_author') page.report_response('response_other_author') page.endorse_response('response_self_author') page.endorse_response('response_other_author') @attr('shard_1') class DiscussionCommentEditTest(BaseDiscussionTestCase): """ Tests for editing comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [Comment(id="comment_other_author", user_id="other"), Comment(id="comment_self_author", user_id=self.user_id)]) view.push() def edit_comment(self, page, comment_id): page.start_comment_edit(comment_id) new_comment = "edited body" page.set_comment_editor_value(comment_id, new_comment) page.submit_comment_edit(comment_id, new_comment) def test_edit_comment_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") def test_edit_comment_as_moderator(self): self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") self.edit_comment(page, "comment_other_author") def test_cancel_comment_edit(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") page.set_comment_editor_value("comment_self_author", "edited body") page.cancel_comment_edit("comment_self_author", original_body) def test_editor_visibility(self): """Only one editor should be visible at a time within a single response""" self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.assertTrue(page.is_add_comment_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_add_comment_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.set_comment_editor_value("comment_self_author", "edited body") page.start_comment_edit("comment_other_author") self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_comment_editor_visible("comment_other_author")) self.assertEqual(page.get_comment_body("comment_self_author"), original_body) page.start_response_edit("response1") self.assertFalse(page.is_comment_editor_visible("comment_other_author")) self.assertTrue(page.is_response_editor_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_response_editor_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.cancel_comment_edit("comment_self_author", original_body) self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_add_comment_visible("response1")) @attr('shard_1') class InlineDiscussionTest(UniqueCourseTest, DiscussionResponsePaginationTestMixin): """ Tests for inline discussions """ def setUp(self): super(InlineDiscussionTest, self).setUp() self.discussion_id = "test_discussion_{}".format(uuid4().hex) self.additional_discussion_id = "test_discussion_{}".format(uuid4().hex) self.course_fix = CourseFixture(**self.course_info).add_children( XBlockFixtureDesc("chapter", "Test Section").add_children( XBlockFixtureDesc("sequential", "Test Subsection").add_children( XBlockFixtureDesc("vertical", "Test Unit").add_children( XBlockFixtureDesc( "discussion", "Test Discussion", metadata={"discussion_id": self.discussion_id} ), XBlockFixtureDesc( "discussion", "Test Discussion 1", metadata={"discussion_id": self.additional_discussion_id} ) ) ) ) ).install() self.user_id = AutoAuthPage(self.browser, course_id=self.course_id).visit().get_user_id() self.courseware_page = CoursewarePage(self.browser, self.course_id) self.courseware_page.visit() self.discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) self.additional_discussion_page = InlineDiscussionPage(self.browser, self.additional_discussion_id) def setup_thread_page(self, thread_id): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 1) self.thread_page = InlineDiscussionThreadPage(self.browser, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.expand() def test_initial_render(self): self.assertFalse(self.discussion_page.is_discussion_expanded()) def test_expand_discussion_empty(self): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 0) def check_anonymous_to_peers(self, is_staff): thread = Thread(id=uuid4().hex, anonymous_to_peers=True, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertEqual(self.thread_page.is_thread_anonymous(), not is_staff) def test_anonymous_to_peers_threads_as_staff(self): AutoAuthPage(self.browser, course_id=self.course_id, roles="Administrator").visit() self.courseware_page.visit() self.check_anonymous_to_peers(True) def test_anonymous_to_peers_threads_as_peer(self): self.check_anonymous_to_peers(False) def test_discussion_blackout_period(self): now = datetime.datetime.now(UTC) self.course_fix.add_advanced_settings( { u"discussion_blackouts": { "value": [ [ (now - datetime.timedelta(days=14)).isoformat(), (now + datetime.timedelta(days=2)).isoformat() ] ] } } ) self.course_fix._add_advanced_settings() self.browser.refresh() thread = Thread(id=uuid4().hex, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.addResponse( Response(id="response1"), [Comment(id="comment1", user_id="other"), Comment(id="comment2", user_id=self.user_id)]) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertFalse(self.discussion_page.element_exists(".new-post-btn")) self.assertFalse(self.thread_page.has_add_response_button()) self.assertFalse(self.thread_page.is_response_editable("response1")) self.assertFalse(self.thread_page.is_add_comment_visible("response1")) self.assertFalse(self.thread_page.is_comment_editable("comment1")) self.assertFalse(self.thread_page.is_comment_editable("comment2")) self.assertFalse(self.thread_page.is_comment_deletable("comment1")) self.assertFalse(self.thread_page.is_comment_deletable("comment2")) def test_dual_discussion_module(self): """ Scenario: Two discussion module in one unit shouldn't override their actions Given that I'm on courseware page where there are two inline discussion When I click on one discussion module new post button Then it should add new post form of that module in DOM And I should be shown new post form of that module And I shouldn't be shown second discussion module new post form And I click on second discussion module new post button Then it should add new post form of second module in DOM And I should be shown second discussion new post form And I shouldn't be shown first discussion module new post form And I have two new post form in the DOM When I click back on first module new post button And I should be shown new post form of that module And I shouldn't be shown second discussion module new post form """ self.discussion_page.wait_for_page() self.additional_discussion_page.wait_for_page() self.discussion_page.click_new_post_button() with self.discussion_page.handle_alert(): self.discussion_page.click_cancel_new_post() self.additional_discussion_page.click_new_post_button() self.assertFalse(self.discussion_page._is_element_visible(".new-post-article")) with self.additional_discussion_page.handle_alert(): self.additional_discussion_page.click_cancel_new_post() self.discussion_page.click_new_post_button() self.assertFalse(self.additional_discussion_page._is_element_visible(".new-post-article")) @attr('shard_1') class DiscussionUserProfileTest(UniqueCourseTest): """ Tests for user profile page in discussion tab. """ PAGE_SIZE = 20 # django_comment_client.forum.views.THREADS_PER_PAGE PROFILED_USERNAME = "profiled-user" def setUp(self): super(DiscussionUserProfileTest, self).setUp() CourseFixture(**self.course_info).install() # The following line creates a user enrolled in our course, whose # threads will be viewed, but not the one who will view the page. # It isn't necessary to log them in, but using the AutoAuthPage # saves a lot of code. self.profiled_user_id = AutoAuthPage( self.browser, username=self.PROFILED_USERNAME, course_id=self.course_id ).visit().get_user_id() # now create a second user who will view the profile. self.user_id = AutoAuthPage( self.browser, course_id=self.course_id ).visit().get_user_id() def check_pages(self, num_threads): # set up the stub server to return the desired amount of thread results threads = [Thread(id=uuid4().hex) for _ in range(num_threads)] UserProfileViewFixture(threads).push() # navigate to default view (page 1) page = DiscussionUserProfilePage( self.browser, self.course_id, self.profiled_user_id, self.PROFILED_USERNAME ) page.visit() current_page = 1 total_pages = max(num_threads - 1, 1) / self.PAGE_SIZE + 1 all_pages = range(1, total_pages + 1) return page def _check_page(): # ensure the page being displayed as "current" is the expected one self.assertEqual(page.get_current_page(), current_page) # ensure the expected threads are being shown in the right order threads_expected = threads[(current_page - 1) * self.PAGE_SIZE:current_page * self.PAGE_SIZE] self.assertEqual(page.get_shown_thread_ids(), [t["id"] for t in threads_expected]) # ensure the clickable page numbers are the expected ones self.assertEqual(page.get_clickable_pages(), [ p for p in all_pages if p != current_page and p - 2 <= current_page <= p + 2 or (current_page > 2 and p == 1) or (current_page < total_pages and p == total_pages) ]) # ensure the previous button is shown, but only if it should be. # when it is shown, make sure it works. if current_page > 1: self.assertTrue(page.is_prev_button_shown(current_page - 1)) page.click_prev_page() self.assertEqual(page.get_current_page(), current_page - 1) page.click_next_page() self.assertEqual(page.get_current_page(), current_page) else: self.assertFalse(page.is_prev_button_shown()) # ensure the next button is shown, but only if it should be. if current_page < total_pages: self.assertTrue(page.is_next_button_shown(current_page + 1)) else: self.assertFalse(page.is_next_button_shown()) # click all the way up through each page for i in range(current_page, total_pages): _check_page() if current_page < total_pages: page.click_on_page(current_page + 1) current_page += 1 # click all the way back down for i in range(current_page, 0, -1): _check_page() if current_page > 1: page.click_on_page(current_page - 1) current_page -= 1 def test_0_threads(self): self.check_pages(0) def test_1_thread(self): self.check_pages(1) def test_20_threads(self): self.check_pages(20) def test_21_threads(self): self.check_pages(21) def test_151_threads(self): self.check_pages(151) def test_pagination_window_reposition(self): page = self.check_pages(50) page.click_next_page() page.wait_for_ajax() self.assertTrue(page.is_window_on_top()) def test_redirects_to_learner_profile(self): """ Scenario: Verify that learner-profile link is present on forum discussions page and we can navigate to it. Given that I am on discussion forum user's profile page. And I can see a username on left sidebar When I click on my username. Then I will be navigated to Learner Profile page. And I can my username on Learner Profile page """ learner_profile_page = LearnerProfilePage(self.browser, self.PROFILED_USERNAME) page = self.check_pages(1) page.click_on_sidebar_username() learner_profile_page.wait_for_page() self.assertTrue(learner_profile_page.field_is_visible('username')) @attr('shard_1') class DiscussionSearchAlertTest(UniqueCourseTest): """ Tests for spawning and dismissing alerts related to user search actions and their results. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionSearchAlertTest, self).setUp() CourseFixture(**self.course_info).install() # first auto auth call sets up a user that we will search for in some tests self.searched_user_id = AutoAuthPage( self.browser, username=self.SEARCHED_USERNAME, course_id=self.course_id ).visit().get_user_id() # this auto auth call creates the actual session user AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() def setup_corrected_text(self, text): SearchResultFixture(SearchResult(corrected_text=text)).push() def check_search_alert_messages(self, expected): actual = self.page.get_search_alert_messages() self.assertTrue(all(map(lambda msg, sub: msg.lower().find(sub.lower()) >= 0, actual, expected))) def test_no_rewrite(self): self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) def test_rewrite_dismiss(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.page.dismiss_alert_message("foo") self.check_search_alert_messages([]) def test_new_search(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.setup_corrected_text("bar") self.page.perform_search() self.check_search_alert_messages(["bar"]) self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) def test_rewrite_and_user(self): self.setup_corrected_text("foo") self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["foo", self.SEARCHED_USERNAME]) def test_user_only(self): self.setup_corrected_text(None) self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["no threads", self.SEARCHED_USERNAME]) # make sure clicking the link leads to the user profile page UserProfileViewFixture([]).push() self.page.get_search_alert_links().first.click() DiscussionUserProfilePage( self.browser, self.course_id, self.searched_user_id, self.SEARCHED_USERNAME ).wait_for_page() @attr('shard_1') class DiscussionSortPreferenceTest(UniqueCourseTest): """ Tests for the discussion page displaying a single thread. """ def setUp(self): super(DiscussionSortPreferenceTest, self).setUp() # Create a course to register for. CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.sort_page = DiscussionSortPreferencePage(self.browser, self.course_id) self.sort_page.visit() def test_default_sort_preference(self): """ Test to check the default sorting preference of user. (Default = date ) """ selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, "date") def test_change_sort_preference(self): """ Test that if user sorting preference is changing properly. """ selected_sort = "" for sort_type in ["votes", "comments", "date"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) def test_last_preference_saved(self): """ Test that user last preference is saved. """ selected_sort = "" for sort_type in ["votes", "comments", "date"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) self.sort_page.refresh_page() selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type)
DefyVentures/edx-platform
common/test/acceptance/tests/discussion/test_discussion.py
Python
agpl-3.0
42,568
[ "VisIt" ]
1208246d8dc7bbd6358876615e3266c0a0e0a0fdc8d5a3f29f2d5b46831d865c
# -*- coding: utf-8 -*- # # This file is part of cclib (http://cclib.github.io), a library for parsing # and interpreting the results of computational chemistry packages. # # Copyright (C) 2007-2014, the cclib development team # # The library is free software, distributed under the terms of # the GNU Lesser General Public version 2.1 or later. You should have # received a copy of the license along with cclib. You can also access # the full license online at http://www.gnu.org/copyleft/lgpl.html. """Parser for Molpro output files""" import itertools import numpy from . import logfileparser from . import utils def create_atomic_orbital_names(orbitals): """Generate all atomic orbital names that could be used by Molpro. The names are returned in a dictionary, organized by subshell (S, P, D and so on). """ # We can write out the first two manually, since there are not that many. atomic_orbital_names = { 'S': ['s', '1s'], 'P': ['x', 'y', 'z', '2px', '2py', '2pz'], } # Although we could write out all names for the other subshells, it is better # to generate them if we need to expand further, since the number of functions quickly # grows and there are both Cartesian and spherical variants to consider. # For D orbitals, the Cartesian functions are xx, yy, zz, xy, xz and yz, and the # spherical ones are called 3d0, 3d1-, 3d1+, 3d2- and 3d2+. For F orbitals, the Cartesians # are xxx, xxy, xxz, xyy, ... and the sphericals are 4f0, 4f1-, 4f+ and so on. for i, orb in enumerate(orbitals): # Cartesian can be generated directly by combinations. cartesian = list(map(''.join, list(itertools.combinations_with_replacement(['x', 'y', 'z'], i+2)))) # For spherical functions, we need to construct the names. pre = str(i+3) + orb.lower() spherical = [pre + '0'] + [pre + str(j) + s for j in range(1, i+3) for s in ['-', '+']] atomic_orbital_names[orb] = cartesian + spherical return atomic_orbital_names class Molpro(logfileparser.Logfile): """Molpro file parser""" atomic_orbital_names = create_atomic_orbital_names(['D', 'F', 'G']) def __init__(self, *args, **kwargs): # Call the __init__ method of the superclass super(Molpro, self).__init__(logname="Molpro", *args, **kwargs) def __str__(self): """Return a string representation of the object.""" return "Molpro log file %s" % (self.filename) def __repr__(self): """Return a representation of the object.""" return 'Molpro("%s")' % (self.filename) def normalisesym(self, label): """Normalise the symmetries used by Molpro.""" ans = label.replace("`", "'").replace("``", "''") return ans def before_parsing(self): self.electronorbitals = "" self.insidescf = False def after_parsing(self): # If optimization thresholds are default, they are normally not printed and we need # to set them to the default after parsing. Make sure to set them in the same order that # they appear in the in the geometry optimization progress printed in the output, # namely: energy difference, maximum gradient, maximum step. if not hasattr(self, "geotargets"): self.geotargets = [] # Default THRENERG (required accuracy of the optimized energy). self.geotargets.append(1E-6) # Default THRGRAD (required accuracy of the optimized gradient). self.geotargets.append(3E-4) # Default THRSTEP (convergence threshold for the geometry optimization step). self.geotargets.append(3E-4) def extract(self, inputfile, line): """Extract information from the file object inputfile.""" if line[1:19] == "ATOMIC COORDINATES": if not hasattr(self,"atomcoords"): self.atomcoords = [] atomcoords = [] atomnos = [] self.skip_lines(inputfile, ['line', 'line', 'line']) line = next(inputfile) while line.strip(): temp = line.strip().split() atomcoords.append([utils.convertor(float(x), "bohr", "Angstrom") for x in temp[3:6]]) #bohrs to angs atomnos.append(int(round(float(temp[2])))) line = next(inputfile) self.atomcoords.append(atomcoords) self.set_attribute('atomnos', atomnos) self.set_attribute('natom', len(self.atomnos)) # Use BASIS DATA to parse input for gbasis, aonames and atombasis. If symmetry is used, # the function number starts from 1 for each irrep (the irrep index comes after the dot). # # BASIS DATA # # Nr Sym Nuc Type Exponents Contraction coefficients # # 1.1 A 1 1s 71.616837 0.154329 # 13.045096 0.535328 # 3.530512 0.444635 # 2.1 A 1 1s 2.941249 -0.099967 # 0.683483 0.399513 # ... # if line[1:11] == "BASIS DATA": # We can do a sanity check with the header. self.skip_line(inputfile, 'blank') header = next(inputfile) assert header.split() == ["Nr", "Sym", "Nuc", "Type", "Exponents", "Contraction", "coefficients"] self.skip_line(inputfile, 'blank') aonames = [] atombasis = [[] for i in range(self.natom)] gbasis = [[] for i in range(self.natom)] while line.strip(): # We need to read the line at the start of the loop here, because the last function # will be added when a blank line signalling the end of the block is encountered. line = next(inputfile) # The formatting here can exhibit subtle differences, including the number of spaces # or indentation size. However, we will rely on explicit slices since not all components # are always available. In fact, components not being there has some meaning (see below). line_nr = line[1:6].strip() line_sym = line[7:9].strip() line_nuc = line[11:14].strip() line_type = line[16:22].strip() line_exp = line[25:38].strip() line_coeffs = line[38:].strip() # If a new function type is printed or the BASIS DATA block ends with a blank line, # then add the previous function to gbasis, except for the first function since # there was no preceeding one. When translating the Molpro function name to gbasis, # note that Molpro prints all components, but we want it only once, with the proper # shell type (S,P,D,F,G). Molpro names also differ between Cartesian/spherical representations. if (line_type and aonames) or line.strip() == "": # All the possible AO names are created with the class. The function should always # find a match in that dictionary, so we can check for that here and will need to # update the dict if something unexpected comes up. funcbasis = None for fb, names in self.atomic_orbital_names.items(): if functype in names: funcbasis = fb assert funcbasis # There is a separate basis function for each column of contraction coefficients. Since all # atomic orbitals for a subshell will have the same parameters, we can simply check if # the function tuple is already in gbasis[i] before adding it. for i in range(len(coefficients[0])): func = (funcbasis, []) for j in range(len(exponents)): func[1].append((exponents[j], coefficients[j][i])) if func not in gbasis[funcatom-1]: gbasis[funcatom-1].append(func) # If it is a new type, set up the variables for the next shell(s). An exception is symmetry functions, # which we want to copy from the previous function and don't have a new number on the line. For them, # we just want to update the nuclear index. if line_type: if line_nr: exponents = [] coefficients = [] functype = line_type funcatom = int(line_nuc) # Add any exponents and coefficients to lists. if line_exp and line_coeffs: funcexp = float(line_exp) funccoeffs = [float(s) for s in line_coeffs.split()] exponents.append(funcexp) coefficients.append(funccoeffs) # If the function number is present then add to atombasis and aonames, which is different from # adding to gbasis since it enumerates AOs rather than basis functions. The number counts functions # in each irrep from 1 and we could add up the functions for each irrep to get the global count, # but it is simpler to just see how many aonames we have already parsed. Any symmetry functions # are also printed, but they don't get numbers so they are nor parsed. if line_nr: element = self.table.element[self.atomnos[funcatom-1]] aoname = "%s%i_%s" % (element, funcatom, functype) aonames.append(aoname) funcnr = len(aonames) atombasis[funcatom-1].append(funcnr-1) self.set_attribute('aonames', aonames) self.set_attribute('atombasis', atombasis) self.set_attribute('gbasis', gbasis) if line[1:23] == "NUMBER OF CONTRACTIONS": nbasis = int(line.split()[3]) self.set_attribute('nbasis', nbasis) # This is used to signalize whether we are inside an SCF calculation. if line[1:8] == "PROGRAM" and line[14:18] == "-SCF": self.insidescf = True # Use this information instead of 'SETTING ...', in case the defaults are standard. # Note that this is sometimes printed in each geometry optimization step. if line[1:20] == "NUMBER OF ELECTRONS": spinup = int(line.split()[3][:-1]) spindown = int(line.split()[4][:-1]) # Nuclear charges (atomnos) should be parsed by now. nuclear = numpy.sum(self.atomnos) charge = nuclear - spinup - spindown self.set_attribute('charge', charge) mult = spinup - spindown + 1 self.set_attribute('mult', mult) # Convergenve thresholds for SCF cycle, should be contained in a line such as: # CONVERGENCE THRESHOLDS: 1.00E-05 (Density) 1.40E-07 (Energy) if self.insidescf and line[1:24] == "CONVERGENCE THRESHOLDS:": if not hasattr(self, "scftargets"): self.scftargets = [] scftargets = list(map(float, line.split()[2::2])) self.scftargets.append(scftargets) # Usually two criteria, but save the names this just in case. self.scftargetnames = line.split()[3::2] # Read in the print out of the SCF cycle - for scfvalues. For RHF looks like: # ITERATION DDIFF GRAD ENERGY 2-EL.EN. DIPOLE MOMENTS DIIS # 1 0.000D+00 0.000D+00 -379.71523700 1159.621171 0.000000 0.000000 0.000000 0 # 2 0.000D+00 0.898D-02 -379.74469736 1162.389787 0.000000 0.000000 0.000000 1 # 3 0.817D-02 0.144D-02 -379.74635529 1162.041033 0.000000 0.000000 0.000000 2 # 4 0.213D-02 0.571D-03 -379.74658063 1162.159929 0.000000 0.000000 0.000000 3 # 5 0.799D-03 0.166D-03 -379.74660889 1162.144256 0.000000 0.000000 0.000000 4 if self.insidescf and line[1:10] == "ITERATION": if not hasattr(self, "scfvalues"): self.scfvalues = [] line = next(inputfile) energy = 0.0 scfvalues = [] while line.strip() != "": if line.split()[0].isdigit(): ddiff = float(line.split()[1].replace('D','E')) newenergy = float(line.split()[3]) ediff = newenergy - energy energy = newenergy # The convergence thresholds must have been read above. # Presently, we recognize MAX DENSITY and MAX ENERGY thresholds. numtargets = len(self.scftargetnames) values = [numpy.nan]*numtargets for n, name in zip(list(range(numtargets)),self.scftargetnames): if "ENERGY" in name.upper(): values[n] = ediff elif "DENSITY" in name.upper(): values[n] = ddiff scfvalues.append(values) line = next(inputfile) self.scfvalues.append(numpy.array(scfvalues)) # SCF result - RHF/UHF and DFT (RKS) energies. if (line[1:5] in ["!RHF", "!UHF", "!RKS"] and line[16:22].lower() == "energy"): if not hasattr(self, "scfenergies"): self.scfenergies = [] scfenergy = float(line.split()[4]) self.scfenergies.append(utils.convertor(scfenergy, "hartree", "eV")) # We are now done with SCF cycle (after a few lines). self.insidescf = False # MP2 energies. if line[1:5] == "!MP2": if not hasattr(self, 'mpenergies'): self.mpenergies = [] mp2energy = float(line.split()[-1]) mp2energy = utils.convertor(mp2energy, "hartree", "eV") self.mpenergies.append([mp2energy]) # MP2 energies if MP3 or MP4 is also calculated. if line[1:5] == "MP2:": if not hasattr(self, 'mpenergies'): self.mpenergies = [] mp2energy = float(line.split()[2]) mp2energy = utils.convertor(mp2energy, "hartree", "eV") self.mpenergies.append([mp2energy]) # MP3 (D) and MP4 (DQ or SDQ) energies. if line[1:8] == "MP3(D):": mp3energy = float(line.split()[2]) mp2energy = utils.convertor(mp3energy, "hartree", "eV") line = next(inputfile) self.mpenergies[-1].append(mp2energy) if line[1:9] == "MP4(DQ):": mp4energy = float(line.split()[2]) line = next(inputfile) if line[1:10] == "MP4(SDQ):": mp4energy = float(line.split()[2]) mp4energy = utils.convertor(mp4energy, "hartree", "eV") self.mpenergies[-1].append(mp4energy) # The CCSD program operates all closed-shel coupled cluster runs. if line[1:15] == "PROGRAM * CCSD": if not hasattr(self, "ccenergies"): self.ccenergies = [] while line[1:20] != "Program statistics:": # The last energy (most exact) will be read last and thus saved. if line[1:5] == "!CCD" or line[1:6] == "!CCSD" or line[1:9] == "!CCSD(T)": ccenergy = float(line.split()[-1]) ccenergy = utils.convertor(ccenergy, "hartree", "eV") line = next(inputfile) self.ccenergies.append(ccenergy) # Read the occupancy (index of HOMO s). # For restricted calculations, there is one line here. For unrestricted, two: # Final alpha occupancy: ... # Final beta occupancy: ... if line[1:17] == "Final occupancy:": self.homos = [int(line.split()[-1])-1] if line[1:23] == "Final alpha occupancy:": self.homos = [int(line.split()[-1])-1] line = next(inputfile) self.homos.append(int(line.split()[-1])-1) # Dipole is always printed on one line after the final RHF energy, and by default # it seems Molpro uses the origin as the reference point. if line.strip()[:13] == "Dipole moment": assert line.split()[2] == "/Debye" reference = [0.0, 0.0, 0.0] dipole = [float(d) for d in line.split()[-3:]] if not hasattr(self, 'moments'): self.moments = [reference, dipole] else: self.moments[1] == dipole # From this block aonames, atombasis, moenergies and mocoeffs can be parsed. The data is # flipped compared to most programs (GAMESS, Gaussian), since the MOs are in rows. Also, Molpro # does not cut the table into parts, rather each MO row has as many lines as it takes ro print # all of the MO coefficients. Each row normally has 10 coefficients, although this can be less # for the last row and when symmetry is used (each irrep has its own block). # # ELECTRON ORBITALS # ================= # # # Orb Occ Energy Couls-En Coefficients # # 1 1s 1 1s 1 2px 1 2py 1 2pz 2 1s (...) # 3 1s 3 1s 3 2px 3 2py 3 2pz 4 1s (...) # (...) # # 1.1 2 -11.0351 -43.4915 0.701460 0.025696 -0.000365 -0.000006 0.000000 0.006922 (...) # -0.006450 0.004742 -0.001028 -0.002955 0.000000 -0.701460 (...) # (...) # if line[1:18] == "ELECTRON ORBITALS" or self.electronorbitals: # For unrestricted calcualtions, ELECTRON ORBITALS is followed on the same line # by FOR POSITIVE SPIN or FOR NEGATIVE SPIN as appropriate. spin = (line[19:36] == "FOR NEGATIVE SPIN") or (self.electronorbitals[19:36] == "FOR NEGATIVE SPIN") if not self.electronorbitals: self.skip_line(inputfile, 'equals') self.skip_lines(inputfile, ['b', 'b', 'headers', 'b']) aonames = [] atombasis = [[] for i in range(self.natom)] moenergies = [] mocoeffs = [] line = next(inputfile) # Besides a double blank line, stop when the next orbitals are encountered for unrestricted jobs # or if there are stars on the line which always signifies the end of the block. while line.strip() and (not "ORBITALS" in line) and (not set(line.strip()) == {'*'}): # The function names are normally printed just once, but if symmetry is used then each irrep # has its own mocoeff block with a preceding list of names. is_aonames = line[:25].strip() == "" if is_aonames: # We need to save this offset for parsing the coefficients later. offset = len(aonames) aonum = len(aonames) while line.strip(): for s in line.split(): if s.isdigit(): atomno = int(s) atombasis[atomno-1].append(aonum) aonum += 1 else: functype = s element = self.table.element[self.atomnos[atomno-1]] aoname = "%s%i_%s" % (element, atomno, functype) aonames.append(aoname) line = next(inputfile) # Now there can be one or two blank lines. while not line.strip(): line = next(inputfile) # Newer versions of Molpro (for example, 2012 test files) will print some # more things here, such as HOMO and LUMO, but these have less than 10 columns. if "HOMO" in line or "LUMO" in line: break # Now parse the MO coefficients, padding the list with an appropriate amount of zeros. coeffs = [0.0 for i in range(offset)] while line.strip() != "": if line[:31].rstrip(): moenergy = float(line.split()[2]) moenergy = utils.convertor(moenergy, "hartree", "eV") moenergies.append(moenergy) # Coefficients are in 10.6f format and splitting does not work since there are not # always spaces between them. If the numbers are very large, there will be stars. str_coeffs = line[31:] ncoeffs = len(str_coeffs) // 10 coeff = [] for ic in range(ncoeffs): p = str_coeffs[ic*10:(ic+1)*10] try: c = float(p) except ValueError as detail: self.logger.warn("setting mocoeff element to zero: %s" % detail) c = 0.0 coeff.append(c) coeffs.extend(coeff) line = next(inputfile) mocoeffs.append(coeffs) # The loop should keep going until there is a double blank line, and there is # a single line between each coefficient block. line = next(inputfile) if not line.strip(): line = next(inputfile) # If symmetry was used (offset was needed) then we will need to pad all MO vectors # up to nbasis for all irreps before the last one. if offset > 0: for im,m in enumerate(mocoeffs): if len(m) < self.nbasis: mocoeffs[im] = m + [0.0 for i in range(self.nbasis - len(m))] self.set_attribute('atombasis', atombasis) self.set_attribute('aonames', aonames) # Consistent with current cclib conventions, reset moenergies/mocoeffs if they have been # previously parsed, since we want to produce only the final values. if not hasattr(self, "moenergies") or spin == 0: self.mocoeffs = [] self.moenergies = [] self.moenergies.append(moenergies) self.mocoeffs.append(mocoeffs) # Check if last line begins the next ELECTRON ORBITALS section, because we already used # this line and need to know when this method is called next time. if line[1:18] == "ELECTRON ORBITALS": self.electronorbitals = line else: self.electronorbitals = "" # If the MATROP program was called appropriately, # the atomic obital overlap matrix S is printed. # The matrix is printed straight-out, ten elements in each row, both halves. # Note that is the entire matrix is not printed, then aooverlaps # will not have dimensions nbasis x nbasis. if line[1:9] == "MATRIX S": if not hasattr(self, "aooverlaps"): self.aooverlaps = [[]] self.skip_lines(inputfile, ['b', 'symblocklabel']) line = next(inputfile) while line.strip() != "": elements = [float(s) for s in line.split()] if len(self.aooverlaps[-1]) + len(elements) <= self.nbasis: self.aooverlaps[-1] += elements else: n = len(self.aooverlaps[-1]) + len(elements) - self.nbasis self.aooverlaps[-1] += elements[:-n] self.aooverlaps.append([]) self.aooverlaps[-1] += elements[-n:] line = next(inputfile) # Thresholds are printed only if the defaults are changed with GTHRESH. # In that case, we can fill geotargets with non-default values. # The block should look like this as of Molpro 2006.1: # THRESHOLDS: # ZERO = 1.00D-12 ONEINT = 1.00D-12 TWOINT = 1.00D-11 PREFAC = 1.00D-14 LOCALI = 1.00D-09 EORDER = 1.00D-04 # ENERGY = 0.00D+00 ETEST = 0.00D+00 EDENS = 0.00D+00 THRDEDEF= 1.00D-06 GRADIENT= 1.00D-02 STEP = 1.00D-03 # ORBITAL = 1.00D-05 CIVEC = 1.00D-05 COEFF = 1.00D-04 PRINTCI = 5.00D-02 PUNCHCI = 9.90D+01 OPTGRAD = 3.00D-04 # OPTENERG= 1.00D-06 OPTSTEP = 3.00D-04 THRGRAD = 2.00D-04 COMPRESS= 1.00D-11 VARMIN = 1.00D-07 VARMAX = 1.00D-03 # THRDOUB = 0.00D+00 THRDIV = 1.00D-05 THRRED = 1.00D-07 THRPSP = 1.00D+00 THRDC = 1.00D-10 THRCS = 1.00D-10 # THRNRM = 1.00D-08 THREQ = 0.00D+00 THRDE = 1.00D+00 THRREF = 1.00D-05 SPARFAC = 1.00D+00 THRDLP = 1.00D-07 # THRDIA = 1.00D-10 THRDLS = 1.00D-07 THRGPS = 0.00D+00 THRKEX = 0.00D+00 THRDIS = 2.00D-01 THRVAR = 1.00D-10 # THRLOC = 1.00D-06 THRGAP = 1.00D-06 THRLOCT = -1.00D+00 THRGAPT = -1.00D+00 THRORB = 1.00D-06 THRMLTP = 0.00D+00 # THRCPQCI= 1.00D-10 KEXTA = 0.00D+00 THRCOARS= 0.00D+00 SYMTOL = 1.00D-06 GRADTOL = 1.00D-06 THROVL = 1.00D-08 # THRORTH = 1.00D-08 GRID = 1.00D-06 GRIDMAX = 1.00D-03 DTMAX = 0.00D+00 if line [1:12] == "THRESHOLDS": self.skip_line(input, 'blank') line = next(inputfile) while line.strip(): if "OPTENERG" in line: start = line.find("OPTENERG") optenerg = line[start+10:start+20] if "OPTGRAD" in line: start = line.find("OPTGRAD") optgrad = line[start+10:start+20] if "OPTSTEP" in line: start = line.find("OPTSTEP") optstep = line[start+10:start+20] line = next(inputfile) self.geotargets = [optenerg, optgrad, optstep] # The optimization history is the source for geovlues: # # END OF GEOMETRY OPTIMIZATION. TOTAL CPU: 246.9 SEC # # ITER. ENERGY(OLD) ENERGY(NEW) DE GRADMAX GRADNORM GRADRMS STEPMAX STEPLEN STEPRMS # 1 -382.02936898 -382.04914450 -0.01977552 0.11354875 0.20127947 0.01183997 0.12972761 0.20171740 0.01186573 # 2 -382.04914450 -382.05059234 -0.00144784 0.03299860 0.03963339 0.00233138 0.05577169 0.06687650 0.00393391 # 3 -382.05059234 -382.05069136 -0.00009902 0.00694359 0.01069889 0.00062935 0.01654549 0.02016307 0.00118606 # ... # # The above is an exerpt from Molpro 2006, but it is a little bit different # for Molpro 2012, namely the 'END OF GEOMETRY OPTIMIZATION occurs after the # actual history list. It seems there is a another consistent line before the # history, but this might not be always true -- so this is a potential weak link. if line[1:30] == "END OF GEOMETRY OPTIMIZATION." or line.strip() == "Quadratic Steepest Descent - Minimum Search": # I think this is the trigger for convergence, and it shows up at the top in Molpro 2006. geometry_converged = line[1:30] == "END OF GEOMETRY OPTIMIZATION." self.skip_line(inputfile, 'blank') # Newer version of Molpro (at least for 2012) print and additional column # with the timing information for each step. Otherwise, the history looks the same. headers = next(inputfile).split() if not len(headers) in (10,11): return # Although criteria can be changed, the printed format should not change. # In case it does, retrieve the columns for each parameter. index_ITER = headers.index('ITER.') index_THRENERG = headers.index('DE') index_THRGRAD = headers.index('GRADMAX') index_THRSTEP = headers.index('STEPMAX') line = next(inputfile) self.geovalues = [] while line.strip(): line = line.split() istep = int(line[index_ITER]) geovalues = [] geovalues.append(float(line[index_THRENERG])) geovalues.append(float(line[index_THRGRAD])) geovalues.append(float(line[index_THRSTEP])) self.geovalues.append(geovalues) line = next(inputfile) if line.strip() == "Freezing grid": line = next(inputfile) # The convergence trigger shows up somewhere at the bottom in Molpro 2012, # before the final stars. If convergence is not reached, there is an additional # line that can be checked for. This is a little tricky, though, since it is # not the last line... so bail out of the loop if convergence failure is detected. while "*****" not in line: line = next(inputfile) if line.strip() == "END OF GEOMETRY OPTIMIZATION.": geometry_converged = True if "No convergence" in line: geometry_converged = False break # Finally, deal with optdone, append the last step to it only if we had convergence. if not hasattr(self, 'optdone'): self.optdone = [] if geometry_converged: self.optdone.append(istep-1) # This block should look like this: # Normal Modes # # 1 Au 2 Bu 3 Ag 4 Bg 5 Ag # Wavenumbers [cm-1] 151.81 190.88 271.17 299.59 407.86 # Intensities [km/mol] 0.33 0.28 0.00 0.00 0.00 # Intensities [relative] 0.34 0.28 0.00 0.00 0.00 # CX1 0.00000 -0.01009 0.02577 0.00000 0.06008 # CY1 0.00000 -0.05723 -0.06696 0.00000 0.06349 # CZ1 -0.02021 0.00000 0.00000 0.11848 0.00000 # CX2 0.00000 -0.01344 0.05582 0.00000 -0.02513 # CY2 0.00000 -0.06288 -0.03618 0.00000 0.00349 # CZ2 -0.05565 0.00000 0.00000 0.07815 0.00000 # ... # Molpro prints low frequency modes in a subsequent section with the same format, # which also contains zero frequency modes, with the title: # Normal Modes of low/zero frequencies if line[1:13] == "Normal Modes": if line[1:37] == "Normal Modes of low/zero frequencies": islow = True else: islow = False self.skip_line(inputfile, 'blank') # Each portion of five modes is followed by a single blank line. # The whole block is followed by an additional blank line. line = next(inputfile) while line.strip(): if line[1:25].isspace(): numbers = list(map(int, line.split()[::2])) vibsyms = line.split()[1::2] if line[1:12] == "Wavenumbers": vibfreqs = list(map(float, line.strip().split()[2:])) if line[1:21] == "Intensities [km/mol]": vibirs = list(map(float, line.strip().split()[2:])) # There should always by 3xnatom displacement rows. if line[1:11].isspace() and line[13:25].strip().isdigit(): # There are a maximum of 5 modes per line. nmodes = len(line.split())-1 vibdisps = [] for i in range(nmodes): vibdisps.append([]) for n in range(self.natom): vibdisps[i].append([]) for i in range(nmodes): disp = float(line.split()[i+1]) vibdisps[i][0].append(disp) for i in range(self.natom*3 - 1): line = next(inputfile) iatom = (i+1)//3 for i in range(nmodes): disp = float(line.split()[i+1]) vibdisps[i][iatom].append(disp) line = next(inputfile) if not line.strip(): if not hasattr(self, "vibfreqs"): self.vibfreqs = [] if not hasattr(self, "vibsyms"): self.vibsyms = [] if not hasattr(self, "vibirs") and "vibirs" in dir(): self.vibirs = [] if not hasattr(self, "vibdisps") and "vibdisps" in dir(): self.vibdisps = [] if not islow: self.vibfreqs.extend(vibfreqs) self.vibsyms.extend(vibsyms) if "vibirs" in dir(): self.vibirs.extend(vibirs) if "vibdisps" in dir(): self.vibdisps.extend(vibdisps) else: nonzero = [f > 0 for f in vibfreqs] vibfreqs = [f for f in vibfreqs if f > 0] self.vibfreqs = vibfreqs + self.vibfreqs vibsyms = [vibsyms[i] for i in range(len(vibsyms)) if nonzero[i]] self.vibsyms = vibsyms + self.vibsyms if "vibirs" in dir(): vibirs = [vibirs[i] for i in range(len(vibirs)) if nonzero[i]] self.vibirs = vibirs + self.vibirs if "vibdisps" in dir(): vibdisps = [vibdisps[i] for i in range(len(vibdisps)) if nonzero[i]] self.vibdisps = vibdisps + self.vibdisps line = next(inputfile) if line[1:16] == "Force Constants": self.logger.info("Creating attribute hessian") self.hessian = [] line = next(inputfile) hess = [] tmp = [] while line.strip(): try: list(map(float, line.strip().split()[2:])) except: line = next(inputfile) line.strip().split()[1:] hess.extend([list(map(float, line.strip().split()[1:]))]) line = next(inputfile) lig = 0 while (lig==0) or (len(hess[0]) > 1): tmp.append(hess.pop(0)) lig += 1 k = 5 while len(hess) != 0: tmp[k] += hess.pop(0) k += 1 if (len(tmp[k-1]) == lig): break if k >= lig: k = len(tmp[-1]) for l in tmp: self.hessian += l if line[1:14] == "Atomic Masses" and hasattr(self,"hessian"): line = next(inputfile) self.amass = list(map(float, line.strip().split()[2:])) while line.strip(): line = next(inputfile) self.amass += list(map(float, line.strip().split()[2:])) #1PROGRAM * POP (Mulliken population analysis) # # # Density matrix read from record 2100.2 Type=RHF/CHARGE (state 1.1) # # Population analysis by basis function type # # Unique atom s p d f g Total Charge # 2 C 3.11797 2.88497 0.00000 0.00000 0.00000 6.00294 - 0.00294 # 3 C 3.14091 2.91892 0.00000 0.00000 0.00000 6.05984 - 0.05984 # ... if line.strip() == "1PROGRAM * POP (Mulliken population analysis)": self.skip_lines(inputfile, ['b', 'b', 'density_source', 'b', 'func_type', 'b']) header = next(inputfile) icharge = header.split().index('Charge') charges = [] line = next(inputfile) while line.strip(): cols = line.split() charges.append(float(cols[icharge]+cols[icharge+1])) line = next(inputfile) if not hasattr(self, "atomcharges"): self.atomcharges = {} self.atomcharges['mulliken'] = charges if __name__ == "__main__": import doctest, molproparser doctest.testmod(molproparser, verbose=False)
jchodera/cclib
src/cclib/parser/molproparser.py
Python
lgpl-2.1
38,027
[ "GAMESS", "Gaussian", "Molpro", "cclib" ]
6c7a47fcb33e5a514d10586160b95bfb6a87b92cb9a445a7f8c78fd2d5316dac
# Copyright (C) 2018, 2017 # Max Planck Institute for Polymer Research # # 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/>. r""" **************************************************** **espressopp.integrator.LangevinThermostatOnRadius** **************************************************** Langevin Thermostat for Radii of Particles Example: >>> radius_mass = mass >>> # set virtual mass for dynamics of radius >>> langevin = espressopp.integrator.LangevinThermostatOnRadius(system, radius_mass) >>> # set up the thermostat >>> langevin.gamma = gamma >>> # set friction coefficient gamma >>> langevin.temperature = temp >>> # set temperature >>> integrator.addExtension(langevin) >>> # add extensions to a previously defined integrator .. function:: espressopp.integrator.LangevinThermostatOnRadius(system, dampingmass) :param system: :param _dampingmass: :type system: :type dampingmass: real .. function:: espressopp.integrator.LangevinThermostatOnRadius.addExclusions(pidlist) :param pidlist: list of particle ids to be excluded from thermostating. :type pidlist: list of ints """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_LangevinThermostatOnRadius class LangevinThermostatOnRadiusLocal(ExtensionLocal, integrator_LangevinThermostatOnRadius): def __init__(self, system, dampingmass): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_LangevinThermostatOnRadius, system, dampingmass) def addExclusions(self, pidlist): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): for pid in pidlist: self.cxxclass.addExclpid(self, pid) if pmi.isController : class LangevinThermostatOnRadius(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.LangevinThermostatOnRadiusLocal', pmiproperty = [ 'gamma', 'temperature'], pmicall = [ 'addExclusions' ] )
espressopp/espressopp
src/integrator/LangevinThermostatOnRadius.py
Python
gpl-3.0
2,876
[ "ESPResSo" ]
221661def68c669a848f4de2e74d5af3b1d0354b0c50e586d10f6534bf73e4c5
''' More information at: http://www.pymolwiki.org/index.php/elbow_angle Calculate the elbow angle of an antibody Fab complex and optionally draw a graphical representation of the vectors used to determine the angle. NOTE: There is no automatic checking of the validity of limit_l and limit_h values or of the assignment of light and heavy chain IDs. If these are entered incorrectly or omitted, the reported angle will likely be incorrect. As always with these things, your mileage may vary. Use at your own risk! REQUIREMENTS numpy, version 1.6 http://numpy.scipy.org transformations.py, version 2012.01.01 by Christoph Gohlke www.lfd.uci.edu/~gohlke/code May also require an edit to transformations.py: Changes `1e-8` to `1e-7` in lines 357 & 363 to avoid a numerical error. com.py by Jason Vertrees http://www.pymolwiki.org/index.php/com ''' __author__ = 'Jared Sampson' __version__ = '0.1' from pymol import cmd import transformations import com import numpy ################################################################################ def calc_super_matrix(mobile,static): ''' DESCRIPTION Aligns two objects (or selections), returns the transformation matrix, and resets the matrix of the mobile object. Uses CEAlign PyMOL function for alignment. ARGUMENTS mobile = string: selection describing the mobile object whose rotation matrix will be reported static = string: selection describing the static object onto which the mobile object will be aligned REQUIRES: numpy ''' cmd.cealign(static,mobile) # cmd.super(mobile,static) T = cmd.get_object_matrix(mobile) R = numpy.identity(4) k=0 for i in range (0,4): for j in range (0,4): R[i][j] = T[k] k+=1 return R ################################################################################ def elbow_angle(obj,heavy,light,limit_h=113,limit_l=109,draw=0): #def elbow_angle(obj,light='D',heavy='E',limit_l=128,limit_h=126,draw=1): """ DESCRIPTION Calculates the integer elbow angle of an antibody Fab complex and optionally draws a graphical representation of the vectors used to determine the angle. ARGUMENTS obj = string: object light/heavy = strings: chain ID of light and heavy chains, respectively limit_l/limit_h = integers: residue numbers of the last residue in the light and heavy chain variable domains, respectively draw = boolean: Choose whether or not to draw the angle visualization REQUIRES: com.py, transformations.py, numpy (see above) """ # store current view orig_view = cmd.get_view() limit_l = int(limit_l) limit_h = int(limit_h) draw = int(draw) # for temp object names tmp_prefix = "tmp_elbow_" prefix = tmp_prefix + obj + '_' # names vl = prefix + 'VL' vh = prefix + 'VH' cl = prefix + 'CL' ch = prefix + 'CH' # selections vl_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, light, limit_l) vh_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, heavy, limit_h) cl_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, light, limit_l) ch_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h) v_sel = '(('+vl_sel+') or ('+vh_sel+'))' c_sel = '(('+cl_sel+') or ('+ch_sel+'))' # create temp objects cmd.create(vl,vl_sel) cmd.create(vh,vh_sel) cmd.create(cl,cl_sel) cmd.create(ch,ch_sel) # superimpose vl onto vh, calculate axis and angle Rv = calc_super_matrix(vl,vh) angle_v,direction_v,point_v = transformations.rotation_from_matrix(Rv) # superimpose cl onto ch, calculate axis and angle Rc = calc_super_matrix(cl,ch) angle_c,direction_c,point_c = transformations.rotation_from_matrix(Rc) # delete temporary objects cmd.delete(vl) cmd.delete(vh) cmd.delete(cl) cmd.delete(ch) # if dot product is positive, angle is acute if (numpy.dot(direction_v,direction_c)>0): direction_c = direction_c * -1 # ensure angle is > 90 (need to standardize this) # TODO: make both directions point away from the elbow axis. elbow = int(numpy.degrees(numpy.arccos(numpy.dot(direction_v,direction_c)))) # while (elbow < 90): # elbow = 180 - elbow # limit to physically reasonable range # compare the direction_v and direction_c axes to the vector defined by # the C-alpha atoms of limit_l and limit_h of the original fab hinge_l_sel = "%s//%s/%s/CA" % (obj,light,limit_l) hinge_h_sel = "%s//%s/%s/CA" % (obj,heavy,limit_h) hinge_l = cmd.get_atom_coords(hinge_l_sel) hinge_h = cmd.get_atom_coords(hinge_h_sel) hinge_vec = numpy.array(hinge_h) - numpy.array(hinge_l) test = numpy.dot(hinge_vec,numpy.cross(direction_v,direction_c)) if (test > 0): elbow = 360 - elbow #print " Elbow angle: %i degrees" % elbow if (draw==1): # there is probably a more elegant way to do this, but # it works so I'm not going to mess with it for now pre = obj+'_elbow_' # draw hinge vector cmd.pseudoatom(pre+"hinge_l",pos=hinge_l) cmd.pseudoatom(pre+"hinge_h",pos=hinge_h) cmd.distance(pre+"hinge_vec",pre+"hinge_l",pre+"hinge_h") cmd.set("dash_gap",0) # draw the variable domain axis com_v = com.COM(v_sel) start_v = [a - 10*b for a, b in zip(com_v, direction_v)] end_v = [a + 10*b for a, b in zip(com_v, direction_v)] cmd.pseudoatom(pre+"start_v",pos=start_v) cmd.pseudoatom(pre+"end_v",pos=end_v) cmd.distance(pre+"v_vec",pre+"start_v",pre+"end_v") # draw the constant domain axis com_c = com.COM(c_sel) start_c = [a - 10*b for a, b in zip(com_c, direction_c)] end_c = [a + 10*b for a, b in zip(com_c, direction_c)] cmd.pseudoatom(pre+"start_c",pos=start_c) cmd.pseudoatom(pre+"end_c",pos=end_c) cmd.distance(pre+"c_vec",pre+"start_c",pre+"end_c") # customize appearance cmd.hide("labels",pre+"hinge_vec");cmd.hide("labels",pre+"v_vec");cmd.hide("labels",pre+"c_vec"); cmd.color("green",pre+"hinge_l");cmd.color("red",pre+"hinge_h");cmd.color("black",pre+"hinge_vec"); cmd.color("black",pre+"start_v");cmd.color("black",pre+"end_v");cmd.color("black",pre+"v_vec"); cmd.color("black",pre+"start_c");cmd.color("black",pre+"end_c");cmd.color("black",pre+"c_vec") # draw spheres cmd.show("spheres",pre+"hinge_l or "+pre+"hinge_h") cmd.show("spheres",pre+"start_v or "+pre+"start_c") cmd.show("spheres",pre+"end_v or "+pre+"end_c") cmd.set("sphere_scale",2) cmd.set("dash_gap",0,pre+"hinge_vec") cmd.set("dash_width",5) cmd.set("dash_radius",0.3) # group drawing objects cmd.group(pre,pre+"*") # restore original view cmd.set_view(orig_view) return elbow def setup_antibody(): my_struc = cmd.load("1mhp_ch.pdb") my_elbow = elbow_angle(my_struc) print(my_elbow) return 0
demharters/git_scripts
my_elbow_angle_ab.py
Python
apache-2.0
7,399
[ "PyMOL" ]
29d448ac87a1f2092ff257b463aee2ae0c96c225cb4db5a8ab2ee84655c43eaf
""" Actions manager for transcripts ajax calls. +++++++++++++++++++++++++++++++++++++++++++ Module do not support rollback (pressing "Cancel" button in Studio) All user changes are saved immediately. """ import copy import json import logging import os import requests from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse from django.utils.translation import ugettext as _ from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import UsageKey from student.auth import has_course_author_access from util.json_request import JsonResponse from xmodule.contentstore.content import StaticContent from xmodule.contentstore.django import contentstore from xmodule.exceptions import NotFoundError from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.video_module.transcripts_utils import ( copy_or_rename_transcript, download_youtube_subs, GetTranscriptsFromYouTubeException, get_video_transcript_content, generate_subs_from_source, get_transcripts_from_youtube, is_val_transcript_feature_enabled_for_course, manage_video_subtitles_save, remove_subs_from_store, Transcript, TranscriptsRequestValidationException, youtube_video_transcript_name, ) __all__ = [ 'upload_transcripts', 'download_transcripts', 'check_transcripts', 'choose_transcripts', 'replace_transcripts', 'rename_transcripts', 'save_transcripts', ] log = logging.getLogger(__name__) def error_response(response, message, status_code=400): """ Simplify similar actions: log message and return JsonResponse with message included in response. By default return 400 (Bad Request) Response. """ log.debug(message) response['status'] = message return JsonResponse(response, status_code) @login_required def upload_transcripts(request): """ Upload transcripts for current module. returns: response dict:: status: 'Success' and HTTP 200 or 'Error' and HTTP 400. subs: Value of uploaded and saved html5 sub field in video item. """ response = { 'status': 'Unknown server error', 'subs': '', } locator = request.POST.get('locator') if not locator: return error_response(response, 'POST data without "locator" form data.') try: item = _get_item(request, request.POST) except (InvalidKeyError, ItemNotFoundError): return error_response(response, "Can't find item by locator.") if 'transcript-file' not in request.FILES: return error_response(response, 'POST data without "file" form data.') video_list = request.POST.get('video_list') if not video_list: return error_response(response, 'POST data without video names.') try: video_list = json.loads(video_list) except ValueError: return error_response(response, 'Invalid video_list JSON.') # Used utf-8-sig encoding type instead of utf-8 to remove BOM(Byte Order Mark), e.g. U+FEFF source_subs_filedata = request.FILES['transcript-file'].read().decode('utf-8-sig') source_subs_filename = request.FILES['transcript-file'].name if '.' not in source_subs_filename: return error_response(response, "Undefined file extension.") basename = os.path.basename(source_subs_filename) source_subs_name = os.path.splitext(basename)[0] source_subs_ext = os.path.splitext(basename)[1][1:] if item.category != 'video': return error_response(response, 'Transcripts are supported only for "video" modules.') # Allow upload only if any video link is presented if video_list: sub_attr = source_subs_name try: # Generate and save for 1.0 speed, will create subs_sub_attr.srt.sjson subtitles file in storage. generate_subs_from_source({1: sub_attr}, source_subs_ext, source_subs_filedata, item) for video_dict in video_list: video_name = video_dict['video'] # We are creating transcripts for every video source, if in future some of video sources would be deleted. # Updates item.sub with `video_name` on success. copy_or_rename_transcript(video_name, sub_attr, item, user=request.user) response['subs'] = item.sub response['status'] = 'Success' except Exception as ex: return error_response(response, ex.message) else: return error_response(response, 'Empty video sources.') return JsonResponse(response) @login_required def download_transcripts(request): """ Passes to user requested transcripts file. Raises Http404 if unsuccessful. """ locator = request.GET.get('locator') subs_id = request.GET.get('subs_id') if not locator: log.debug('GET data without "locator" property.') raise Http404 try: item = _get_item(request, request.GET) except (InvalidKeyError, ItemNotFoundError): log.debug("Can't find item by locator.") raise Http404 if item.category != 'video': log.debug('transcripts are supported only for video" modules.') raise Http404 try: if not subs_id: raise NotFoundError filename = subs_id content_location = StaticContent.compute_location( item.location.course_key, 'subs_{filename}.srt.sjson'.format(filename=filename), ) sjson_transcript = contentstore().find(content_location).data except NotFoundError: # Try searching in VAL for the transcript as a last resort transcript = None if is_val_transcript_feature_enabled_for_course(item.location.course_key): transcript = get_video_transcript_content( language_code=u'en', edx_video_id=item.edx_video_id, youtube_id_1_0=item.youtube_id_1_0, html5_sources=item.html5_sources, ) if not transcript: raise Http404 filename = os.path.splitext(os.path.basename(transcript['file_name']))[0].encode('utf8') sjson_transcript = transcript['content'] # convert sjson content into srt format. transcript_content = Transcript.convert(sjson_transcript, input_format='sjson', output_format='srt') if not transcript_content: raise Http404 # Construct an HTTP response response = HttpResponse(transcript_content, content_type='application/x-subrip; charset=utf-8') response['Content-Disposition'] = 'attachment; filename="{filename}.srt"'.format(filename=filename) return response @login_required def check_transcripts(request): """ Check state of transcripts availability. request.GET['data'] has key `videos`, which can contain any of the following:: [ {u'type': u'youtube', u'video': u'OEoXaMPEzfM', u'mode': u'youtube'}, {u'type': u'html5', u'video': u'video1', u'mode': u'mp4'} {u'type': u'html5', u'video': u'video2', u'mode': u'webm'} ] `type` is youtube or html5 `video` is html5 or youtube video_id `mode` is youtube, ,p4 or webm Returns transcripts_presence dict:: html5_local: list of html5 ids, if subtitles exist locally for them; is_youtube_mode: bool, if we have youtube_id, and as youtube mode is of higher priority, reflect this with flag; youtube_local: bool, if youtube transcripts exist locally; youtube_server: bool, if youtube transcripts exist on server; youtube_diff: bool, if youtube transcripts exist on youtube server, and are different from local youtube ones; current_item_subs: string, value of item.sub field; status: string, 'Error' or 'Success'; subs: string, new value of item.sub field, that should be set in module; command: string, action to front-end what to do and what to show to user. """ transcripts_presence = { 'html5_local': [], 'html5_equal': False, 'is_youtube_mode': False, 'youtube_local': False, 'youtube_server': False, 'youtube_diff': True, 'current_item_subs': None, 'status': 'Error', } try: __, videos, item = _validate_transcripts_data(request) except TranscriptsRequestValidationException as e: return error_response(transcripts_presence, e.message) transcripts_presence['status'] = 'Success' filename = 'subs_{0}.srt.sjson'.format(item.sub) content_location = StaticContent.compute_location(item.location.course_key, filename) try: local_transcripts = contentstore().find(content_location).data transcripts_presence['current_item_subs'] = item.sub except NotFoundError: pass # Check for youtube transcripts presence youtube_id = videos.get('youtube', None) if youtube_id: transcripts_presence['is_youtube_mode'] = True # youtube local filename = 'subs_{0}.srt.sjson'.format(youtube_id) content_location = StaticContent.compute_location(item.location.course_key, filename) try: local_transcripts = contentstore().find(content_location).data transcripts_presence['youtube_local'] = True except NotFoundError: log.debug("Can't find transcripts in storage for youtube id: %s", youtube_id) # youtube server youtube_text_api = copy.deepcopy(settings.YOUTUBE['TEXT_API']) youtube_text_api['params']['v'] = youtube_id youtube_transcript_name = youtube_video_transcript_name(youtube_text_api) if youtube_transcript_name: youtube_text_api['params']['name'] = youtube_transcript_name youtube_response = requests.get('http://' + youtube_text_api['url'], params=youtube_text_api['params']) if youtube_response.status_code == 200 and youtube_response.text: transcripts_presence['youtube_server'] = True #check youtube local and server transcripts for equality if transcripts_presence['youtube_server'] and transcripts_presence['youtube_local']: try: youtube_server_subs = get_transcripts_from_youtube( youtube_id, settings, item.runtime.service(item, "i18n") ) if json.loads(local_transcripts) == youtube_server_subs: # check transcripts for equality transcripts_presence['youtube_diff'] = False except GetTranscriptsFromYouTubeException: pass # Check for html5 local transcripts presence html5_subs = [] for html5_id in videos['html5']: filename = 'subs_{0}.srt.sjson'.format(html5_id) content_location = StaticContent.compute_location(item.location.course_key, filename) try: html5_subs.append(contentstore().find(content_location).data) transcripts_presence['html5_local'].append(html5_id) except NotFoundError: log.debug("Can't find transcripts in storage for non-youtube video_id: %s", html5_id) if len(html5_subs) == 2: # check html5 transcripts for equality transcripts_presence['html5_equal'] = json.loads(html5_subs[0]) == json.loads(html5_subs[1]) command, subs_to_use = _transcripts_logic(transcripts_presence, videos) if command == 'not_found': # Try searching in VAL for the transcript as a last resort if is_val_transcript_feature_enabled_for_course(item.location.course_key): video_transcript = get_video_transcript_content( language_code=u'en', edx_video_id=item.edx_video_id, youtube_id_1_0=item.youtube_id_1_0, html5_sources=item.html5_sources, ) command = 'found' if video_transcript else command transcripts_presence.update({ 'command': command, 'subs': subs_to_use, }) return JsonResponse(transcripts_presence) def _transcripts_logic(transcripts_presence, videos): """ By `transcripts_presence` content, figure what show to user: returns: `command` and `subs`. `command`: string, action to front-end what to do and what show to user. `subs`: string, new value of item.sub field, that should be set in module. `command` is one of:: replace: replace local youtube subtitles with server one's found: subtitles are found import: import subtitles from youtube server choose: choose one from two html5 subtitles not found: subtitles are not found """ command = None # new value of item.sub field, that should be set in module. subs = '' # youtube transcripts are of high priority than html5 by design if ( transcripts_presence['youtube_diff'] and transcripts_presence['youtube_local'] and transcripts_presence['youtube_server']): # youtube server and local exist command = 'replace' subs = videos['youtube'] elif transcripts_presence['youtube_local']: # only youtube local exist command = 'found' subs = videos['youtube'] elif transcripts_presence['youtube_server']: # only youtube server exist command = 'import' else: # html5 part if transcripts_presence['html5_local']: # can be 1 or 2 html5 videos if len(transcripts_presence['html5_local']) == 1 or transcripts_presence['html5_equal']: command = 'found' subs = transcripts_presence['html5_local'][0] else: command = 'choose' subs = transcripts_presence['html5_local'][0] else: # html5 source have no subtitles # check if item sub has subtitles if transcripts_presence['current_item_subs'] and not transcripts_presence['is_youtube_mode']: log.debug("Command is use existing %s subs", transcripts_presence['current_item_subs']) command = 'use_existing' else: command = 'not_found' log.debug( "Resulted command: %s, current transcripts: %s, youtube mode: %s", command, transcripts_presence['current_item_subs'], transcripts_presence['is_youtube_mode'] ) return command, subs @login_required def choose_transcripts(request): """ Replaces html5 subtitles, presented for both html5 sources, with chosen one. Code removes rejected html5 subtitles and updates sub attribute with chosen html5_id. It does nothing with youtube id's. Returns: status `Success` and resulted item.sub value or status `Error` and HTTP 400. """ response = { 'status': 'Error', 'subs': '', } try: data, videos, item = _validate_transcripts_data(request) except TranscriptsRequestValidationException as e: return error_response(response, e.message) html5_id = data.get('html5_id') # html5_id chosen by user # find rejected html5_id and remove appropriate subs from store html5_id_to_remove = [x for x in videos['html5'] if x != html5_id] if html5_id_to_remove: remove_subs_from_store(html5_id_to_remove, item) if item.sub != html5_id: # update sub value item.sub = html5_id item.save_with_metadata(request.user) response = { 'status': 'Success', 'subs': item.sub, } return JsonResponse(response) @login_required def replace_transcripts(request): """ Replaces all transcripts with youtube ones. Downloads subtitles from youtube and replaces all transcripts with downloaded ones. Returns: status `Success` and resulted item.sub value or status `Error` and HTTP 400. """ response = {'status': 'Error', 'subs': ''} try: __, videos, item = _validate_transcripts_data(request) except TranscriptsRequestValidationException as e: return error_response(response, e.message) youtube_id = videos['youtube'] if not youtube_id: return error_response(response, 'YouTube id {} is not presented in request data.'.format(youtube_id)) try: download_youtube_subs(youtube_id, item, settings) except GetTranscriptsFromYouTubeException as e: return error_response(response, e.message) item.sub = youtube_id item.save_with_metadata(request.user) response = { 'status': 'Success', 'subs': item.sub, } return JsonResponse(response) def _validate_transcripts_data(request): """ Validates, that request contains all proper data for transcripts processing. Returns tuple of 3 elements:: data: dict, loaded json from request, videos: parsed `data` to useful format, item: video item from storage Raises `TranscriptsRequestValidationException` if validation is unsuccessful or `PermissionDenied` if user has no access. """ data = json.loads(request.GET.get('data', '{}')) if not data: raise TranscriptsRequestValidationException(_('Incoming video data is empty.')) try: item = _get_item(request, data) except (InvalidKeyError, ItemNotFoundError): raise TranscriptsRequestValidationException(_("Can't find item by locator.")) if item.category != 'video': raise TranscriptsRequestValidationException(_('Transcripts are supported only for "video" modules.')) # parse data form request.GET.['data']['video'] to useful format videos = {'youtube': '', 'html5': {}} for video_data in data.get('videos'): if video_data['type'] == 'youtube': videos['youtube'] = video_data['video'] else: # do not add same html5 videos if videos['html5'].get('video') != video_data['video']: videos['html5'][video_data['video']] = video_data['mode'] return data, videos, item @login_required def rename_transcripts(request): """ Create copies of existing subtitles with new names of HTML5 sources. Old subtitles are not deleted now, because we do not have rollback functionality. If succeed, Item.sub will be chosen randomly from html5 video sources provided by front-end. """ response = {'status': 'Error', 'subs': ''} try: __, videos, item = _validate_transcripts_data(request) except TranscriptsRequestValidationException as e: return error_response(response, e.message) old_name = item.sub for new_name in videos['html5'].keys(): # copy subtitles for every HTML5 source try: # updates item.sub with new_name if it is successful. copy_or_rename_transcript(new_name, old_name, item, user=request.user) except NotFoundError: # subtitles file `item.sub` is not presented in the system. Nothing to copy or rename. error_response(response, "Can't find transcripts in storage for {}".format(old_name)) response['status'] = 'Success' response['subs'] = item.sub # item.sub has been changed, it is not equal to old_name. log.debug("Updated item.sub to %s", item.sub) return JsonResponse(response) @login_required def save_transcripts(request): """ Saves video module with updated values of fields. Returns: status `Success` or status `Error` and HTTP 400. """ response = {'status': 'Error'} data = json.loads(request.GET.get('data', '{}')) if not data: return error_response(response, 'Incoming video data is empty.') try: item = _get_item(request, data) except (InvalidKeyError, ItemNotFoundError): return error_response(response, "Can't find item by locator.") metadata = data.get('metadata') if metadata is not None: new_sub = metadata.get('sub') for metadata_key, value in metadata.items(): setattr(item, metadata_key, value) item.save_with_metadata(request.user) # item becomes updated with new values if new_sub: manage_video_subtitles_save(item, request.user) else: # If `new_sub` is empty, it means that user explicitly does not want to use # transcripts for current video ids and we remove all transcripts from storage. current_subs = data.get('current_subs') if current_subs is not None: for sub in current_subs: remove_subs_from_store(sub, item) response['status'] = 'Success' return JsonResponse(response) def _get_item(request, data): """ Obtains from 'data' the locator for an item. Next, gets that item from the modulestore (allowing any errors to raise up). Finally, verifies that the user has access to the item. Returns the item. """ usage_key = UsageKey.from_string(data.get('locator')) # This is placed before has_course_author_access() to validate the location, # because has_course_author_access() raises r if location is invalid. item = modulestore().get_item(usage_key) # use the item's course_key, because the usage_key might not have the run if not has_course_author_access(request.user, item.location.course_key): raise PermissionDenied() return item
lduarte1991/edx-platform
cms/djangoapps/contentstore/views/transcripts_ajax.py
Python
agpl-3.0
21,535
[ "FEFF" ]
18d507601802577694bb09aacd973541a28af0edddbcc3194d3927b9e57da746
# -*- coding: utf-8 -*- # # test_connect_array_fixed_indegree.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/>. """ Tests of connection with rule fixed_indegree and parameter arrays in syn_spec """ import unittest import nest import numpy @nest.ll_api.check_stack class ConnectArrayFixedIndegreeTestCase(unittest.TestCase): """Tests of connections with fixed indegree and parameter arrays""" def test_Connect_Array_Fixed_Indegree(self): """Tests of connections with fixed indegree and parameter arrays""" N = 20 # number of neurons in each subnet K = 5 # number of connections per neuron ############################################ # test with connection rule fixed_indegree ############################################ nest.ResetKernel() net1 = nest.Create('iaf_psc_alpha', N) # creates source subnet net2 = nest.Create('iaf_psc_alpha', N) # creates target subnet Warr = [[y*K+x for x in range(K)] for y in range(N)] # weight array Darr = [[y*K+x + 1 for x in range(K)] for y in range(N)] # delay array # synapses and connection dictionaries syn_dict = {'model': 'static_synapse', 'weight': Warr, 'delay': Darr} conn_dict = {'rule': 'fixed_indegree', 'indegree': K} # connects source to target subnet nest.Connect(net1, net2, conn_spec=conn_dict, syn_spec=syn_dict) for i in range(N): # loop on all neurons of target subnet # gets all connections to the target neuron conns = nest.GetConnections(target=net2[i:i+1]) Warr1 = [] # creates empty weight array # loop on synapses that connect to target neuron for j in range(len(conns)): c = conns[j:j+1] w = nest.GetStatus(c, 'weight')[0] # gets synaptic weight d = nest.GetStatus(c, 'delay')[0] # gets synaptic delay self.assertTrue(d - w == 1) # checks that delay = weight + 1 Warr1.append(w) # appends w to Warr1 self.assertTrue(len(Warr1) == K) # checks the size of Warr1 Warr1.sort() # sorts the elements of Warr1 # get row of original weight array, sort it # and compare it with Warr1 Warr2 = sorted(Warr[i]) for k in range(K): self.assertTrue(Warr1[k]-Warr2[k] == 0.0) def suite(): suite = unittest.makeSuite(ConnectArrayFixedIndegreeTestCase, 'test') return suite def run(): runner = unittest.TextTestRunner(verbosity=2) runner.run(suite()) if __name__ == "__main__": run()
hakonsbm/nest-simulator
pynest/nest/tests/test_connect_array_fixed_indegree.py
Python
gpl-2.0
3,322
[ "NEURON" ]
df738b1aecbafcd8734aeb97e2771b83ba149ac787a005966bdf552020a457b7
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2014--, tax-credit development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from setuptools import find_packages, setup setup( name='tax-credit', version='0.0.0-dev', license='BSD-3-Clause', packages=find_packages(), install_requires=['biom-format', 'pandas', 'statsmodels', 'bokeh', 'scipy', 'jupyter', 'scikit-bio', 'seaborn'], author="Nicholas Bokulich", author_email="nbokulich@gmail.com", description="Systematic benchmarking of taxonomic classification methods", url="https://github.com/caporaso-lab/short-read-tax-assignment" )
nbokulich/short-read-tax-assignment
setup.py
Python
bsd-3-clause
895
[ "scikit-bio" ]
d69bbf5e2bd0efec705abfde7c06dff74c4b6890f5a7914e15a9d88991139ecc
""" Tests for the antisite renderer """ from __future__ import absolute_import from __future__ import unicode_literals import unittest import numpy as np import vtk from vtk.util import numpy_support from .. import antisiteRenderer from ... import utils from six.moves import range ################################################################################ # required unless ColouringOptions is rewritten to have a non GUI dependent settings object class DummyColouringOpts(object): def __init__(self): self.colourBy = "Species" self.heightAxis = 1 self.minVal = 0.0 self.maxVal = 1.0 self.solidColourRGB = (1.0, 0.0, 0.0) self.scalarBarText = "Height in Y (A)" ################################################################################ class TestAntisiteRenderer(unittest.TestCase): """ Test the antisite renderer """ def setUp(self): """ Called before each test """ # arrays points = np.asarray([[1.2,1.2,1.6], [0,0,0], [8,8,8], [5.4,8,1], [4,1,0]], dtype=np.float64) scalars = np.asarray([0,0,1,0,1], dtype=np.float64) radii = np.asarray([1.2, 1.2, 0.8, 1.5, 1.1], dtype=np.float64) # convert to vtk arrays self.atomPoints = utils.NumpyVTKData(points) self.radiusArray = utils.NumpyVTKData(radii, name="radius") self.scalarsArray = utils.NumpyVTKData(scalars, name="colours") # lut self.nspecies = 2 self.lut = vtk.vtkLookupTable() self.lut.SetNumberOfColors(self.nspecies) self.lut.SetNumberOfTableValues(self.nspecies) self.lut.SetTableRange(0, self.nspecies - 1) self.lut.SetRange(0, self.nspecies - 1) for i in range(self.nspecies): self.lut.SetTableValue(i, 1, 0, 0, 1.0) def tearDown(self): """ Called after each test """ # remove refs self.atomPoints = None self.radiusArray = None self.scalarsArray = None self.lut = None def test_antisiteRenderer(self): """ Antisite renderer """ # the renderer renderer = antisiteRenderer.AntisiteRenderer() # some settings colouringOptions = DummyColouringOpts() atomScaleFactor = 1 # render atoms renderer.render(self.atomPoints, self.scalarsArray, self.radiusArray, self.nspecies, colouringOptions, atomScaleFactor, self.lut) # check result is correct type self.assertIsInstance(renderer.getActor(), utils.ActorObject)
chrisdjscott/Atoman
atoman/rendering/renderers/tests/test_antisiteRenderer.py
Python
mit
2,673
[ "VTK" ]
1e2920f59e8d6430bf24817c78b445d0a675b4f3c3fe19dbfcb44c8f67226aec
# Licensed to Tomaz Muraus under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # Tomaz muraus 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 os import logging from optparse import OptionParser from libcloud.storage.providers import get_driver from libcloud.storage.types import Provider from file_syncer.log import get_logger from file_syncer.constants import VALID_LOG_LEVELS from file_syncer.syncer import FileSyncer SUPPORTED_PROVIDERS = [p for p in Provider.__dict__.keys() if not p.startswith('__')] PROVIDER_MAP = dict([(k, v) for k, v in Provider.__dict__.iteritems() if not k.startswith('__')]) REQUIRED_OPTIONS = [('username', 'api_username'), ('key', 'api_key'), ('container-name', 'container_name'), ('directory', 'directory')] def run(): usage = 'usage: %prog --username=<api username> --key=<api key> [options]' parser = OptionParser(usage=usage) parser.add_option('--provider', dest='provider', default='CLOUDFILES_US', help='Provider to use') parser.add_option('--region', dest='region', default=None, help='Region to use if a Libcloud driver supports \ multiple regions (e.g. ORD for CloudFiles provider)') parser.add_option('--username', dest='api_username', help='API username') parser.add_option('--key', dest='api_key', help='API key') parser.add_option('--restore', dest='restore', action="store_true", help='Restore from') parser.add_option('--container-name', dest='container_name', default='file_syncer', help='Name of the container storing the files') parser.add_option('--directory', dest='directory', help='Local directory to sync') parser.add_option('--cache-path', dest='cache_path', default=os.path.expanduser('~/.file_syncer'), help='Directory where a settings and cached manifest ' + 'files are stored') parser.add_option('--concurrency', dest='concurrency', default=10, help='File upload concurrency') parser.add_option('--exclude', dest='exclude', help='Comma separated list of file name patterns to ' + 'exclude') parser.add_option('--log-level', dest='log_level', default='INFO', help='Log level') parser.add_option('--delete', dest='delete', action='store_true', help='delete extraneous files from dest containers', default=False) parser.add_option('--auto-content-type', dest='auto_content_type', default=False, action='store_true', help='Don\'t automatically specify \'application/' + 'octet-stream\' content-type for every file. Use ' + 'automatic file type detection based on the file ' + 'extension') parser.add_option('--ignore-symlinks', dest='ignore_symlinks', default=False, action='store_true', help='Don\'t visit directories pointed to by ' + 'symlinks, on systems that support them') (options, args) = parser.parse_args() for option_name, key in REQUIRED_OPTIONS: if not getattr(options, key, None): raise ValueError('Missing required argument: ' + option_name) # Set up provider if options.provider not in SUPPORTED_PROVIDERS: raise ValueError('Invalid provider: %s. Valid providers are: %s' % (options.provider, ', '.join(SUPPORTED_PROVIDERS))) provider = PROVIDER_MAP[options.provider] # Set up logger log_level = options.log_level.upper() if log_level not in VALID_LOG_LEVELS: valid_levels = [value.lower() for value in VALID_LOG_LEVELS] raise ValueError('Invalid log level: %s. Valid log levels are: %s' % (options.log_level, ', ' .join(valid_levels))) level = getattr(logging, log_level, 'INFO') logger = get_logger(handler=logging.StreamHandler(), level=level) directory = os.path.expanduser(options.directory) exclude_patterns = options.exclude or '' exclude_patterns = exclude_patterns.split(',') syncer = FileSyncer(directory=directory, provider_cls=get_driver(provider), provider=provider, region=options.region, username=options.api_username, api_key=options.api_key, container_name=options.container_name, cache_path=options.cache_path, exclude_patterns=exclude_patterns, logger=logger, concurrency=int(options.concurrency), no_content_type=options.no_content_type, ignore_symlinks=options.ignore_symlinks) if options.restore: syncer.restore() else: syncer.sync(options.delete)
ogrisel/python-file-syncer
file_syncer/run.py
Python
apache-2.0
5,893
[ "VisIt" ]
22d2a293d64b7fc9c9bf3f402765033c18f7c7f4b391a580f50f466989e70f4d
# pylint: disable=missing-docstring # pylint: disable=redefined-outer-name # pylint: disable=unused-argument from lettuce import step, world @step('I click on View Courseware') def i_click_on_view_courseware(step): world.css_click('a.enter-course') @step('I click on the "([^"]*)" tab$') def i_click_on_the_tab(step, tab_text): world.click_link(tab_text) @step('I click the "([^"]*)" button$') def i_click_on_the_button(step, data_attr): world.click_button(data_attr) @step('I click on the "([^"]*)" link$') def i_click_on_the_link(step, link_text): world.click_link(link_text) @step('I visit the courseware URL$') def i_visit_the_course_info_url(step): world.visit('/courses/MITx/6.002x/2012_Fall/courseware') @step(u'I am on the dashboard page$') def i_am_on_the_dashboard_page(step): assert world.is_css_present('section.courses') assert world.url_equals('/dashboard') @step('the "([^"]*)" tab is active$') def the_tab_is_active(step, tab_text): assert world.css_text('.course-tabs a.active') == tab_text @step('the login dialog is visible$') def login_dialog_visible(step): assert world.css_visible('form#login_form.login_form')
ahmedaljazzar/edx-platform
lms/djangoapps/courseware/features/courseware_common.py
Python
agpl-3.0
1,186
[ "VisIt" ]
fa22309df3dec9b4e7972f123b5c92982a136006c5651844903ba66cd58fe79a
## # Copyright 2009-2013 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://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/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 Ferret, 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) @author: George Fanourgakis (The Cyprus Institute) """ import os,re,fileinput,sys import easybuild.tools.toolchain as toolchain from easybuild.easyblocks.generic.configuremake import ConfigureMake from easybuild.tools.filetools import run_cmd from easybuild.tools.modules import get_software_root class EB_Ferret(ConfigureMake): """Support for building/installing Ferret.""" def configure_step(self): """Configure Ferret build.""" buildtype = "x86_64-linux" try: os.chdir('FERRET') except OSError, err: self.log.error("Failed to change to FERRET dir: %s" % err) deps = ['HDF5', 'netCDF', 'Java'] for name in deps: if not get_software_root(name): self.log.error("%s module not loaded?" % name) fn = "site_specific.mk" for line in fileinput.input(fn, inplace=1, backup='.orig'): line = re.sub(r"^BUILDTYPE\s*=.*", "BUILDTYPE = %s" % buildtype, line) line = re.sub(r"^INSTALL_FER_DIR =.*", "INSTALL_FER_DIR = %s" % self.installdir, line) for name in deps: line = re.sub(r"^(%s.*DIR\s*)=.*" % name.upper(), r"\1 = %s" % get_software_root(name), line) sys.stdout.write(line) comp_vars = { 'CC':'CC', 'CFLAGS':'CFLAGS', 'CPPFLAGS':'CPPFLAGS', 'FC':'F77', } fn = 'xgks/CUSTOMIZE.%s' % buildtype for line in fileinput.input(fn, inplace=1, backup='.orig'): for x,y in comp_vars.items(): line = re.sub(r"^(%s\s*)=.*" % x, r"\1=%s" % os.getenv(y), line) line = re.sub(r"^(FFLAGS\s*=').*-m64 (.*)", r"\1%s \2" % os.getenv('FFLAGS'), line) line = re.sub(r"^(LD_X11\s*)=.*", r"\1='-L/usr/lib64/X11 -lX11'", line) sys.stdout.write(line) comp_vars = { 'CC':'CC', 'CXX':'CXX', 'F77':'F77', 'FC':'F77', } fns = [ 'fer/platform_specific_flags.mk.%s' % buildtype, 'ppl/platform_specific_flags.mk.%s' % buildtype, 'external_functions/ef_utility/platform_specific_flags.mk.%s' % buildtype, ] for fn in fns: for line in fileinput.input(fn, inplace=1, backup='.orig'): for x,y in comp_vars.items(): line = re.sub(r"^(\s*%s\s*)=.*" % x, r"\1 = %s" % os.getenv(y), line) if self.toolchain.comp_family() == toolchain.INTELCOMP: line = re.sub(r"^(\s*LD\s*)=.*", r"\1 = %s -nofor-main" % os.getenv("F77"), line) for x in ["CFLAGS", "FFLAGS"]: line = re.sub(r"^(\s*%s\s*=\s*\$\(CPP_FLAGS\)).*\\" % x, r"\1 %s \\" % os.getenv(x), line) sys.stdout.write(line) def sanity_check_step(self): """Custom sanity check for Ferret.""" custom_paths = { 'files': ["bin/ferret_v%s" % self.version], 'dirs': [], } super(EB_Ferret, self).sanity_check_step(custom_paths=custom_paths)
geimer/easybuild-easyblocks
easybuild/easyblocks/f/ferret.py
Python
gpl-2.0
4,526
[ "NetCDF" ]
2994996810edb343a00c361ebc3451de59ab67e41636c7dea2582e4e6439a065
# -*- coding: utf-8 -*- from os.path import dirname, join import unilangs.bcp47.parser as parser from unittest import TestCase from unilangs.bcp47.parser import ( parse_code, InvalidLanguageCodeException, MalformedLanguageCodeException ) class BCP47ParserTest(TestCase): def assertMalformed(self, code): return self.assertRaises(MalformedLanguageCodeException, lambda: parse_code(code)) def assertInvalid(self, code): return self.assertRaises(InvalidLanguageCodeException, lambda: parse_code(code)) def assertTagDesc(self, subtag_dict, tag, desc): self.assertEqual(subtag_dict['subtag'].lower(), tag) self.assertEqual(subtag_dict['description'][0], desc) def assertNil(self, language_dict, fields): for f in fields: val = language_dict[f] if f == 'variants': self.assertEqual(val, []) elif f == 'extensions': self.assertEqual(val, {}) else: self.assertIsNone(val) def test_grandfathered(self): p = parser._parse_code('i-klingon') self.assertEqual(p['grandfathered']['tag'], 'i-klingon') self.assertEqual(p['grandfathered']['description'][0], 'Klingon') self.assertNil(p, ['language', 'extlang', 'script', 'region', 'variants', 'extensions']) p = parser._parse_code('i-navajo') self.assertEqual(p['grandfathered']['tag'], 'i-navajo') self.assertEqual(p['grandfathered']['description'][0], 'Navajo') self.assertNil(p, ['language', 'extlang', 'script', 'region', 'variants', 'extensions']) p = parser._parse_code('art-lojban') self.assertEqual(p['grandfathered']['tag'], 'art-lojban') self.assertEqual(p['grandfathered']['description'][0], 'Lojban') self.assertNil(p, ['language', 'extlang', 'script', 'region', 'variants', 'extensions']) def test_bare_language(self): # Bare, simple language codes should parse fine. p = parse_code('en') self.assertTagDesc(p['language'], 'en', 'English') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('de') self.assertTagDesc(p['language'], 'de', 'German') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) # Language codes are case-insensitive. self.assertEqual(parse_code('en'), parse_code('EN')) self.assertEqual(parse_code('en'), parse_code('eN')) # Invalid languages should throw errors. self.assertMalformed('cheese') self.assertMalformed('dogs') def test_language_script(self): # Languages with scripts should parse fine. p = parse_code('zh-Hans') self.assertTagDesc(p['language'], 'zh', 'Chinese') self.assertTagDesc(p['script'], 'hans', 'Han (Simplified variant)') self.assertNil(p, ['extlang', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('zh-HANT') self.assertTagDesc(p['language'], 'zh', 'Chinese') self.assertTagDesc(p['script'], 'hant', 'Han (Traditional variant)') self.assertNil(p, ['extlang', 'region', 'variants', 'extensions', 'grandfathered']) # Scripts cannot stand without a language. self.assertMalformed('Cyrl') self.assertMalformed('Hant') # Invalid languages are still invalid, even with a script. self.assertMalformed('kitties-Hant') # Invalid scripts are invalid. self.assertMalformed('zh-Hannt') def test_language_region(self): # Language with region codes should be fine. p = parse_code('en-us') self.assertTagDesc(p['language'], 'en', 'English') self.assertTagDesc(p['region'], 'us', 'United States') self.assertNil(p, ['extlang', 'script', 'variants', 'extensions', 'grandfathered']) p = parse_code('en-gb') self.assertTagDesc(p['language'], 'en', 'English') self.assertTagDesc(p['region'], 'gb', 'United Kingdom') self.assertNil(p, ['extlang', 'script', 'variants', 'extensions', 'grandfathered']) p = parse_code('es-419') self.assertTagDesc(p['language'], 'es', 'Spanish') self.assertTagDesc(p['region'], '419', 'Latin America and the Caribbean') self.assertNil(p, ['extlang', 'script', 'variants', 'extensions', 'grandfathered']) # Regions cannot be given without a language. self.assertMalformed('419') self.assertMalformed('gb') # Invalid languages are still invalid, even with a region. self.assertMalformed('cheese-gb') # Invalid regions are invalid. self.assertMalformed('en-murica') def test_language_script_region(self): p = parse_code('en-Arab-us') self.assertTagDesc(p['language'], 'en', 'English') self.assertTagDesc(p['script'], 'arab', 'Arabic') self.assertTagDesc(p['region'], 'us', 'United States') self.assertNil(p, ['extlang', 'variants', 'extensions', 'grandfathered']) p = parse_code('sr-Cyrl-RS') self.assertTagDesc(p['language'], 'sr', 'Serbian') self.assertTagDesc(p['script'], 'cyrl', 'Cyrillic') self.assertTagDesc(p['region'], 'rs', 'Serbia') self.assertNil(p, ['extlang', 'variants', 'extensions', 'grandfathered']) # Scripts and regions still require a language. self.assertMalformed('Latn-us') # Invalid language codes, scripts, and regions don't work. self.assertMalformed('minecraft-Latn-us') self.assertMalformed('en-cursive-us') self.assertMalformed('en-Latn-murica') def test_language_variants(self): # p = parse_code('sl-rozaj') # self.assertTagDesc(p['language'], 'sl', 'Slovenian') # self.assertTagDesc(p['variants'][0], 'rozaj', 'Resian') # self.assertNil(p, ['extlang', 'script', 'region', 'extensions', # 'grandfathered']) p = parse_code('sl-rozaj-biske-1994') self.assertTagDesc(p['language'], 'sl', 'Slovenian') self.assertTagDesc(p['variants'][0], 'rozaj', 'Resian') self.assertTagDesc(p['variants'][1], 'biske', 'The San Giorgio dialect of Resian') self.assertTagDesc(p['variants'][2], '1994', 'Standardized Resian orthography') self.assertNil(p, ['extlang', 'script', 'region', 'extensions', 'grandfathered']) # Variants still require a language. self.assertMalformed('rozaj') self.assertMalformed('rozaj-biske') # Invalid variants don't work. self.assertMalformed('sl-rozajbad') def test_language_region_variants(self): p = parse_code('de-CH-1901') self.assertTagDesc(p['language'], 'de', 'German') self.assertTagDesc(p['region'], 'ch', 'Switzerland') self.assertTagDesc(p['variants'][0], '1901', 'Traditional German orthography') self.assertNil(p, ['extlang', 'script', 'extensions', 'grandfathered']) p = parse_code('sl-it-nedis') self.assertTagDesc(p['language'], 'sl', 'Slovenian') self.assertTagDesc(p['region'], 'it', 'Italy') self.assertTagDesc(p['variants'][0], 'nedis', 'Natisone dialect') self.assertNil(p, ['extlang', 'script', 'extensions', 'grandfathered']) p = parse_code('fr-419-1694acad') self.assertTagDesc(p['language'], 'fr', 'French') self.assertTagDesc(p['region'], '419', 'Latin America and the Caribbean') self.assertTagDesc(p['variants'][0], '1694acad', 'Early Modern French') self.assertNil(p, ['extlang', 'script', 'extensions', 'grandfathered']) self.assertMalformed('419-1694acad') self.assertMalformed('fr-2345-nedis') self.assertMalformed('fr-ca-01010101') def test_language_script_region_variants(self): p = parse_code('hy-Latn-IT-arevela') self.assertTagDesc(p['language'], 'hy', 'Armenian') self.assertTagDesc(p['script'], 'latn', 'Latin') self.assertTagDesc(p['region'], 'it', 'Italy') self.assertTagDesc(p['variants'][0], 'arevela', 'Eastern Armenian') self.assertNil(p, ['extlang', 'extensions', 'grandfathered']) self.assertMalformed('Latn-IT-arevela') self.assertMalformed('hy-invalid-IT-arevela') self.assertMalformed('hy-Latn-invalid-arevela') self.assertMalformed('hy-Latn-IT-invalid') def test_language_extlang(self): p = parser._parse_code('zh-cmn-Hans-CN') self.assertTagDesc(p['language'], 'zh', 'Chinese') self.assertTagDesc(p['extlang'], 'cmn', 'Mandarin Chinese') self.assertTagDesc(p['script'], 'hans', 'Han (Simplified variant)') self.assertTagDesc(p['region'], 'cn', 'China') self.assertNil(p, ['variants', 'extensions', 'grandfathered']) p = parser._parse_code('zh-yue-HK') self.assertTagDesc(p['language'], 'zh', 'Chinese') self.assertTagDesc(p['extlang'], 'yue', 'Yue Chinese') self.assertTagDesc(p['region'], 'hk', 'Hong Kong') self.assertNil(p, ['script', 'variants', 'extensions', 'grandfathered']) p = parser._parse_code('sgn-ase') self.assertTagDesc(p['language'], 'sgn', 'Sign languages') self.assertTagDesc(p['extlang'], 'ase', 'American Sign Language') self.assertNil(p, ['script', 'region', 'variants', 'extensions', 'grandfathered']) self.assertMalformed('zh-invalid-Hans-CN') self.assertMalformed('zh-cmn-invalid-CN') self.assertMalformed('zh-cmn-Hans-invalid') def test_extensions(self): p = parse_code('x-cheese') self.assertEqual(p['extensions'], {'x': ['cheese']}) self.assertNil(p, ['language', 'extlang', 'script', 'region', 'variants', 'grandfathered']) p = parse_code('x-cheese-and-crackers') self.assertEqual(p['extensions'], {'x': ['cheese', 'and', 'crackers']}) self.assertNil(p, ['language', 'extlang', 'script', 'region', 'variants', 'grandfathered']) p = parse_code('fr-u-ham-and-swiss') self.assertTagDesc(p['language'], 'fr', 'French') self.assertEqual(p['extensions'], {'u': ['ham', 'and', 'swiss']}) self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'grandfathered']) p = parse_code('hy-Latn-IT-arevela-x-phonebook-a-foo-b-bar-baz') self.assertTagDesc(p['language'], 'hy', 'Armenian') self.assertTagDesc(p['script'], 'latn', 'Latin') self.assertTagDesc(p['region'], 'it', 'Italy') self.assertTagDesc(p['variants'][0], 'arevela', 'Eastern Armenian') self.assertEqual(p['extensions'], {'x': ['phonebook'], 'a': ['foo'], 'b': ['bar', 'baz']}) self.assertNil(p, ['extlang', 'grandfathered']) # Extensions have to contain data. self.assertMalformed('x-') self.assertMalformed('x-x-foo') self.assertMalformed('x-a-foo') self.assertMalformed('x-foo-a') self.assertMalformed('x--eggs') self.assertMalformed('x-egg--dog') self.assertMalformed('x-egg-dog-') # Private use extensions can stand alone, but others cannot. self.assertMalformed('a-foo') self.assertMalformed('u-bar') self.assertMalformed('u-bar-x-baz') # According to the spec, I *think* this should be invalid, but I'm not # 100% sure so we'll accept it for now. # self.assertMalformed('x-foo-a-bar') def test_invalid(self): """Test some malformed tags to make sure they don't parse.""" # Two regions. self.assertMalformed('de-419-DE') # Starting with a non-x singleton. self.assertMalformed('a-DE') # Bad dashes. self.assertMalformed('en--us') self.assertMalformed('en-us-') # Garbage. self.assertMalformed('en-us,') self.assertMalformed('en us') # Duplicate extension singleton tags. self.assertMalformed('ar-a-aaa-b-bbb-a-ccc') self.assertMalformed('en-us-a-123-b-bbb-a-ccc') def test_youtube(self): """Test a bunch of language codes YouTube uses. This should give us a nice variety of test cases. """ with open(join(dirname(__file__), 'youtube_languages.txt')) as f: for code in f: # For some reason youtube uses underscores in some of its codes. # We'll just strip them out here -- users of the library can do # sanitation stuff like this themselves. code = code.strip() code = code.replace('_', '-') self.assertIsNotNone(parse_code(code)) def test_normalization_grandfathered(self): p = parse_code('i-navajo') self.assertTagDesc(p['language'], 'nv', 'Navajo') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('art-lojban') self.assertTagDesc(p['language'], 'jbo', 'Lojban') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) def test_normalization_extlangs(self): p = parse_code('sgn-ase') self.assertTagDesc(p['language'], 'ase', 'American Sign Language') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('ar-abh') self.assertTagDesc(p['language'], 'abh', 'Tajiki Arabic') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) def test_normalization_languages(self): p = parse_code('ji-Latn') self.assertTagDesc(p['language'], 'yi', 'Yiddish') self.assertTagDesc(p['script'], 'latn', 'Latin') self.assertNil(p, ['extlang', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('iw-u-foo-bar') self.assertTagDesc(p['language'], 'he', 'Hebrew') self.assertEqual(p['extensions'], {'u': ['foo', 'bar']}) self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'grandfathered']) def test_normalization_suppress_script(self): p = parse_code('en-Latn') self.assertTagDesc(p['language'], 'en', 'English') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('is-Latn-IS-x-puffins') self.assertTagDesc(p['language'], 'is', 'Icelandic') self.assertTagDesc(p['region'], 'is', 'Iceland') self.assertEqual(p['extensions'], {'x': ['puffins']}) self.assertNil(p, ['extlang', 'script', 'variants', 'grandfathered']) p = parse_code('ja-Latn') self.assertTagDesc(p['language'], 'ja', 'Japanese') self.assertTagDesc(p['script'], 'latn', 'Latin') self.assertNil(p, ['extlang', 'region', 'variants', 'extensions', 'grandfathered']) def test_normalization_redundant(self): # These aren't special cases -- they're just provided in the subtag # registry as examples for god knows why. p = parse_code('zh-gan') self.assertTagDesc(p['language'], 'gan', 'Gan Chinese') self.assertNil(p, ['extlang', 'script', 'region', 'variants', 'extensions', 'grandfathered']) p = parse_code('zh-cmn-Hans') self.assertTagDesc(p['language'], 'cmn', 'Mandarin Chinese') self.assertTagDesc(p['script'], 'hans', 'Han (Simplified variant)') self.assertNil(p, ['extlang', 'region', 'variants', 'extensions', 'grandfathered']) def test_extlang_prefix_validation(self): self.assertInvalid('en-ase') self.assertInvalid('is-acy-ar') self.assertInvalid('jax-jax') def test_variant_prefixes_validation(self): self.assertInvalid('en-ase') self.assertInvalid('is-acy-ar') self.assertInvalid('jax-jax') # solba has the following prefix: # Prefix: sl-rozaj self.assertInvalid('sl-solba') self.assertIsNotNone(parse_code('sl-solba-rozaj')) self.assertIsNotNone(parse_code('sl-rozaj-solba')) # 1994 has the following prefixes: # Prefix: sl-rozaj # Prefix: sl-rozaj-biske # Prefix: sl-rozaj-njiva # Prefix: sl-rozaj-osojs # Prefix: sl-rozaj-solba self.assertInvalid('sl-1994') self.assertInvalid('sl-1994-solba') self.assertIsNotNone(parse_code('sl-1994-rozaj')) self.assertIsNotNone(parse_code('sl-1994-solba-rozaj')) self.assertIsNotNone(parse_code('sl-solba-1994-rozaj')) self.assertIsNotNone(parse_code('sl-solba-rozaj-1994')) self.assertIsNotNone(parse_code('sl-rozaj-solba-1994'))
pculture/unilangs
unilangs/tests/test_bcp47_parsing.py
Python
mit
17,603
[ "ASE" ]
5bf1785f99f2f28d6c02f4e70ab5d8cfc00492b8307661707b80066a6d074104
import os import tempfile import numpy as np from noseperf.testcases import PerformanceTest #from mdtraj import dcd, binpos, trr, netcdf, hdf5 from mdtraj import (XTCTrajectoryFile, TRRTrajectoryFile, DCDTrajectoryFile, BINPOSTrajectoryFile, NetCDFTrajectoryFile, HDF5TrajectoryFile) ###################################################### # Base class: handles setting up a temp file and array ###################################################### class WithTemp(PerformanceTest): n_frames = 10000 n_atoms = 100 def setUp(self): self.xyz = np.random.randn(self.n_frames, self.n_atoms, 3).astype(np.float32) self.fn = tempfile.mkstemp()[1] def tearDown(self): os.unlink(self.fn) ######################################## # Tests ######################################## class TestXTCWriter(WithTemp): def test(self): "Test the write speed of the XTC code (10000 frames, 100 atoms)" with XTCTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) class TestXTCRead(WithTemp): def setUp(self): super(TestXTCRead, self).setUp() with XTCTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) def test(self): "Test the read speed of the XTC code (10000 frames, 100 atoms)" with XTCTrajectoryFile(self.fn) as f: f.read() class TestDCDWrite(WithTemp): def test(self): "Test the write speed of the DCD code (10000 frames, 100 atoms)" with DCDTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) class TestDCDRead(WithTemp): def setUp(self): super(TestDCDRead, self).setUp() with DCDTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) def test(self): "Test the read speed of the DCD code (10000 frames, 100 atoms)" with DCDTrajectoryFile(self.fn) as f: f.read() class TestBINPOSWrite(WithTemp): def test(self): "Test the write speed of the BINPOS code (10000 frames, 100 atoms)" with BINPOSTrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) class TestBINPOSRead(WithTemp): def setUp(self): super(TestBINPOSRead, self).setUp() with BINPOSTrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) def test(self): "Test the read speed of the BINPOS code (10000 frames, 100 atoms)" with BINPOSTrajectoryFile(self.fn) as f: xyz = f.read() class TestTRRWriter(WithTemp): def test(self): "Test the write speed of the TRR code (10000 frames, 100 atoms)" with TRRTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) class TestTRRRead(WithTemp): def setUp(self): super(TestTRRRead, self).setUp() with TRRTrajectoryFile(self.fn, 'w') as f: f.write(xyz=self.xyz) def test(self): "Test the read speed of the TRR code (10000 frames, 100 atoms)" with TRRTrajectoryFile(self.fn) as f: f.read() class TestNetCDFWrite(WithTemp): def test(self): "Test the write speed of the NetCDF code (10000 frames, 100 atoms)" with NetCDFTrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) class TestNetCDFRead(WithTemp): def setUp(self): super(TestNetCDFRead, self).setUp() with NetCDFTrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) def test(self): "Test the read speed of the NetCDF code (10000 frames, 100 atoms)" with NetCDFTrajectoryFile(self.fn) as f: f.read() class TestHDF5Write(WithTemp): def test(self): "Test the write speed of the hdf5 code (10000 frames, 100 atoms)" with HDF5TrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) class TestHDF5Read(WithTemp): def setUp(self): super(TestHDF5Read, self).setUp() with HDF5TrajectoryFile(self.fn, 'w', force_overwrite=True) as f: f.write(self.xyz) def test(self): "Test the read speed of the hdf5 code (10000 frames, 100 atoms)" with HDF5TrajectoryFile(self.fn) as f: f.read()
marscher/mdtraj
MDTraj/tests/performance/test_readwrite.py
Python
lgpl-2.1
4,297
[ "MDTraj", "NetCDF" ]
6194538ca8c931744d9ef21fed17dd779cd372808aa1841c21070a4b6a00f8b1
######################################################################## # $Id$ ######################################################################## __RCSID__ = "$Id$" from DIRAC import S_OK, S_ERROR, gLogger from DIRAC.DataManagementSystem.DB.FileCatalogComponents.FileManagerBase import FileManagerBase from DIRAC.Core.Utilities.List import stringListToString, \ intListToString, \ breakListIntoChunks import datetime import os from types import ListType, TupleType, StringTypes # The logic of some methods is basically a copy/paste from the FileManager class, # so I could have inherited from it. However, I did not want to depend on it class FileManagerPs( FileManagerBase ): def __init__(self, database = None ): super( FileManagerPs, self ).__init__( database ) ###################################################### # # The all important _findFiles and _getDirectoryFiles methods # def _findFiles( self, lfns, metadata = ['FileID'], allStatus = False, connection = False ): """ Returns the information for the given lfns The logic works nicely in the FileManager, so I pretty much copied it. :param lfns: list of lfns :param metadata: list of params that we want to get for each lfn :param allStatus: consider all file status or only those defined in db.visibleFileStatus :return successful/failed convention. successful is a dict < lfn : dict of metadata > """ connection = self._getConnection( connection ) dirDict = self._getFileDirectories( lfns ) result = self.db.dtree.findDirs( dirDict.keys() ) if not result['OK']: return result directoryIDs = result['Value'] failed = {} successful = {} for dirPath in directoryIDs: fileNames = dirDict[dirPath] res = self._getDirectoryFiles( directoryIDs[dirPath], fileNames, metadata, allStatus = allStatus, connection = connection ) for fileName, fileDict in res.get( 'Value', {} ).items(): fname = os.path.join( dirPath, fileName ) successful[fname] = fileDict # The lfns that are not in successful nor failed don't exist for failedLfn in ( set( lfns ) - set( successful ) ): failed.setdefault( failedLfn, "No such file or directory" ) return S_OK( {"Successful":successful, "Failed":failed} ) def _findFileIDs( self, lfns, connection = False ): """ Find lfn <-> FileID correspondence """ connection = self._getConnection(connection) failed = {} successful = {} # If there is only one lfn, we might as well make a direct query if len(lfns) == 1: lfn = list( lfns )[0] # if lfns is a dict, list(lfns) returns lfns.keys() pathPart, filePart = os.path.split( lfn ) result = self.db.executeStoredProcedure( 'ps_get_file_id_from_lfn', ( pathPart, filePart, 'ret1' ), outputIds = [2] ) if not result['OK']: return result fileId = result['Value'][0] if not fileId: failed[lfn] = "No such file" else: successful[lfn] = fileId else: # We separate the files by directory filesInDirDict = self._getFileDirectories( lfns ) # We get the directory ids result = self.db.dtree.findDirs( filesInDirDict.keys() ) if not result['OK']: return result directoryPathToIds = result['Value'] # For each directory, we get the file ids of the files we want for dirPath in directoryPathToIds: fileNames = filesInDirDict[dirPath] dirID = directoryPathToIds[dirPath] formatedFileNames = stringListToString( fileNames ) result = self.db.executeStoredProcedureWithCursor( 'ps_get_file_ids_from_dir_id', ( dirID, formatedFileNames ) ) if not result['OK']: return result for fileID, fileName in result['Value']: fname = os.path.join( dirPath, fileName ) successful[fname] = fileID # The lfns that are not in successful dont exist for failedLfn in ( set( lfns ) - set( successful ) ): failed[failedLfn] = "No such file" return S_OK({"Successful":successful,"Failed":failed}) def _getDirectoryFiles(self,dirID,fileNames,metadata_input,allStatus=False,connection=False): """ For a given directory, and eventually given file, returns all the desired metadata :param dirID : directory ID :param filenames : the list of filenames, or [] :param metadata_input: list of desired metadata. It can be anything from (FileName, DirID, FileID, Size, UID, Owner, GID, OwnerGroup, Status, GUID, Checksum, ChecksumType, Type, CreationDate, ModificationDate, Mode) :param allStatus : if False, only displays the files whose status is in db.visibleFileStatus :returns S_OK(files), where files is a dictionary indexed on filename, and values are dictionary of metadata """ connection = self._getConnection( connection ) metadata = list( metadata_input ) if "UID" in metadata: metadata.append( "Owner" ) if "GID" in metadata: metadata.append( "OwnerGroup" ) if "FileID" not in metadata: metadata.append( "FileID" ) # Format the filenames and status to be used in a IN clause in the sotred procedure formatedFileNames = stringListToString( fileNames ) fStatus = stringListToString( self.db.visibleFileStatus ) specificFiles = True if len( fileNames ) else False result = self.db.executeStoredProcedureWithCursor( 'ps_get_all_info_for_files_in_dir', ( dirID, specificFiles, formatedFileNames, allStatus, fStatus ) ) if not result['OK']: return result fieldNames = ["FileName", "DirID", "FileID", "Size", "UID", "Owner", "GID", "OwnerGroup", "Status", "GUID", "Checksum", "ChecksumType", "Type", "CreationDate", "ModificationDate", "Mode"] rows = result['Value'] files = {} for row in rows: rowDict = dict( zip( fieldNames, row ) ) fileName = rowDict['FileName'] # Returns only the required metadata files[fileName] = dict( ( key, rowDict.get( key, "Unknown metadata field" ) ) for key in metadata ) return S_OK( files ) def _getFileMetadataByID( self, fileIDs, connection=False ): """ Get standard file metadata for a list of files specified by FileID :param fileIDS : list of file Ids :returns S_OK(files), where files is a dictionary indexed on fileID and the values dictionaries containing the following info: ["FileID", "Size", "UID", "GID", "s.Status", "GUID", "CreationDate"] """ # Format the filenames and status to be used in a IN clause in the sotred procedure formatedFileIds = intListToString( fileIDs ) result = self.db.executeStoredProcedureWithCursor( 'ps_get_all_info_for_file_ids', ( formatedFileIds, ) ) if not result['OK']: return result rows = result['Value'] fieldNames = ["FileID", "Size", "UID", "GID", "s.Status", "GUID", "CreationDate"] resultDict = {} for row in rows: rowDict = dict( zip( fieldNames, row ) ) rowDict["Size"] = int( rowDict["Size"] ) rowDict["UID"] = int( rowDict["UID"] ) rowDict["GID"] = int( rowDict["GID"] ) resultDict[rowDict["FileID"]] = rowDict return S_OK( resultDict ) def __insertMultipleFiles ( self, allFileValues, wantedLfns ): """ Insert multiple files in one query. However, if there is a problem with one file, all the query is rolled back. :param allFileValues : dictionary of tuple with all the information about possibly more files than we want to insert :param wantedLfns : list of lfn that we want to insert """ fileValuesStrings = [] fileDescStrings = [] for lfn in wantedLfns: dirID, size, s_uid, s_gid, statusID, fileName, guid, checksum, checksumtype, mode = allFileValues[lfn] utcNow = datetime.datetime.utcnow().replace( microsecond = 0 ) fileValuesStrings.append( "(%s, %s, %s, %s, %s, '%s', '%s', '%s', '%s', '%s', '%s', %s)" % ( dirID, size, s_uid, s_gid, statusID, fileName, guid, checksum, checksumtype, utcNow, utcNow, mode ) ) fileDescStrings.append( "(DirID = %s AND FileName = '%s')" % ( dirID, fileName ) ) fileValuesStr = ",".join( fileValuesStrings ) fileDescStr = " OR ".join( fileDescStrings ) result = self.db.executeStoredProcedureWithCursor( 'ps_insert_multiple_file', ( fileValuesStr, fileDescStr ) ) return result def __chunks( self, l, n ): """ Yield successive n-sized chunks from l. """ for i in xrange( 0, len( l ), n ): yield l[i:i + n] def _insertFiles( self, lfns, uid, gid, connection = False ): """ Insert new files. lfns is a dictionary indexed on lfn, the values are mandatory: DirID, Size, Checksum, GUID optional : Owner (dict with username and group), ChecksumType (Adler32 by default), Mode (db.umask by default) :param lfns : lfns and info to insert :param uid : user id, overwriten by Owner['username'] if defined :param gid : user id, overwriten by Owner['group'] if defined """ connection = self._getConnection(connection) failed = {} successful = {} res = self._getStatusInt( 'AprioriGood', connection = connection ) if res['OK']: statusID = res['Value'] else: return res lfnsToRetry = [] fileValues = {} fileDesc = {} # Prepare each file separately for lfn in lfns: # Get all the info fileInfo = lfns[lfn] dirID = fileInfo['DirID'] fileName = os.path.basename( lfn ) size = fileInfo['Size'] ownerDict = fileInfo.get( 'Owner', None ) checksum = fileInfo['Checksum'] checksumtype = fileInfo.get( 'ChecksumType', 'Adler32' ) guid = fileInfo['GUID'] mode = fileInfo.get( 'Mode', self.db.umask ) s_uid = uid s_gid = gid # overwrite the s_uid and s_gid if defined in the lfn info if ownerDict: result = self.db.ugManager.getUserAndGroupID( ownerDict ) if result['OK']: s_uid, s_gid = result['Value'] fileValues[lfn] = ( dirID, size, s_uid, s_gid, statusID, fileName, guid, checksum, checksumtype, mode ) fileDesc[( dirID, fileName )] = lfn chunkSize = 200 allChunks = list( self.__chunks( lfns.keys(), chunkSize ) ) for lfnChunk in allChunks: result = self.__insertMultipleFiles( fileValues, lfnChunk ) if result['OK']: allIds = result['Value'] for dirId, fileName, fileID in allIds: lfn = fileDesc[ ( dirId, fileName ) ] successful[lfn] = lfns[lfn] successful[lfn]['FileID'] = fileID else: lfnsToRetry.extend( lfnChunk ) # If we are here, that means that the multiple insert failed, so we do one by one for lfn in lfnsToRetry: dirID, size, s_uid, s_gid, statusID, fileName, guid, checksum, checksumtype, mode = fileValues[lfn] # insert result = self.db.executeStoredProcedureWithCursor( 'ps_insert_file', ( dirID, size, s_uid, s_gid, statusID, fileName, guid, checksum, checksumtype, mode ) ) if not result['OK']: failed[lfn] = result['Message'] else: fileID = result['Value'][0][0] successful[lfn] = lfns[lfn] successful[lfn]['FileID'] = fileID return S_OK( { 'Successful' : successful, 'Failed' : failed} ) def _getFileIDFromGUID( self, guids, connection = False ): """ Returns the file ids from list of guids :param guids : list of guid :returns dictionary < guid : fileId > """ connection = self._getConnection(connection) if not guids: return S_OK({}) if type( guids ) not in [ListType, TupleType]: guids = [guids] # formatedGuids = ','.join( [ '"%s"' % guid for guid in guids ] ) formatedGuids = stringListToString( guids ) result = self.db.executeStoredProcedureWithCursor( 'ps_get_file_ids_from_guids', ( formatedGuids, ) ) if not result['OK']: return result guidDict = dict( ( guid, fileID ) for guid, fileID in result['Value'] ) return S_OK(guidDict) def getLFNForGUID( self, guids, connection = False ): """ Returns the lfns matching given guids""" connection = self._getConnection( connection ) if not guids: return S_OK( {} ) if type( guids ) not in [ListType, TupleType]: guids = [guids] formatedGuids = stringListToString( guids ) result = self.db.executeStoredProcedureWithCursor( 'ps_get_lfns_from_guids', ( formatedGuids, ) ) if not result['OK']: return result guidDict = dict( ( guid, lfn ) for guid, lfn in result['Value'] ) failedGuid = set( guids ) - set( guidDict ) failed = dict.fromkeys( failedGuid, "GUID does not exist" ) if failedGuid else {} return S_OK( {"Successful" : guidDict, "Failed" : failed} ) ###################################################### # # _deleteFiles related methods # def _deleteFiles( self, fileIDs, connection = False ): """ Delete a list of files and the associated replicas :param fileIDS : list of fileID :returns S_OK() or S_ERROR(msg) """ connection = self._getConnection(connection) replicaPurge = self.__deleteFileReplicas(fileIDs) filePurge = self.__deleteFiles(fileIDs,connection=connection) if not replicaPurge['OK']: return replicaPurge if not filePurge['OK']: return filePurge return S_OK() def __deleteFileReplicas( self, fileIDs, connection = False ): """ Delete all the replicas from the file ids :param fileIDs list of file ids :returns S_OK() or S_ERROR(msg) """ connection = self._getConnection(connection) if not fileIDs: return S_OK() formatedFileIds = intListToString( fileIDs ) result = self.db.executeStoredProcedureWithCursor( 'ps_delete_replicas_from_file_ids', ( formatedFileIds, ) ) if not result['OK']: return result errno, msg = result['Value'][0] if errno: return S_ERROR( msg ) return S_OK() def __deleteFiles(self,fileIDs,connection=False): """ Delete the files from their ids :param fileIDs list of file ids :returns S_OK() or S_ERROR(msg) """ connection = self._getConnection(connection) formatedFileIds = intListToString( fileIDs ) result = self.db.executeStoredProcedureWithCursor( 'ps_delete_files', ( formatedFileIds, ) ) if not result['OK']: return result errno, msg = result['Value'][0] if errno: return S_ERROR( msg ) return S_OK() def __insertMultipleReplicas ( self, allReplicaValues, lfnsChunk ): """ Insert multiple replicas in one query. However, if there is a problem with one replica, all the query is rolled back. :param allReplicaValues : dictionary of tuple with all the information about possibly more replica than we want to insert :param lfnsChunk : list of lfn that we want to insert """ repValuesStrings = [] repDescStrings = [] for lfn in lfnsChunk: fileID, seID, statusID, replicaType, pfn = allReplicaValues[lfn] utcNow = datetime.datetime.utcnow().replace( microsecond = 0 ) repValuesStrings.append( "(%s,%s,'%s','%s','%s','%s','%s')" % ( fileID, seID, statusID, replicaType, utcNow, utcNow, pfn ) ) repDescStrings.append( "(r.FileID = %s AND SEID = %s)" % ( fileID, seID ) ) repValuesStr = ",".join( repValuesStrings ) repDescStr = " OR ".join( repDescStrings ) result = self.db.executeStoredProcedureWithCursor( 'ps_insert_multiple_replica', ( repValuesStr, repDescStr ) ) return result def _insertReplicas( self, lfns, master = False, connection = False ): """ Insert new replicas. lfns is a dictionary with one entry for each file. The keys are lfns, and values are dict with mandatory attributes : FileID, SE (the name), PFN :param lfns: lfns and info to insert :param master: true if they are master replica, otherwise they will be just 'Replica' :return successful/failed convention, with successful[lfn] = true """ chunkSize = 200 connection = self._getConnection(connection) # Add the files failed = {} successful = {} # Get the status id of AprioriGood res = self._getStatusInt( 'AprioriGood', connection = connection ) if not res['OK']: return res statusID = res['Value'] lfnsToRetry = [] repValues = {} repDesc = {} # treat each file after each other for lfn in lfns.keys(): fileID = lfns[lfn]['FileID'] seName = lfns[lfn]['SE'] if type(seName) in StringTypes: seList = [seName] elif type(seName) == ListType: seList = seName else: return S_ERROR('Illegal type of SE list: %s' % str( type( seName ) ) ) replicaType = 'Master' if master else 'Replica' pfn = lfns[lfn]['PFN'] # treat each replica of a file after the other # (THIS CANNOT WORK... WE ARE ONLY CAPABLE OF DOING ONE REPLICA PER FILE AT THE TIME) for seName in seList: # get the SE id res = self.db.seManager.findSE(seName) if not res['OK']: failed[lfn] = res['Message'] continue seID = res['Value'] # This is incompatible with adding multiple replica at the time for a given file repValues[lfn] = ( fileID, seID, statusID, replicaType, pfn ) repDesc[( fileID, seID )] = lfn allChunks = list( self.__chunks( lfns.keys(), chunkSize ) ) for lfnChunk in allChunks: result = self.__insertMultipleReplicas( repValues, lfnChunk ) if result['OK']: allIds = result['Value'] for fileId, seId, repId in allIds: lfn = repDesc[ ( fileId, seId ) ] successful[lfn] = True lfns[lfn]['RepID'] = repId else: lfnsToRetry.extend( lfnChunk ) for lfn in lfnsToRetry: fileID, seID, statusID, replicaType, pfn = repValues[lfn] # insert the replica and its info result = self.db.executeStoredProcedureWithCursor( 'ps_insert_replica', ( fileID, seID, statusID, replicaType, pfn ) ) if not result['OK']: failed[lfn] = result['Message'] else: replicaID = result['Value'][0][0] lfns[lfn]['RepID'] = replicaID successful[lfn] = True return S_OK({'Successful':successful,'Failed':failed}) def _getRepIDsForReplica( self, replicaTuples, connection = False ): """ Get the Replica IDs for (fileId, SEID) couples :param repliacTuples : list of (fileId, SEID) couple :returns { fileID : { seID : RepID } } """ connection = self._getConnection(connection) replicaDict = {} for fileID,seID in replicaTuples: result = self.db.executeStoredProcedure( 'ps_get_replica_id', ( fileID, seID, 'repIdOut' ), outputIds = [2] ) if not result['OK']: return result repID = result['Value'][0] # if the replica exists, we add it to the dict if repID: replicaDict.setdefault( fileID, {} ).setdefault( seID, repID ) return S_OK( replicaDict ) ###################################################### # # _deleteReplicas related methods # def _deleteReplicas(self,lfns,connection=False): """ Deletes replicas. The deletion of replicas that do not exist is successful :param lfns : dictinary with lfns as key, and the value is a dict with a mandatory "SE" key, corresponding to the SE name or SE ID :returns successful/failed convention, with successful[lfn] = True """ connection = self._getConnection(connection) failed = {} successful = {} # First we get the fileIds from our lfns res = self._findFiles( lfns.keys(), ['FileID'], connection = connection ) # If the file does not exist we consider the deletion successful for lfn, error in res['Value']['Failed'].items(): if error == 'No such file or directory': successful[lfn] = True else: failed[lfn] = error lfnFileIDDict = res['Value']['Successful'] for lfn,fileDict in lfnFileIDDict.items(): fileID = fileDict['FileID'] # Then we get our StorageElement Id (cached in seManager) se = lfns[lfn]['SE'] # if se is already the se id, findSE will return it res = self.db.seManager.findSE( se ) if not res['OK']: return res seID = res['Value'] # Finally remove the replica result = self.db.executeStoredProcedureWithCursor( 'ps_delete_replica_from_file_and_se_ids', ( fileID, seID ) ) if not result['OK']: failed[lfn] = result['Message'] continue errno, errMsg = result['Value'][0] if errno: failed[lfn] = errMsg else: successful[lfn] = True return S_OK( {"Successful" : successful, "Failed" : failed} ) ###################################################### # # _setReplicaStatus _setReplicaHost _setReplicaParameter methods # _setFileParameter method # def _setReplicaStatus( self, fileID, se, status, connection = False ): """ Set the status of a replica :param fileID : file id :param se : se name or se id :param status : status to be applied :returns S_OK() or S_ERROR(msg) """ if not status in self.db.validReplicaStatus: return S_ERROR( 'Invalid replica status %s' % status ) connection = self._getConnection(connection) res = self._getStatusInt(status,connection=connection) if not res['OK']: return res statusID = res['Value'] # Then we get our StorageElement Id (cached in seManager) res = self.db.seManager.findSE( se ) if not res['OK']: return res seID = res['Value'] result = self.db.executeStoredProcedureWithCursor( 'ps_set_replica_status', ( fileID, seID, statusID ) ) if not result['OK']: return result affected = result['Value'][0][0] # Affected is the number of raws updated if not affected: return S_ERROR( "Replica does not exist" ) else: return S_OK() def _setReplicaHost( self, fileID, se, newSE, connection = False ): """ Move a replica from one SE to another (I don't think this should be called :param fileID : file id :param se : se name or se id of the previous se :param newSE : se name or se id of the new se :returns S_OK() or S_ERROR(msg) """ connection = self._getConnection(connection) # Get the new se id res = self.db.seManager.findSE(newSE) if not res['OK']: return res newSEID = res['Value'] # Get the old se id res = self.db.seManager.findSE( se ) if not res['OK']: return res oldSEID = res['Value'] # update result = self.db.executeStoredProcedureWithCursor( 'ps_set_replica_host', ( fileID, oldSEID, newSEID ) ) if not result['OK']: return result affected = result['Value'][0][0] if not affected: return S_ERROR( "Replica does not exist" ) else: return S_OK() def _setFileParameter( self, fileID, paramName, paramValue, connection = False ): """ Generic method to set a file parameter :param fileID : id of the file :param paramName : the file parameter you want to change It should be one of [ UID, GID, Status, Mode]. However, in case of unexpected parameter, and to stay compatible with the other Manager, there is a manual request done. :param paramValue : the value (raw, or id) to insert :returns S_OK() or S_ERROR """ connection = self._getConnection(connection) # The PS associated with a given parameter psNames = {'UID' : 'ps_set_file_uid', 'GID' : 'ps_set_file_gid', 'Status' : 'ps_set_file_status', 'Mode' : 'ps_set_file_mode', } psName = psNames.get(paramName, None) # If there is an associated procedure, we go for it if psName: result = self.db.executeStoredProcedureWithCursor( psName, ( fileID, paramValue ) ) if not result['OK']: return result _affected = result['Value'][0][0] # If affected = 0, the file does not exist, but who cares... # In case this is a 'new' parameter, we have a failback solution, but we should add a specific ps for it else: req = "UPDATE FC_Files SET %s='%s', ModificationDate=UTC_TIMESTAMP() WHERE FileID IN (%s)"\ % ( paramName, paramValue, intListToString( fileID ) ) return self.db._update( req, connection ) return S_OK() ###################################################### # # _getFileReplicas related methods # def _getFileReplicas( self, fileIDs, fields_input = ['PFN'], allStatus = False, connection = False ): """ Get replicas for the given list of files specified by their fileIDs :param fileIDs : list of file ids :param fields_input : metadata of the Replicas we are interested in :param allStatus : if True, all the Replica statuses will be considered, otherwise, only the db.visibleReplicaStatus :returns S_OK with a dict { fileID : { SE name : dict of metadata } } """ connection = self._getConnection( connection ) fields = list( fields_input ) if 'Status' not in fields: fields.append( 'Status' ) replicas = {} # Format the status to be used in a IN clause in the stored procedure fStatus = stringListToString( self.db.visibleReplicaStatus ) fieldNames = [ "FileID", "SE", "Status", "RepType", "CreationDate", "ModificationDate", "PFN"] for fileID in fileIDs: result = self.db.executeStoredProcedureWithCursor( 'ps_get_all_info_of_replicas', ( fileID, allStatus, fStatus ) ) if not result['OK']: return result rows = result['Value'] if not rows: replicas[fileID] = {} for row in rows: rowDict = dict( zip( fieldNames, row ) ) # Returns only the required metadata se = rowDict["SE"] repForFile = replicas.setdefault( fileID, {} ) repForFile[se] = dict( ( key, rowDict.get( key, "Unknown metadata field" ) ) for key in fields ) return S_OK(replicas) def countFilesInDir( self, dirId ): """ Count how many files there is in a given Directory :param dirID : directory id :returns S_OK(value) or S_ERROR """ result = self.db.executeStoredProcedure( 'ps_count_files_in_dir', ( dirId, 'ret1' ), outputIds = [1] ) if not result['OK']: return result res = S_OK( result['Value'][0] ) return res ######################################################################################################## # # We overwrite some methods from the base class because of the new DB constraints or perf reasons # # Some methods could be inherited in the future if we have perf problems. For example # * setFileGroup # * setFileOwner # * setFileMode # * changePath* # ######################################################################################################## def _updateDirectoryUsage( self, directorySEDict, change, connection = False ): """ This updates the directory usage, but is now done by triggers in the DB""" return S_OK() def _computeStorageUsageOnRemoveFile( self, lfns, connection = False ): """Again nothing to compute, all done by the triggers""" directorySESizeDict = {} return S_OK( directorySESizeDict ) # "REMARQUE : THIS IS STILL TRUE, BUT YOU MIGHT WANT TO CHECK FOR A GIVEN GUID ANYWAY # def _checkUniqueGUID( self, lfns, connection = False ): # """ The GUID unicity is ensured at the DB level, so we will have similar message if the insertion fails""" # # failed = {} # return failed def getDirectoryReplicas( self, dirID, path, allStatus = False, connection = False ): """ This is defined in the FileManagerBase but it relies on the SEManager to get the SE names. It is good practice in software, but since the SE and Replica tables are bound together in the DB, I might as well resolve the name in the query Get the replicas for all the Files in the given Directory :param DirID : ID of the directory :param path : useless :param allStatus : whether all replicas and file status are considered If False, take the visibleFileStatus and visibleReplicaStatus values from the configuration """ # We format the visible file/replica satus so we can give it as argument to the ps # It is used in an IN clause, so it looks like --'"AprioriGood","Trash"'-- # fStatus = ','.join( [ '"%s"' % status for status in self.db.visibleFileStatus ] ) # rStatus = ','.join( [ '"%s"' % status for status in self.db.visibleReplicaStatus ] ) fStatus = stringListToString( self.db.visibleFileStatus ) rStatus = stringListToString( self.db.visibleReplicaStatus ) result = self.db.executeStoredProcedureWithCursor( 'ps_get_replicas_for_files_in_dir', ( dirID, allStatus, fStatus, rStatus ) ) if not result['OK']: return result resultDict = {} for fileName, _fileID, seName, pfn in result['Value']: resultDict.setdefault( fileName, {} ).setdefault( seName, [] ).append( pfn ) return S_OK( resultDict )
coberger/DIRAC
DataManagementSystem/DB/FileCatalogComponents/WithFkAndPs/FileManagerPs.py
Python
gpl-3.0
30,500
[ "DIRAC" ]
c54f9ce19c9840f5f11e49fda2f5ca3ad6e87ce18f5051c68286118bef51a7a8
# -*- coding: utf-8 -*- #!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup import test-for-brian-criswell version = test-for-brian-criswell.__version__ setup( name='test-for-brian-criswell', version=version, author='', author_email='Your email', packages=[ 'test-for-brian-criswell', ], include_package_data=True, install_requires=[ 'Django>=1.6.5', ], zip_safe=False, scripts=['test-for-brian-criswell/manage.py'], )
mikemitr/test-for-brian-criswell
setup.py
Python
bsd-3-clause
569
[ "Brian" ]
a8ff2cd042fbf265792c0b149d94c8a0a2627cf1c65b9554ac11db0445af7d79
#! /usr/bin/env python #David Shean #dshean@gmail.com #This utility will interpolate to fill gaps in both spatial and temporal dimension import os import sys import multiprocessing as mp from datetime import datetime, timedelta import pickle from copy import deepcopy import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import scipy.signal import scipy.interpolate #from sklearn.gaussian_process import GaussianProcess #from scikits import umfpack from scipy.ndimage.interpolation import map_coordinates from pygeotools.lib import iolib from pygeotools.lib import malib from pygeotools.lib import timelib from pygeotools.lib import geolib #This does the interpolation for a particular time for all points defined by x and y coords #Used for parallel interpolation def dto_interp(interpf, x, y, dto): return (dto, interpf(x, y, dto.repeat(x.size)).T) def rangenorm(x, offset=None, scale=None): if offset is None: offset = x.min() if scale is None: scale = x.ptp() return (x.astype(np.float64) - offset)/scale #This repeats the first and last array in the stack with a specified time offset def pad_stack(s, dt_offset=timedelta(365.25)): o = s.ma_stack.shape new_ma_stack = np.ma.vstack((s.ma_stack[0:1], s.ma_stack, s.ma_stack[-1:])) new_date_list = np.ma.hstack((s.date_list[0:1] - dt_offset, s.date_list, s.date_list[-1:] + dt_offset)) new_date_list_o = timelib.dt2o(new_date_list) return new_ma_stack, new_date_list_o def apply_mask(a, m): a[:,m] = np.ma.masked def main(): if len(sys.argv) < 2: sys.exit("Usage: %s stack.npz [mask.tif]" % os.path.basename(sys.argv[0])) #This will attempt to load cached files on disk load_existing = False #Limit spatial interpolation to input mask clip_to_mask = True #This expects a DEMStack object, see pygeotools/lib/malib.py or pygeotools/make_stack.py stack_fn = sys.argv[1] #Expects shp polygon as valid mask, in same projection as input raster mask_fn = sys.argv[2] stack = malib.DEMStack(stack_fn=stack_fn, save=False, trend=True, med=True, stats=True) #Get times of original obs t = stack.date_list_o.data t = t.astype(int) t[0] -= 0.1 t[-1] += 0.1 if clip_to_mask: m = geolib.shp2array(mask_fn, res=stack.res, extent=stack.extent) #Expand mask - hardcoded to 6 km import scipy.ndimage it = int(np.ceil(6000./stack.res)) m = ~(scipy.ndimage.morphology.binary_dilation(~m, iterations=it)) apply_mask(stack.ma_stack, m) #This is used frome here on out test = stack.ma_stack test_ptp = stack.dt_stack_ptp test_source = np.array(stack.source) res = stack.res gt = np.copy(stack.gt) #Probably don't need rull-res stack if True: stride = 2 test = test[:,::stride,::stride] test_ptp = test_ptp[::stride,::stride] res *= stride print("Using a stride of %i (%0.1f m)" % (stride, res)) gt[[1,5]] *= stride print("Orig shape: ", test.shape) #Check to make sure all t have valid data tcount = test.reshape(test.shape[0], test.shape[1]*test.shape[2]).count(axis=1) validt_idx = (tcount > 0).nonzero()[0] test = test[validt_idx] test_source = test_source[validt_idx] t = t[validt_idx] print("New shape: ", test.shape) y, x = (test.count(axis=0) > 1).nonzero() x = x.astype(int) y = y.astype(int) #vm_t = test.reshape(test.shape[0], test.shape[1]*test.shape[2]) vm_t = test[:,y,x] vm_t_flat = vm_t.ravel() idx = ~np.ma.getmaskarray(vm_t_flat) #These are values VM = vm_t_flat[idx] #Determine scaling factors for x and y coords #Should be the same for both xy_scale = max(x.ptp(), y.ptp()) xy_offset = min(x.min(), y.min()) #This scales t to encourage interpolation along the time axis rather than spatial axis t_factor = 16. t_scale = t.ptp()*t_factor t_offset = t.min() xn = rangenorm(x, xy_offset, xy_scale) yn = rangenorm(y, xy_offset, xy_scale) tn = rangenorm(t, t_offset, t_scale) X = np.tile(xn, t.size)[idx] Y = np.tile(yn, t.size)[idx] T = np.repeat(tn, x.size)[idx] #These are coords pts = np.vstack((X,Y,T)).T #Step size in days #ti_dt = 91.3125 #ti_dt = 121.75 ti_dt = 365.25 #Set min and max times for interpolation #ti = np.arange(t.min(), t.max(), ti_dt) ti_min = timelib.dt2o(datetime(2008,1,1)) ti_max = timelib.dt2o(datetime(2015,1,1)) #Interpolate at these times ti = np.arange(ti_min, ti_max, ti_dt) #Annual #ti = timelib.dt2o([datetime(2008,1,1), datetime(2009,1,1), datetime(2010,1,1), datetime(2011,1,1), datetime(2012,1,1), datetime(2013,1,1), datetime(2014,1,1), datetime(2015,1,1)]) tin = rangenorm(ti, t_offset, t_scale) """ #Never got this working efficiently, but preserved for reference #Radial basis function interpolation #Need to normalize to input cube print "Running Rbf interpolation for %i points" % X.size rbfi = scipy.interpolate.Rbf(Xn,Yn,Tn,VM, function='linear', smooth=0.1) #rbfi = scipy.interpolate.Rbf(Xn,Yn,Tn,VM, function='gaussian', smooth=0.000001) #rbfi = scipy.interpolate.Rbf(Xn,Yn,Tn,VM, function='inverse', smooth=0.00001) print "Sampling result at %i points" % xin.size vmi_rbf = rbfi(xin, yin, tin.repeat(x.size)) vmi_rbf_ma[:,y,x] = np.ma.fix_invalid(vmi_rbf.reshape((ti.size, x.shape[0]))) """ #Attempt to load cached interpolation function int_fn = '%s_LinearNDint_%i_%i.pck' % (os.path.splitext(stack_fn)[0], test.shape[1], test.shape[2]) print(int_fn) if load_existing and os.path.exists(int_fn): print("Loading pickled interpolation function: %s" % int_fn) f = open(int_fn, 'rb') linNDint = pickle.load(f) else: #NearestND interpolation (fast) #print "Running NearestND interpolation for %i points" % X.size #NearNDint = scipy.interpolate.NearestNDInterpolator(pts, VM, rescale=True) #LinearND interpolation print("Running LinearND interpolation for %i points" % X.size) #Note: this breaks qhull for lots of input points linNDint = scipy.interpolate.LinearNDInterpolator(pts, VM, rescale=False) print("Saving pickled interpolation function: %s" % int_fn) f = open(int_fn, 'wb') pickle.dump(linNDint, f, protocol=2) f.close() vmi_fn = '%s_%iday.npy' % (os.path.splitext(int_fn)[0], ti_dt) if load_existing and os.path.exists(vmi_fn): print('Loading existing interpolated stack: %s' % vmi_fn) vmi_ma = np.ma.fix_invalid(np.load(vmi_fn)['arr_0']) else: #Once tesselation is complete, sample each timestep in parallel print("Sampling %i points at %i timesteps, %i total" % (x.size, ti.size, x.size*ti.size)) #Prepare array to hold output vmi_ma = np.ma.masked_all((ti.size, test.shape[1], test.shape[2])) """ #This does all points at once #vmi = linNDint(ptsi) #vmi_ma[:,y,x] = np.ma.fix_invalid(vmi.reshape((ti.size, x.shape[0]))) #This does interpolation serially by timestep for n, i in enumerate(ti): print n, i, timelib.o2dt(i) vmi_ma[n,y,x] = linNDint(x, y, i.repeat(x.size)).T """ #Parallel processing pool = mp.Pool(processes=None) results = [pool.apply_async(dto_interp, args=(linNDint, xn, yn, i)) for i in tin] results = [p.get() for p in results] results.sort() for n, r in enumerate(results): t_rescale = r[0]*t_scale + t_offset print(n, t_rescale, timelib.o2dt(t_rescale)) vmi_ma[n,y,x] = r[1] vmi_ma = np.ma.fix_invalid(vmi_ma) print('Saving interpolated stack: %s' % vmi_fn) np.save(vmi_fn, vmi_ma.filled(np.nan)) origt = False if origt: print("Sampling %i points at %i original timesteps" % (x.size, t.size)) vmi_ma_origt = np.ma.masked_all((t.size, test.shape[1], test.shape[2])) #Parallel pool = mp.Pool(processes=None) results = [pool.apply_async(dto_interp, args=(linNDint, x, y, i)) for i in t] results = [p.get() for p in results] results.sort() for n, r in enumerate(results): print(n, r[0], timelib.o2dt(r[0])) vmi_ma_origt[n,y,x] = r[1] vmi_ma_origt = np.ma.fix_invalid(vmi_ma_origt) #print 'Saving interpolated stack: %s' % vmi_fn #np.save(vmi_fn, vmi_ma.filled(np.nan)) #Write out a proper stack, for use by stack_melt and flux gate mass budget if True: out_stack = deepcopy(stack) out_stack.stats = False out_stack.trend = False out_stack.datestack = False out_stack.write_stats = False out_stack.write_trend = False out_stack.write_datestack = False out_stack.ma_stack = vmi_ma out_stack.stack_fn = os.path.splitext(vmi_fn)[0]+'.npz' out_stack.date_list_o = np.ma.array(ti) out_stack.date_list = np.ma.array(timelib.o2dt(ti)) out_fn_list = [timelib.print_dt(i)+'_LinearNDint.tif' for i in out_stack.date_list] out_stack.fn_list = out_fn_list out_stack.error = np.zeros_like(out_stack.date_list_o) out_stack.source = np.repeat('LinearNDint', ti.size) out_stack.gt = gt out_stack.res = res out_stack.savestack() sys.exit() """ #Other interpolation methods #vmi = scipy.interpolate.griddata(pts, VM, ptsi, method='linear', rescale=True) #Kriging #Should explore this more - likely the best option #http://connor-johnson.com/2014/03/20/simple-kriging-in-python/ #http://resources.esri.com/help/9.3/arcgisengine/java/gp_toolref/geoprocessing_with_3d_analyst/using_kriging_in_3d_analyst.htm #PyKrige does moving window Kriging, but only in 2D #https://github.com/bsmurphy/PyKrige/pull/5 #Could do tiled kriging with overlap in parallel #Split along x and y direction, preserve all t #Need to generate semivariogram globally though, then pass to each tile #See malib sliding_window wx = wy = 30 wz = test.shape[0] overlap = 0.5 dwx = dwy = int(overlap*wx) gp_slices = malib.nanfill(test, malib.sliding_window, ws=(wz,wy,wx), ss=(0,dwy,dwx)) vmi_gp_ma = np.ma.masked_all((ti.size, test.shape[1], test.shape[2])) vmi_gp_mse_ma = np.ma.masked_all((ti.size, test.shape[1], test.shape[2])) out = [] for i in gp_slices: y, x = (i.count(axis=0) > 0).nonzero() x = x.astype(int) y = y.astype(int) vm_t = test[:,y,x] vm_t_flat = vm_t.ravel() idx = ~np.ma.getmaskarray(vm_t_flat) #These are values VM = vm_t_flat[idx] #These are coords X = np.tile(x, t.size)[idx] Y = np.tile(y, t.size)[idx] T = np.repeat(t, x.size)[idx] pts = np.vstack((X,Y,T)).T xi = np.tile(x, ti.size) yi = np.tile(y, ti.size) ptsi = np.array((xi, yi, ti.repeat(x.size))).T #gp = GaussianProcess(regr='linear', verbose=True, normalize=True, theta0=0.1, nugget=2) gp = GaussianProcess(regr='linear', verbose=True, normalize=True, nugget=2) gp.fit(pts, VM) vmi_gp, vmi_gp_mse = gp.predict(ptsi, eval_MSE=True) vmi_gp_ma = np.ma.masked_all((ti.size, i.shape[1], i.shape[2])) vmi_gp_ma[:,y,x] = np.array(vmi_gp.reshape((ti.size, x.shape[0]))) vmi_gp_mse_ma = np.ma.masked_all((ti.size, i.shape[1], i.shape[2])) vmi_gp_mse_ma[:,y,x] = np.array(vmi_gp_mse.reshape((ti.size, x.shape[0]))) out.append(vmi_gp_ma) #Now combine intelligently print "Gaussian Process regression" pts2d_vm = vm_t[1] pts2d = np.vstack((x,y))[~(np.ma.getmaskarray(pts2d_vm))].T pts2di = np.vstack((x,y)).T gp = GaussianProcess(regr='linear', verbose=True, normalize=True, theta0=0.1, nugget=1) gp.fit(pts, VM) print "Gaussian Process prediction" vmi_gp, vmi_gp_mse = gp.predict(ptsi, eval_MSE=True) print "Converting to stack" vmi_gp_ma = np.ma.masked_all((ti.size, test.shape[1], test.shape[2])) vmi_gp_ma[:,y,x] = np.array(vmi_gp.reshape((ti.size, x.shape[0]))) vmi_gp_mse_ma = np.ma.masked_all((ti.size, test.shape[1], test.shape[2])) vmi_gp_mse_ma[:,y,x] = np.array(vmi_gp_mse.reshape((ti.size, x.shape[0]))) sigma = np.sqrt(vmi_gp_mse_ma) """ """ #This fills nodata in last timestep with values from previous timestep #Helps Savitzy-Golay filter fill_idx = ~np.ma.getmaskarray(vmi_ma[-1]).nonzero() temp = np.ma.array(vmi_ma[-2]) temp[fill_idx] = vmi_ma[-1][fill_idx] vmi_ma[-1] = temp """ if __name__ == "__main__": main()
dshean/iceflow
iceflow/ndinterp.py
Python
mit
12,920
[ "Gaussian" ]
c992df346ba988b665c955234b80aa7258d1364c8db50684146d25aee766ff08
import unittest as ut from .. import tabular as ta from ....common import RTOL, ATOL, pandas, requires as _requires from ....examples import get_path from ...shapes import Polygon from ....io import geotable as pdio from ... import ops as GIS import numpy as np try: import shapely as shp except ImportError: shp = None PANDAS_EXTINCT = pandas is None SHAPELY_EXTINCT = shp is None @ut.skipIf(PANDAS_EXTINCT or SHAPELY_EXTINCT, 'missing pandas or shapely') class Test_Tabular(ut.TestCase): def setUp(self): import pandas as pd self.columbus = pdio.read_files(get_path('columbus.shp')) grid = [Polygon([(0,0),(0,1),(1,1),(1,0)]), Polygon([(0,1),(0,2),(1,2),(1,1)]), Polygon([(1,2),(2,2),(2,1),(1,1)]), Polygon([(1,1),(2,1),(2,0),(1,0)])] regime = [0,0,1,1] ids = list(range(4)) data = np.array((regime, ids)).T self.exdf = pd.DataFrame(data, columns=['regime', 'ids']) self.exdf['geometry'] = grid @_requires('geopandas') def test_round_trip(self): import geopandas as gpd import pandas as pd geodf = GIS.tabular.to_gdf(self.columbus) self.assertIsInstance(geodf, gpd.GeoDataFrame) new_df = GIS.tabular.to_df(geodf) self.assertIsInstance(new_df, pd.DataFrame) for new, old in zip(new_df.geometry, self.columbus.geometry): self.assertEqual(new, old) def test_spatial_join(self): pass def test_spatial_overlay(self): pass def test_dissolve(self): out = GIS.tabular.dissolve(self.exdf, by='regime') self.assertEqual(out[0].area, 2.0) self.assertEqual(out[1].area, 2.0) answer_vertices0 = [(0,0), (0,1), (0,2), (1,2), (1,1), (1,0), (0,0)] answer_vertices1 = [(2,1), (2,0), (1,0), (1,1), (1,2), (2,2), (2,1)] np.testing.assert_allclose(out[0].vertices, answer_vertices0) np.testing.assert_allclose(out[1].vertices, answer_vertices1) def test_clip(self): pass def test_erase(self): pass def test_union(self): new_geom = GIS.tabular.union(self.exdf) self.assertEqual(new_geom.area, 4) def test_intersection(self): pass def test_symmetric_difference(self): pass def test_difference(self): pass
lixun910/pysal
pysal/lib/cg/ops/tests/test_tabular.py
Python
bsd-3-clause
2,367
[ "COLUMBUS" ]
920338e0144287afff38d9aa3bfdc924fd315768eedbd3ccff4e644afed5f218
# Copyright 2000-2003 Jeff Chang. # Copyright 2001-2008 Brad Chapman. # Copyright 2005-2011 by Peter Cock. # Copyright 2006-2009 Michiel de Hoon. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Represent a Sequence Feature holding info about a part of a sequence. This is heavily modeled after the Biocorba SeqFeature objects, and may be pretty biased towards GenBank stuff since I'm writing it for the GenBank parser output... What's here: Base class to hold a Feature. ---------------------------- classes: o SeqFeature Hold information about a Reference. ---------------------------------- This is an attempt to create a General class to hold Reference type information. classes: o Reference Specify locations of a feature on a Sequence. --------------------------------------------- This aims to handle, in Ewan's words, 'the dreaded fuzziness issue' in much the same way as Biocorba. This has the advantages of allowing us to handle fuzzy stuff in case anyone needs it, and also be compatible with Biocorba. classes: o FeatureLocation - Specify the start and end location of a feature. o ExactPosition - Specify the position as being exact. o WithinPosition - Specify a position occuring within some range. o BetweenPosition - Specify a position occuring between a range (OBSOLETE?). o BeforePosition - Specify the position as being found before some base. o AfterPosition - Specify the position as being found after some base. o OneOfPosition - Specify a position where the location can be multiple positions. """ from Bio.Seq import MutableSeq, reverse_complement class SeqFeature(object): """Represent a Sequence Feature on an object. Attributes: o location - the location of the feature on the sequence (FeatureLocation) o type - the specified type of the feature (ie. CDS, exon, repeat...) o location_operator - a string specifying how this SeqFeature may be related to others. For example, in the example GenBank feature shown below, the location_operator would be "join" o strand - A value specifying on which strand (of a DNA sequence, for instance) the feature deals with. 1 indicates the plus strand, -1 indicates the minus strand, 0 indicates stranded but unknown (? in GFF3), while the default of None indicates that strand doesn't apply (dot in GFF3, e.g. features on proteins). Note this is a shortcut for accessing the strand property of the feature's location. o id - A string identifier for the feature. o ref - A reference to another sequence. This could be an accession number for some different sequence. Note this is a shortcut for the reference property of the feature's location. o ref_db - A different database for the reference accession number. Note this is a shortcut for the reference property of the location o qualifiers - A dictionary of qualifiers on the feature. These are analagous to the qualifiers from a GenBank feature table. The keys of the dictionary are qualifier names, the values are the qualifier values. o sub_features - Additional SeqFeatures which fall under this 'parent' feature. For instance, if we having something like: CDS join(1..10,30..40,50..60) Then the top level feature would be of type 'CDS' from 1 to 60 (actually 0 to 60 in Python counting) with location_operator='join', and the three sub- features would also be of type 'CDS', and would be from 1 to 10, 30 to 40 and 50 to 60, respectively (although actually using Python counting). To get the nucleotide sequence for this CDS, you would need to take the parent sequence and do seq[0:10]+seq[29:40]+seq[49:60] (Python counting). Things are more complicated with strands and fuzzy positions. To save you dealing with all these special cases, the SeqFeature provides an extract method to do this for you. """ def __init__(self, location = None, type = '', location_operator = '', strand = None, id = "<unknown id>", qualifiers = None, sub_features = None, ref = None, ref_db = None): """Initialize a SeqFeature on a Sequence. location can either be a FeatureLocation (with strand argument also given if required), or None. e.g. With no strand, on the forward strand, and on the reverse strand: >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> f1 = SeqFeature(FeatureLocation(5, 10), type="domain") >>> f1.strand == f1.location.strand == None True >>> f2 = SeqFeature(FeatureLocation(7, 110, strand=1), type="CDS") >>> f2.strand == f2.location.strand == +1 True >>> f3 = SeqFeature(FeatureLocation(9, 108, strand=-1), type="CDS") >>> f3.strand == f3.location.strand == -1 True An invalid strand will trigger an exception: >>> f4 = SeqFeature(FeatureLocation(50, 60), strand=2) Traceback (most recent call last): ... ValueError: Strand should be +1, -1, 0 or None, not 2 Similarly if set via the FeatureLocation directly: >>> loc4 = FeatureLocation(50, 60, strand=2) Traceback (most recent call last): ... ValueError: Strand should be +1, -1, 0 or None, not 2 For exact start/end positions, an integer can be used (as shown above) as shorthand for the ExactPosition object. For non-exact locations, the FeatureLocation must be specified via the appropriate position objects. """ if location is not None and not isinstance(location, FeatureLocation): raise TypeError("FeatureLocation (or None) required for the location") self.location = location self.type = type self.location_operator = location_operator if strand is not None: self.strand = strand self.id = id if qualifiers is None: qualifiers = {} self.qualifiers = qualifiers if sub_features is None: sub_features = [] self.sub_features = sub_features if ref is not None: self.ref = ref if ref_db is not None: self.ref_db = ref_db def _get_strand(self): return self.location.strand def _set_strand(self, value): try: self.location.strand = value except AttributeError: if self.location is None: if value is not None: raise ValueError("Can't set strand without a location.") else: raise strand = property(fget = _get_strand, fset = _set_strand, doc = """Feature's strand This is a shortcut for feature.location.strand """) def _get_ref(self): return self.location.ref def _set_ref(self, value): try: self.location.ref = value except AttributeError: if self.location is None: if value is not None: raise ValueError("Can't set ref without a location.") else: raise ref = property(fget = _get_ref, fset = _set_ref, doc = """Feature location reference (e.g. accession). This is a shortcut for feature.location.ref """) def _get_ref_db(self): return self.location.ref_db def _set_ref_db(self, value): self.location.ref_db = value ref_db = property(fget = _get_ref_db, fset = _set_ref_db, doc = """Feature location reference's database. This is a shortcut for feature.location.ref_db """) def __repr__(self): """A string representation of the record for debugging.""" answer = "%s(%s" % (self.__class__.__name__, repr(self.location)) if self.type: answer += ", type=%s" % repr(self.type) if self.location_operator: answer += ", location_operator=%s" % repr(self.location_operator) if self.id and self.id != "<unknown id>": answer += ", id=%s" % repr(self.id) if self.ref: answer += ", ref=%s" % repr(self.ref) if self.ref_db: answer += ", ref_db=%s" % repr(self.ref_db) answer += ")" return answer def __str__(self): """A readable summary of the feature intended to be printed to screen. """ out = "type: %s\n" % self.type out += "location: %s\n" % self.location if self.id and self.id != "<unknown id>": out += "id: %s\n" % self.id out += "qualifiers: \n" for qual_key in sorted(self.qualifiers): out += " Key: %s, Value: %s\n" % (qual_key, self.qualifiers[qual_key]) if len(self.sub_features) != 0: out += "Sub-Features\n" for sub_feature in self.sub_features: out +="%s\n" % sub_feature return out def _shift(self, offset): """Returns a copy of the feature with its location shifted (PRIVATE). The annotation qaulifiers are copied.""" return SeqFeature(location = self.location._shift(offset), type = self.type, location_operator = self.location_operator, id = self.id, qualifiers = dict(self.qualifiers.iteritems()), sub_features = [f._shift(offset) for f in self.sub_features]) def _flip(self, length): """Returns a copy of the feature with its location flipped (PRIVATE). The argument length gives the length of the parent sequence. For example a location 0..20 (+1 strand) with parent length 30 becomes after flipping 10..30 (-1 strand). Strandless (None) or unknown strand (0) remain like that - just their end points are changed. The annotation qaulifiers are copied. """ return SeqFeature(location = self.location._flip(length), type = self.type, location_operator = self.location_operator, id = self.id, qualifiers = dict(self.qualifiers.iteritems()), sub_features = [f._flip(length) for f in self.sub_features[::-1]]) def extract(self, parent_sequence): """Extract feature sequence from the supplied parent sequence. The parent_sequence can be a Seq like object or a string, and will generally return an object of the same type. The exception to this is a MutableSeq as the parent sequence will return a Seq object. This should cope with complex locations including complements, joins and fuzzy positions. Even mixed strand features should work! This also covers features on protein sequences (e.g. domains), although here reverse strand features are not permitted. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_protein >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein) >>> f = SeqFeature(FeatureLocation(8,15), type="domain") >>> f.extract(seq) Seq('VALIVIC', ProteinAlphabet()) Note - currently only sub-features of type "join" are supported. """ if isinstance(parent_sequence, MutableSeq): #This avoids complications with reverse complements #(the MutableSeq reverse complement acts in situ) parent_sequence = parent_sequence.toseq() if self.sub_features: if self.location_operator!="join": raise ValueError(self.location_operator) if self.location.strand == -1: #This is a special case given how the GenBank parser works. #Must avoid doing the reverse complement twice. parts = [] for f_sub in self.sub_features[::-1]: assert f_sub.location.strand==-1 parts.append(f_sub.location.extract(parent_sequence)) else: #This copes with mixed strand features: parts = [f_sub.location.extract(parent_sequence) \ for f_sub in self.sub_features] #We use addition rather than a join to avoid alphabet issues: f_seq = parts[0] for part in parts[1:] : f_seq += part return f_seq else: return self.location.extract(parent_sequence) def __nonzero__(self): """Returns True regardless of the length of the feature. This behaviour is for backwards compatibility, since until the __len__ method was added, a SeqFeature always evaluated as True. Note that in comparison, Seq objects, strings, lists, etc, will all evaluate to False if they have length zero. WARNING: The SeqFeature may in future evaluate to False when its length is zero (in order to better match normal python behaviour)! """ return True def __len__(self): """Returns the length of the region described by a feature. >>> from Bio.Seq import Seq >>> from Bio.Alphabet import generic_protein >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein) >>> f = SeqFeature(FeatureLocation(8,15), type="domain") >>> len(f) 7 >>> f.extract(seq) Seq('VALIVIC', ProteinAlphabet()) >>> len(f.extract(seq)) 7 For simple features without subfeatures this is the same as the region spanned (end position minus start position). However, for a feature defined by combining several subfeatures (e.g. a CDS as the join of several exons) the gaps are not counted (e.g. introns). This ensures that len(f) == len(f.extract(parent_seq)), and also makes sure things work properly with features wrapping the origin etc. """ if self.sub_features: return sum(len(f) for f in self.sub_features) else: return len(self.location) def __iter__(self): """Iterate over the parent positions within the feature. The iteration order is strand aware, and can be thought of as moving along the feature using the parent sequence coordinates: >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> f = SeqFeature(FeatureLocation(5,10), type="domain", strand=-1) >>> len(f) 5 >>> for i in f: print i 9 8 7 6 5 >>> list(f) [9, 8, 7, 6, 5] """ if self.sub_features: if self.strand == -1: for f in self.sub_features[::-1]: for i in f.location: yield i else: for f in self.sub_features: for i in f.location: yield i else: for i in self.location: yield i def __contains__(self, value): """Check if an integer position is within the feature. >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> f = SeqFeature(FeatureLocation(5,10), type="domain", strand=-1) >>> len(f) 5 >>> [i for i in range(15) if i in f] [5, 6, 7, 8, 9] For example, to see which features include a SNP position, you could use this: >>> from Bio import SeqIO >>> record = SeqIO.read("GenBank/NC_000932.gb", "gb") >>> for f in record.features: ... if 1750 in f: ... print f.type, f.location source [0:154478](+) gene [1716:4347](-) tRNA [1716:4347](-) Note that for a feature defined as a join of several subfeatures (e.g. the union of several exons) the gaps are not checked (e.g. introns). In this example, the tRNA location is defined in the GenBank file as complement(join(1717..1751,4311..4347)), so that position 1760 falls in the gap: >>> for f in record.features: ... if 1760 in f: ... print f.type, f.location source [0:154478](+) gene [1716:4347](-) Note that additional care may be required with fuzzy locations, for example just before a BeforePosition: >>> from Bio.SeqFeature import SeqFeature, FeatureLocation >>> from Bio.SeqFeature import BeforePosition >>> f = SeqFeature(FeatureLocation(BeforePosition(3),8), type="domain") >>> len(f) 5 >>> [i for i in range(10) if i in f] [3, 4, 5, 6, 7] """ if not isinstance(value, int): raise ValueError("Currently we only support checking for integer " "positions being within a SeqFeature.") if self.sub_features: for f in self.sub_features: if value in f: return True return False else: return value in self.location # --- References # TODO -- Will this hold PubMed and Medline information decently? class Reference(object): """Represent a Generic Reference object. Attributes: o location - A list of Location objects specifying regions of the sequence that the references correspond to. If no locations are specified, the entire sequence is assumed. o authors - A big old string, or a list split by author, of authors for the reference. o title - The title of the reference. o journal - Journal the reference was published in. o medline_id - A medline reference for the article. o pubmed_id - A pubmed reference for the article. o comment - A place to stick any comments about the reference. """ def __init__(self): self.location = [] self.authors = '' self.consrtm = '' self.title = '' self.journal = '' self.medline_id = '' self.pubmed_id = '' self.comment = '' def __str__(self): """Output an informative string for debugging. """ out = "" for single_location in self.location: out += "location: %s\n" % single_location out += "authors: %s\n" % self.authors if self.consrtm: out += "consrtm: %s\n" % self.consrtm out += "title: %s\n" % self.title out += "journal: %s\n" % self.journal out += "medline id: %s\n" % self.medline_id out += "pubmed id: %s\n" % self.pubmed_id out += "comment: %s\n" % self.comment return out def __repr__(self): #TODO - Update this is __init__ later accpets values return "%s(title=%s, ...)" % (self.__class__.__name__, repr(self.title)) # --- Handling feature locations class FeatureLocation(object): """Specify the location of a feature along a sequence. This attempts to deal with fuzziness of position ends, but also make it easy to get the start and end in the 'normal' case (no fuzziness). You should access the start and end attributes with your_location.start and your_location.end. If the start and end are exact, this will return the positions, if not, we'll return the approriate Fuzzy class with info about the position and fuzziness. Note that the start and end location numbering follow Python's scheme, thus a GenBank entry of 123..150 (one based counting) becomes a location of [122:150] (zero based counting). """ def __init__(self, start, end, strand=None, ref=None, ref_db=None): """Specify the start, end, strand etc of a sequence feature. start and end arguments specify the values where the feature begins and ends. These can either by any of the *Position objects that inherit from AbstractPosition, or can just be integers specifying the position. In the case of integers, the values are assumed to be exact and are converted in ExactPosition arguments. This is meant to make it easy to deal with non-fuzzy ends. i.e. Short form: >>> from Bio.SeqFeature import FeatureLocation >>> loc = FeatureLocation(5, 10, strand=-1) >>> print loc [5:10](-) Explicit form: >>> from Bio.SeqFeature import FeatureLocation, ExactPosition >>> loc = FeatureLocation(ExactPosition(5), ExactPosition(10), strand=-1) >>> print loc [5:10](-) Other fuzzy positions are used similarly, >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition >>> loc2 = FeatureLocation(BeforePosition(5), AfterPosition(10), strand=-1) >>> print loc2 [<5:>10](-) For nucleotide features you will also want to specify the strand, use 1 for the forward (plus) strand, -1 for the reverse (negative) strand, 0 for stranded but strand unknown (? in GFF3), or None for when the strand does not apply (dot in GFF3), e.g. features on proteins. >>> loc = FeatureLocation(5, 10, strand=+1) >>> print loc [5:10](+) >>> print loc.strand 1 Normally feature locations are given relative to the parent sequence you are working with, but an explicit accession can be given with the optional ref and db_ref strings: >>> loc = FeatureLocation(105172, 108462, ref="AL391218.9", strand=1) >>> print loc AL391218.9[105172:108462](+) >>> print loc.ref AL391218.9 """ if isinstance(start, AbstractPosition): self._start = start elif isinstance(start, int): self._start = ExactPosition(start) else: raise TypeError(start) if isinstance(end, AbstractPosition): self._end = end elif isinstance(end, int): self._end = ExactPosition(end) else: raise TypeError(end) self.strand = strand self.ref = ref self.ref_db = ref_db def _get_strand(self): return self._strand def _set_strand(self, value): if value not in [+1, -1, 0, None]: raise ValueError("Strand should be +1, -1, 0 or None, not %r" \ % value) self._strand = value strand = property(fget = _get_strand, fset = _set_strand, doc = "Strand of the location (+1, -1, 0 or None).") def __str__(self): """Returns a representation of the location (with python counting). For the simple case this uses the python splicing syntax, [122:150] (zero based counting) which GenBank would call 123..150 (one based counting). """ answer = "[%s:%s]" % (self._start, self._end) if self.ref and self.ref_db: answer = "%s:%s%s" % (self.ref_db, self.ref, answer) elif self.ref: answer = self.ref + answer #Is ref_db without ref meaningful? if self.strand is None: return answer elif self.strand == +1: return answer + "(+)" elif self.strand == -1: return answer + "(-)" else: #strand = 0, stranded but strand unknown, ? in GFF3 return answer + "(?)" def __repr__(self): """A string representation of the location for debugging.""" optional = "" if self.strand is not None: optional += ", strand=%r" % self.strand if self.ref is not None: optional += ", ref=%r" % self.ref if self.ref_db is not None: optional += ", ref_db=%r" % self.ref_db return "%s(%r, %r%s)" \ % (self.__class__.__name__, self.start, self.end, optional) def __nonzero__(self): """Returns True regardless of the length of the feature. This behaviour is for backwards compatibility, since until the __len__ method was added, a FeatureLocation always evaluated as True. Note that in comparison, Seq objects, strings, lists, etc, will all evaluate to False if they have length zero. WARNING: The FeatureLocation may in future evaluate to False when its length is zero (in order to better match normal python behaviour)! """ return True def __len__(self): """Returns the length of the region described by the FeatureLocation. Note that extra care may be needed for fuzzy locations, e.g. >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) >>> len(loc) 5 """ return int(self._end) - int(self._start) def __contains__(self, value): """Check if an integer position is within the FeatureLocation. Note that extra care may be needed for fuzzy locations, e.g. >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) >>> len(loc) 5 >>> [i for i in range(15) if i in loc] [5, 6, 7, 8, 9] """ if not isinstance(value, int): raise ValueError("Currently we only support checking for integer " "positions being within a FeatureLocation.") if value < self._start or value >= self._end: return False else: return True def __iter__(self): """Iterate over the parent positions within the FeatureLocation. >>> from Bio.SeqFeature import FeatureLocation >>> from Bio.SeqFeature import BeforePosition, AfterPosition >>> loc = FeatureLocation(BeforePosition(5),AfterPosition(10)) >>> len(loc) 5 >>> for i in loc: print i 5 6 7 8 9 >>> list(loc) [5, 6, 7, 8, 9] >>> [i for i in range(15) if i in loc] [5, 6, 7, 8, 9] Note this is strand aware: >>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10), strand = -1) >>> list(loc) [9, 8, 7, 6, 5] """ if self.strand == -1: for i in range(self._end - 1, self._start - 1, -1): yield i else: for i in range(self._start, self._end): yield i def _shift(self, offset): """Returns a copy of the location shifted by the offset (PRIVATE).""" if self.ref or self.ref_db: #TODO - Return self? raise ValueError("Feature references another sequence.") return FeatureLocation(start = self._start._shift(offset), end = self._end._shift(offset), strand = self.strand) def _flip(self, length): """Returns a copy of the location after the parent is reversed (PRIVATE).""" if self.ref or self.ref_db: #TODO - Return self? raise ValueError("Feature references another sequence.") #Note this will flip the start and end too! if self.strand == +1: flip_strand = -1 elif self.strand == -1: flip_strand = +1 else: #0 or None flip_strand = self.strand return FeatureLocation(start = self._end._flip(length), end = self._start._flip(length), strand = flip_strand) @property def start(self): """Start location (integer like, possibly a fuzzy position, read only).""" return self._start @property def end(self): """End location (integer like, possibly a fuzzy position, read only).""" return self._end @property def nofuzzy_start(self): """Start position (integer, approximated if fuzzy, read only) (OBSOLETE). This is now a alias for int(feature.start), which should be used in preference -- unless you are trying to support old versions of Biopython. """ return int(self._start) @property def nofuzzy_end(self): """End position (integer, approximated if fuzzy, read only) (OBSOLETE). This is now a alias for int(feature.end), which should be used in preference -- unless you are trying to support old versions of Biopython. """ return int(self._end) def extract(self, parent_sequence): """Extract feature sequence from the supplied parent sequence.""" if self.ref or self.ref_db: #TODO - Take a dictionary as an optional argument? raise ValueError("Feature references another sequence.") if isinstance(parent_sequence, MutableSeq): #This avoids complications with reverse complements #(the MutableSeq reverse complement acts in situ) parent_sequence = parent_sequence.toseq() f_seq = parent_sequence[self.nofuzzy_start:self.nofuzzy_end] if self.strand == -1: try: f_seq = f_seq.reverse_complement() except AttributeError: assert isinstance(f_seq, str) f_seq = reverse_complement(f_seq) return f_seq class AbstractPosition(object): """Abstract base class representing a position. """ def __repr__(self): """String representation of the location for debugging.""" return "%s(...)" % (self.__class__.__name__) class ExactPosition(int, AbstractPosition): """Specify the specific position of a boundary. o position - The position of the boundary. o extension - An optional argument which must be zero since we don't have an extension. The argument is provided so that the same number of arguments can be passed to all position types. In this case, there is no fuzziness associated with the position. >>> p = ExactPosition(5) >>> p ExactPosition(5) >>> print p 5 >>> isinstance(p, AbstractPosition) True >>> isinstance(p, int) True Integer comparisons and operations should work as expected: >>> p == 5 True >>> p < 6 True >>> p <= 5 True >>> p + 10 15 """ def __new__(cls, position, extension = 0): if extension != 0: raise AttributeError("Non-zero extension %s for exact position." % extension) return int.__new__(cls, position) def __repr__(self): """String representation of the ExactPosition location for debugging.""" return "%s(%i)" % (self.__class__.__name__, int(self)) @property def position(self): """Legacy attribute to get position as integer (OBSOLETE).""" return int(self) @property def extension(self): """Legacy attribute to get extension (zero) as integer (OBSOLETE).""" return 0 def _shift(self, offset): #By default preserve any subclass return self.__class__(int(self) + offset) def _flip(self, length): #By default perserve any subclass return self.__class__(length - int(self)) class UncertainPosition(ExactPosition): """Specify a specific position which is uncertain. This is used in UniProt, e.g. ?222 for uncertain position 222, or in the XML format explicitly marked as uncertain. Does not apply to GenBank/EMBL. """ pass class UnknownPosition(AbstractPosition): """Specify a specific position which is unknown (has no position). This is used in UniProt, e.g. ? or in the XML as unknown. """ def __repr__(self): """String representation of the UnknownPosition location for debugging.""" return "%s()" % self.__class__.__name__ def __hash__(self): return hash(None) @property def position(self): """Legacy attribute to get position (None) (OBSOLETE).""" return None @property def extension(self): """Legacy attribute to get extension (zero) as integer (OBSOLETE).""" return 0 def _shift(self, offset): return self def _flip(self, length): return self class WithinPosition(int, AbstractPosition): """Specify the position of a boundary within some coordinates. Arguments: o position - The default integer position o left - The start (left) position of the boundary o right - The end (right) position of the boundary This allows dealing with a position like ((1.4)..100). This indicates that the start of the sequence is somewhere between 1 and 4. Since this is a start coordindate, it should acts like it is at position 1 (or in Python counting, 0). >>> p = WithinPosition(10,10,13) >>> p WithinPosition(10, left=10, right=13) >>> print p (10.13) >>> int(p) 10 Basic integer comparisons and operations should work as though this were a plain integer: >>> p == 10 True >>> p in [9,10,11] True >>> p < 11 True >>> p + 10 20 >>> isinstance(p, WithinPosition) True >>> isinstance(p, AbstractPosition) True >>> isinstance(p, int) True Note this also applies for comparison to other position objects, where again the integer behaviour is used: >>> p == 10 True >>> p == ExactPosition(10) True >>> p == BeforePosition(10) True >>> p == AfterPosition(10) True If this were an end point, you would want the position to be 13: >>> p2 = WithinPosition(13,10,13) >>> p2 WithinPosition(13, left=10, right=13) >>> print p2 (10.13) >>> int(p2) 13 >>> p2 == 13 True >>> p2 == ExactPosition(13) True The old legacy properties of position and extension give the starting/lower/left position as an integer, and the distance to the ending/higher/right position as an integer. Note that the position object will act like either the left or the right end-point depending on how it was created: >>> p.position == p2.position == 10 True >>> p.extension == p2.extension == 3 True >>> int(p) == int(p2) False >>> p == 10 True >>> p2 == 13 True """ def __new__(cls, position, left, right): assert position==left or position==right obj = int.__new__(cls, position) obj._left = left obj._right = right return obj def __repr__(self): """String representation of the WithinPosition location for debugging.""" return "%s(%i, left=%i, right=%i)" \ % (self.__class__.__name__, int(self), self._left, self._right) def __str__(self): return "(%s.%s)" % (self._left, self._right) @property def position(self): """Legacy attribute to get (left) position as integer (OBSOLETE).""" return self._left @property def extension(self): """Legacy attribute to get extension (from left to right) as an integer (OBSOLETE).""" return self._right - self._left def _shift(self, offset): return self.__class__(int(self) + offset, self._left + offset, self._right + offset) def _flip(self, length): return self.__class__(length - int(self), length - self._right, length - self._left) class BetweenPosition(int, AbstractPosition): """Specify the position of a boundary between two coordinates (OBSOLETE?). Arguments: o position - The default integer position o left - The start (left) position of the boundary o right - The end (right) position of the boundary This allows dealing with a position like 123^456. This indicates that the start of the sequence is somewhere between 123 and 456. It is up to the parser to set the position argument to either boundary point (depending on if this is being used as a start or end of the feature). For example as a feature end: >>> p = BetweenPosition(456, 123, 456) >>> p BetweenPosition(456, left=123, right=456) >>> print p (123^456) >>> int(p) 456 Integer equality and comparison use the given position, >>> p == 456 True >>> p in [455, 456, 457] True >>> p > 300 True The old legacy properties of position and extension give the starting/lower/left position as an integer, and the distance to the ending/higher/right position as an integer. Note that the position object will act like either the left or the right end-point depending on how it was created: >>> p2 = BetweenPosition(123, left=123, right=456) >>> p.position == p2.position == 123 True >>> p.extension 333 >>> p2.extension 333 >>> p.extension == p2.extension == 333 True >>> int(p) == int(p2) False >>> p == 456 True >>> p2 == 123 True Note this potentially surprising behaviour: >>> BetweenPosition(123, left=123, right=456) == ExactPosition(123) True >>> BetweenPosition(123, left=123, right=456) == BeforePosition(123) True >>> BetweenPosition(123, left=123, right=456) == AfterPosition(123) True i.e. For equality (and sorting) the position objects behave like integers. """ def __new__(cls, position, left, right): assert position==left or position==right obj = int.__new__(cls, position) obj._left = left obj._right = right return obj def __repr__(self): """String representation of the WithinPosition location for debugging.""" return "%s(%i, left=%i, right=%i)" \ % (self.__class__.__name__, int(self), self._left, self._right) def __str__(self): return "(%s^%s)" % (self._left, self._right) @property def position(self): """Legacy attribute to get (left) position as integer (OBSOLETE).""" return self._left @property def extension(self): """Legacy attribute to get extension (from left to right) as an integer (OBSOLETE).""" return self._right - self._left def _shift(self, offset): return self.__class__(int(self) + offset, self._left + offset, self._right + offset) def _flip(self, length): return self.__class__(length - int(self), length - self._right, length - self._left) class BeforePosition(int, AbstractPosition): """Specify a position where the actual location occurs before it. Arguments: o position - The upper boundary of where the location can occur. o extension - An optional argument which must be zero since we don't have an extension. The argument is provided so that the same number of arguments can be passed to all position types. This is used to specify positions like (<10..100) where the location occurs somewhere before position 10. >>> p = BeforePosition(5) >>> p BeforePosition(5) >>> print p <5 >>> int(p) 5 >>> p + 10 15 Note this potentially surprising behaviour: >>> p == ExactPosition(5) True >>> p == AfterPosition(5) True Just remember that for equality and sorting the position objects act like integers. """ #Subclasses int so can't use __init__ def __new__(cls, position, extension = 0): if extension != 0: raise AttributeError("Non-zero extension %s for exact position." % extension) return int.__new__(cls, position) @property def position(self): """Legacy attribute to get position as integer (OBSOLETE).""" return int(self) @property def extension(self): """Legacy attribute to get extension (zero) as integer (OBSOLETE).""" return 0 def __repr__(self): """A string representation of the location for debugging.""" return "%s(%i)" % (self.__class__.__name__, int(self)) def __str__(self): return "<%s" % self.position def _shift(self, offset): return self.__class__(int(self) + offset) def _flip(self, length): return AfterPosition(length - int(self)) class AfterPosition(int, AbstractPosition): """Specify a position where the actual location is found after it. Arguments: o position - The lower boundary of where the location can occur. o extension - An optional argument which must be zero since we don't have an extension. The argument is provided so that the same number of arguments can be passed to all position types. This is used to specify positions like (>10..100) where the location occurs somewhere after position 10. >>> p = AfterPosition(7) >>> p AfterPosition(7) >>> print p >7 >>> int(p) 7 >>> p + 10 17 >>> isinstance(p, AfterPosition) True >>> isinstance(p, AbstractPosition) True >>> isinstance(p, int) True Note this potentially surprising behaviour: >>> p == ExactPosition(7) True >>> p == BeforePosition(7) True Just remember that for equality and sorting the position objects act like integers. """ #Subclasses int so can't use __init__ def __new__(cls, position, extension = 0): if extension != 0: raise AttributeError("Non-zero extension %s for exact position." % extension) return int.__new__(cls, position) @property def position(self): """Legacy attribute to get position as integer (OBSOLETE).""" return int(self) @property def extension(self): """Legacy attribute to get extension (zero) as integer (OBSOLETE).""" return 0 def __repr__(self): """A string representation of the location for debugging.""" return "%s(%i)" % (self.__class__.__name__, int(self)) def __str__(self): return ">%s" % self.position def _shift(self, offset): return self.__class__(int(self) + offset) def _flip(self, length): return BeforePosition(length - int(self)) class OneOfPosition(int, AbstractPosition): """Specify a position where the location can be multiple positions. This models the GenBank 'one-of(1888,1901)' function, and tries to make this fit within the Biopython Position models. If this was a start position it should act like 1888, but as an end position 1901. >>> p = OneOfPosition(1888, [ExactPosition(1888), ExactPosition(1901)]) >>> p OneOfPosition(1888, choices=[ExactPosition(1888), ExactPosition(1901)]) >>> int(p) 1888 Interget comparisons and operators act like using int(p), >>> p == 1888 True >>> p <= 1888 True >>> p > 1888 False >>> p + 100 1988 >>> isinstance(p, OneOfPosition) True >>> isinstance(p, AbstractPosition) True >>> isinstance(p, int) True The old legacy properties of position and extension give the starting/lowest/left-most position as an integer, and the distance to the ending/highest/right-most position as an integer. Note that the position object will act like one of the list of possible locations depending on how it was created: >>> p2 = OneOfPosition(1901, [ExactPosition(1888), ExactPosition(1901)]) >>> p.position == p2.position == 1888 True >>> p.extension == p2.extension == 13 True >>> int(p) == int(p2) False >>> p == 1888 True >>> p2 == 1901 True """ def __new__(cls, position, choices): """Initialize with a set of posssible positions. position_list is a list of AbstractPosition derived objects, specifying possible locations. position is an integer specifying the default behaviour. """ assert position in choices obj = int.__new__(cls, position) obj.position_choices = choices return obj @property def position(self): """Legacy attribute to get (left) position as integer (OBSOLETE).""" return min(int(pos) for pos in self.position_choices) @property def extension(self): """Legacy attribute to get extension as integer (OBSOLETE).""" positions = [int(pos) for pos in self.position_choices] return max(positions) - min(positions) def __repr__(self): """String representation of the OneOfPosition location for debugging.""" return "%s(%i, choices=%r)" % (self.__class__.__name__, \ int(self), self.position_choices) def __str__(self): out = "one-of(" for position in self.position_choices: out += "%s," % position # replace the last comma with the closing parenthesis out = out[:-1] + ")" return out def _shift(self, offset): return self.__class__(int(self) + offset, [p._shift(offset) for p in self.position_choices]) def _flip(self, length): return self.__class__(length - int(self), [p._flip(length) for p in self.position_choices[::-1]]) class PositionGap(object): """Simple class to hold information about a gap between positions. """ def __init__(self, gap_size): """Intialize with a position object containing the gap information. """ self.gap_size = gap_size def __repr__(self): """A string representation of the position gap for debugging.""" return "%s(%s)" % (self.__class__.__name__, repr(self.gap_size)) def __str__(self): out = "gap(%s)" % self.gap_size return out def _test(): """Run the Bio.SeqFeature module's doctests (PRIVATE). This will try and locate the unit tests directory, and run the doctests from there in order that the relative paths used in the examples work. """ import doctest import os if os.path.isdir(os.path.join("..","Tests")): print "Runing doctests..." cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("..","Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir print "Done" elif os.path.isdir(os.path.join("Tests")) : print "Runing doctests..." cur_dir = os.path.abspath(os.curdir) os.chdir(os.path.join("Tests")) doctest.testmod() os.chdir(cur_dir) del cur_dir print "Done" if __name__ == "__main__": _test()
bryback/quickseq
genescript/Bio/SeqFeature.py
Python
mit
47,556
[ "Biopython" ]
95c930e76ace245eacf4bc1a1eaa6473aeadd2f9e013bdc2867e717cb0e729f5
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """Wrapper for netCDF readers.""" from __future__ import unicode_literals, division, print_function import os.path from monty.dev import requires, deprecated from monty.collections import AttrDict from monty.functools import lazy_property from pymatgen.core.units import ArrayWithUnit from pymatgen.core.structure import Structure import logging logger = logging.getLogger(__name__) __author__ = "Matteo Giantomassi" __copyright__ = "Copyright 2013, The Materials Project" __version__ = "0.1" __maintainer__ = "Matteo Giantomassi" __email__ = "gmatteo at gmail.com" __status__ = "Development" __date__ = "$Feb 21, 2013M$" __all__ = [ "as_ncreader", "as_etsfreader", "NetcdfReader", "ETSF_Reader", "structure_from_ncdata", ] try: import netCDF4 except ImportError: netCDF4 = None def _asreader(file, cls): closeit = False if not isinstance(file, cls): file, closeit = cls(file), True return file, closeit def as_ncreader(file): """ Convert file into a NetcdfReader instance. Returns reader, closeit where closeit is set to True if we have to close the file before leaving the procedure. """ return _asreader(file, NetcdfReader) def as_etsfreader(file): return _asreader(file, ETSF_Reader) class NetcdfReaderError(Exception): """Base error class for NetcdfReader""" class NO_DEFAULT(object): """Signal that read_value should raise an Error""" class NetcdfReader(object): """ Wraps and extends netCDF4.Dataset. Read only mode. Supports with statements. Additional documentation available at: http://netcdf4-python.googlecode.com/svn/trunk/docs/netCDF4-module.html """ Error = NetcdfReaderError @requires(netCDF4 is not None, "netCDF4 must be installed to use this class") def __init__(self, path): """Open the Netcdf file specified by path (read mode).""" self.path = os.path.abspath(path) try: self.rootgrp = netCDF4.Dataset(self.path, mode="r") except Exception as exc: raise self.Error("In file %s: %s" % (self.path, str(exc))) self.ngroups = len(list(self.walk_tree())) #self.path2group = collections.OrderedDict() #for children in self.walk_tree(): # for child in children: # #print(child.group, child.path) # self.path2group[child.path] = child.group def __enter__(self): """Activated when used in the with statement.""" return self def __exit__(self, type, value, traceback): """Activated at the end of the with statement. It automatically closes the file.""" self.rootgrp.close() def close(self): try: self.rootgrp.close() except Exception as exc: logger.warning("Exception %s while trying to close %s" % (exc, self.path)) #@staticmethod #def pathjoin(*args): # return "/".join(args) def walk_tree(self, top=None): """ Navigate all the groups in the file starting from top. If top is None, the root group is used. """ if top is None: top = self.rootgrp values = top.groups.values() yield values for value in top.groups.values(): for children in self.walk_tree(value): yield children def print_tree(self): for children in self.walk_tree(): for child in children: print(child) def read_dimvalue(self, dimname, path="/"): """Returns the value of a dimension.""" dim = self._read_dimensions(dimname, path=path)[0] return len(dim) def read_varnames(self, path="/"): """List of variable names stored in the group specified by path.""" if path == "/": return self.rootgrp.variables.keys() else: group = self.path2group[path] return group.variables.keys() def read_value(self, varname, path="/", cmode=None, default=NO_DEFAULT): """ Returns the values of variable with name varname in the group specified by path. Args: varname: Name of the variable path: path to the group. cmode: if cmode=="c", a complex ndarrays is constructed and returned (netcdf does not provide native support from complex datatype). default: read_value returns default if varname is not present. Returns: numpy array if varname represents an array, scalar otherwise. """ try: var = self.read_variable(varname, path=path) except self.Error: if default is NO_DEFAULT: raise return default if cmode is None: # scalar or array # getValue is not portable! try: return var.getValue()[0] if not var.shape else var[:] except IndexError: return var.getValue() if not var.shape else var[:] else: assert var.shape[-1] == 2 if cmode == "c": return var[...,0] + 1j*var[...,1] else: raise ValueError("Wrong value for cmode %s" % cmode) def read_variable(self, varname, path="/"): """Returns the variable with name varname in the group specified by path.""" return self._read_variables(varname, path=path)[0] def _read_dimensions(self, *dimnames, **kwargs): path = kwargs.get("path", "/") try: if path == "/": return [self.rootgrp.dimensions[dname] for dname in dimnames] else: group = self.path2group[path] return [group.dimensions[dname] for dname in dimnames] except KeyError: raise self.Error("In file %s:\ndimnames %s, kwargs %s" % (self.path, dimnames, kwargs)) def _read_variables(self, *varnames, **kwargs): path = kwargs.get("path", "/") try: if path == "/": return [self.rootgrp.variables[vname] for vname in varnames] else: group = self.path2group[path] return [group.variables[vname] for vname in varnames] except KeyError: raise self.Error("In file %s:\nvarnames %s, kwargs %s" % (self.path, varnames, kwargs)) def read_keys(self, keys, dict_cls=AttrDict, path="/"): """ Read a list of variables/dimensions from file. If a key is not present the corresponding entry in the output dictionary is set to None. """ od = dict_cls() for k in keys: try: # Try to read a variable. od[k] = self.read_value(k, path=path) except self.Error: try: # Try to read a dimension. od[k] = self.read_dimvalue(k, path=path) except self.Error: od[k] = None return od class ETSF_Reader(NetcdfReader): """ This object reads data from a file written according to the ETSF-IO specifications. We assume that the netcdf file contains at least the crystallographic section. """ @lazy_property def chemical_symbols(self): """Chemical symbols char [number of atom species][symbol length].""" charr = self.read_value("chemical_symbols") symbols = [] for v in charr: symbols.append("".join(c for c in v)) #symbols = ["".join(str(c)) for symb in symbols for c in symb] #symbols = [s.decode("ascii") for s in symbols] #chemical_symbols = [str("".join(s)) for s in symbols] #print(symbols) return symbols def typeidx_from_symbol(self, symbol): """Returns the type index from the chemical symbol. Note python convention.""" return self.chemical_symbols.index(symbol) def read_structure(self, cls=Structure): """Returns the crystalline structure.""" if self.ngroups != 1: raise NotImplementedError("In file %s: ngroups != 1" % self.path) return structure_from_ncdata(self, cls=cls) def structure_from_ncdata(ncdata, site_properties=None, cls=Structure): """ Reads and returns a pymatgen structure from a NetCDF file containing crystallographic data in the ETSF-IO format. Args: ncdata: filename or NetcdfReader instance. site_properties: Dictionary with site properties. cls: The Structure class to instanciate. """ ncdata, closeit = as_ncreader(ncdata) # TODO check whether atomic units are used lattice = ArrayWithUnit(ncdata.read_value("primitive_vectors"), "bohr").to("ang") red_coords = ncdata.read_value("reduced_atom_positions") natom = len(red_coords) znucl_type = ncdata.read_value("atomic_numbers") # type_atom[0:natom] --> index Between 1 and number of atom species type_atom = ncdata.read_value("atom_species") # Fortran to C index and float --> int conversion. species = natom * [None] for atom in range(natom): type_idx = type_atom[atom] - 1 species[atom] = int(znucl_type[type_idx]) d = {} if site_properties is not None: for prop in site_properties: d[property] = ncdata.read_value(prop) structure = cls(lattice, species, red_coords, site_properties=d) # Quick and dirty hack. # I need an abipy structure since I need to_abivars and other methods. try: from abipy.core.structure import Structure as AbipyStructure structure.__class__ = AbipyStructure except ImportError: pass if closeit: ncdata.close() return structure
migueldiascosta/pymatgen
pymatgen/io/abinit/netcdf.py
Python
mit
9,868
[ "NetCDF", "pymatgen" ]
0a1423f6c757519c65c8e56f8876f0afcfbdd70b1102f4ef849c90fd1ad53dd4
"""Generates galaxy labels for individual annotators. Matthew Alger The Australian National University 2016 """ import argparse import h5py import numpy import sklearn.neighbors from .config import config ARCMIN = 1 / 60 # deg ATLAS_IMAGE_SIZE = (config['surveys']['atlas']['fits_width'] * config['surveys']['atlas']['fits_height']) def main(f_h5, ir_survey, overwrite=False): """ f_h5: crowdastro HDF5 file. ir_survey: 'wise' or 'swire'. overwrite: Whether to overwrite existing annotator labels. Default False. """ usernames = sorted({username for username in f_h5['/atlas/cdfs/classification_usernames'].value if username}) usernames = {j:i for i, j in enumerate(usernames)} n_annotators = len(usernames) n_examples = f_h5['/{}/cdfs/numeric'.format(ir_survey)].shape[0] if (('/{}/cdfs/rgz_raw_labels'.format(ir_survey) in f_h5 or '/{}/cdfs/rgz_raw_labels_mask'.format(ir_survey) in f_h5) and overwrite): del f_h5['/{}/cdfs/rgz_raw_labels'.format(ir_survey)] del f_h5['/{}/cdfs/rgz_raw_labels_mask'.format(ir_survey)] labels = f_h5.create_dataset( '/{}/cdfs/rgz_raw_labels'.format(ir_survey), data=numpy.zeros((n_annotators, n_examples)).astype(bool)) unseen = f_h5.create_dataset( '/{}/cdfs/rgz_raw_labels_mask'.format(ir_survey), data=numpy.ones((n_annotators, n_examples)).astype(bool)) ir_tree = sklearn.neighbors.KDTree( f_h5['/{}/cdfs/numeric'.format(ir_survey)][:, :2]) # What objects has each annotator seen? Assume that if they have labelled a # radio object, then they have seen everything within 1 arcminute. for class_pos, username in zip( f_h5['/atlas/cdfs/classification_positions'], f_h5['/atlas/cdfs/classification_usernames']): if username not in usernames: # Skip unidentified users. continue atlas_id, ra, dec, primary = class_pos distances = f_h5['/atlas/cdfs/numeric'][atlas_id, 2 + ATLAS_IMAGE_SIZE:] assert distances.shape[0] == n_examples nearby = distances <= ARCMIN unseen[usernames[username], nearby] = False # Unmask nearby objects. # Now, label the example we are looking at now. if numpy.isnan(ra) or numpy.isnan(dec): # No IR source, so we can just skip this. continue # Get the nearest IR object and assign the label. ((dist,),), ((ir,),) = ir_tree.query([(ra, dec)]) if dist > config['surveys'][ir_survey]['distance_cutoff']: logging.debug('Click has no corresponding IR.') continue labels[usernames[username], ir] = 1 def _populate_parser(parser): parser.description = 'Generates galaxy labels for individual annotators.' parser.add_argument('--h5', default='data/crowdastro.h5', help='HDF5 IO file') parser.add_argument('--overwrite', action='store_true', help='overwrite existing annotator labels') def _main(args): with h5py.File(args.h5, 'r+') as f_h5: ir_survey = f_h5.attrs['ir_survey'] main(f_h5, ir_survey, overwrite=args.overwrite) if __name__ == '__main__': parser = argparse.ArgumentParser() _populate_parser(parser) args = parser.parse_args() _main(args)
chengsoonong/crowdastro
crowdastro/generate_annotator_labels.py
Python
mit
3,441
[ "Galaxy" ]
2ea385c0b0013817dc9d18b45beb42657db0ef70fa3a38b3f49c97c519126a0f
# -~- coding: utf-8 -*- from datetime import datetime from django.db import models from django.core.cache import cache from django.contrib.sites.models import Site from django.conf import settings from nongratae.constants import BLOCKED_IPS_CACHE_KEY BLOCKED_IPS_CACHE_KEY = BLOCKED_IPS_CACHE_KEY % settings.SITE_ID class Visit(models.Model): """ Represents a Web Hit """ ip = models.IPAddressField() referer = models.CharField(max_length=512, blank=True) user_agent = models.CharField(max_length=256, blank=True) method = models.CharField(max_length=8) accept_headers = models.CharField(max_length=64, blank=True) visit_time = models.DateTimeField() def build_from_request(self, request): """ Fills out the Visit fields based on the Request data """ self.ip = request.META['REMOTE_ADDR'] self.referer = request.META.get('HTTP_REFERER', '') self.user_agent = request.META.get('HTTP_USER_AGENT', '') self.method = request.META['REQUEST_METHOD'] self.accept = request.META.get('HTTP_ACCEPT', '') self.visit_time = datetime.now() class IPNonGrata(models.Model): """ Represents a Blocked IP that isn't welcome to the site """ BLOCKED = 2 SUSPICIOUS = 1 CLEAN = 0 IP_STATUS = ( (CLEAN, u'Ip Clean'), (SUSPICIOUS, u'Ip Suspicious'), (BLOCKED, u'Ip Blocked'), ) site = models.ForeignKey(Site) ip = models.IPAddressField() motive = models.CharField(max_length=256) date_blocked = models.DateField(auto_now=True) status = models.PositiveSmallIntegerField(choices=IP_STATUS) def save(self, *args, **kwargs): """ Overriden to clear Cache after a new IP is added """ cache.delete(BLOCKED_IPS_CACHE_KEY) super(IPNonGrata, self).save(*args, **kwargs)
jjdelc/django-ip-nongratae
nongratae/models.py
Python
bsd-3-clause
1,838
[ "VisIt" ]
8e47c03ac056a697933fe330af15a49a98fa5f0e42bf0f4e97cdf77aee9fa307
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, absolute_import """ This module provides conversion between the Atomic Simulation Environment Atoms object and pymatgen Structure objects. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Mar 8, 2012" from pymatgen.core.structure import Structure try: from ase import Atoms ase_loaded = True except ImportError: ase_loaded = False class AseAtomsAdaptor(object): """ Adaptor serves as a bridge between ASE Atoms and pymatgen structure. """ @staticmethod def get_atoms(structure, **kwargs): """ Returns ASE Atoms object from pymatgen structure. Args: structure: pymatgen.core.structure.Structure **kwargs: other keyword args to pass into the ASE Atoms constructor Returns: ASE Atoms object """ if not structure.is_ordered: raise ValueError("ASE Atoms only supports ordered structures") symbols = [str(site.specie.symbol) for site in structure] positions = [site.coords for site in structure] cell = structure.lattice.matrix return Atoms(symbols=symbols, positions=positions, pbc=True, cell=cell, **kwargs) @staticmethod def get_structure(atoms, cls=None): """ Returns pymatgen structure from ASE Atoms. Args: atoms: ASE Atoms object cls: The Structure class to instantiate (defaults to pymatgen structure) Returns: Equivalent pymatgen.core.structure.Structure """ symbols = atoms.get_chemical_symbols() positions = atoms.get_positions() lattice = atoms.get_cell() cls = Structure if cls is None else cls return cls(lattice, symbols, positions, coords_are_cartesian=True)
gpetretto/pymatgen
pymatgen/io/ase.py
Python
mit
2,106
[ "ASE", "pymatgen" ]
a848e2a54a68def633edf59a70a8d997d8100e36e4c8a6a3b6e844107fd4e60f
import numpy as np from scipy.spatial.distance import cdist class Segreg(object): def __init__(self): self.attributeMatrix = np.matrix([]) # attributes matrix full size - all columns self.location = [] # x and y coordinates from tract centroid (2D lists) self.pop = [] # population of each groups by tract (2D lists) self.pop_sum = [] # total population of the tract (sum all groups) self.locality = [] # population intensity by groups by tract self.n_location = 0 # length of list (n lines) (attributeMatrix.shape[0]) self.n_group = 0 # number of groups (attributeMatrix.shape[1] - 4) self.costMatrix = [] # scipy cdist distance matrix self.tract_id = [] # tract ids in string format def readAttributesFile(self, filepath): """ This function reads the csv file and populate the class's attributes. Data has to be exactly in the following format or results will be wrong: area id, x_coord, y_coord, attribute 1, attributes 2, attributes 3, attribute n... :param filepath: path with file to be read :return: attribute Matrix [n,n] """ raw_data = np.genfromtxt(filepath, skip_header=1, delimiter=",", filling_values=0, dtype=None) data = [list(item)[1:] for item in raw_data] self.attributeMatrix = np.asmatrix(data) n = self.attributeMatrix.shape[1] self.location = self.attributeMatrix[:, 0:2] self.location = self.location.astype('float') self.pop = self.attributeMatrix[:, 2:n].astype('int') # self.pop[np.where(self.pop < 0)[0], np.where(self.pop < 0)[1]] = 0 self.n_group = n-2 self.n_location = self.attributeMatrix.shape[0] self.pop_sum = np.sum(self.pop, axis=1) self.tract_id = np.asarray([x[0] for x in raw_data]).astype(str) self.tract_id = self.tract_id.reshape((self.n_location, 1)) return self.attributeMatrix def getWeight(self, distance, bandwidth, weightmethod=1): """ This function computes the weights for neighborhood. Default value is Gaussian(1) :param distance: distance in meters to be considered for weighting :param bandwidth: bandwidth in meters selected to perform neighborhood :param weightmethod: method to be used: 1-gussian , 2-bi square and empty-moving windows :return: weight array for internal use """ distance = np.asarray(distance.T) if weightmethod == 1: weight = np.exp((-0.5) * (distance/bandwidth) * (distance/bandwidth)) elif weightmethod == 2: weight = (1 - (distance/bandwidth)*(distance/bandwidth)) * (1 - (distance/bandwidth)*(distance/bandwidth)) sel = np.where(distance > bandwidth) weight[sel[0]] = 0 elif weightmethod == 3: weight = (1 + (distance * 0)) sel = np.where(distance > bandwidth) weight[sel[0]] = 0 else: raise Exception('Invalid weight method selected!') return weight def cal_timeMatrix(self, bandwidth, weightmethod, matrix): """ This function calculate the local population intensity for all groups based on a time matrix. :param bandwidth: bandwidth for neighborhood in meters :param weightmethod: 1 for gaussian, 2 for bi-square and empty for moving window :param matrix: path/file for input time matrix :return: 2d array like with population intensity for all groups """ n_local = self.location.shape[0] n_subgroup = self.pop.shape[1] locality_temp = np.empty([n_local, n_subgroup]) for index in range(0, n_local): for index_sub in range(0, n_subgroup): cost = matrix[index, :].reshape(1, n_local) weight = self.getWeight(cost, bandwidth, weightmethod) locality_temp[index, index_sub] = np.sum(weight * np.asarray(self.pop[:, index_sub])) / np.sum(weight) self.locality = locality_temp self.locality[np.where(self.locality < 0)[0], np.where(self.locality < 0)[1]] = 0 return locality_temp def cal_localityMatrix(self, bandwidth=5000, weightmethod=1): """ This function calculate the local population intensity for all groups. :param bandwidth: bandwidth for neighborhood in meters :param weightmethod: 1 for gaussian, 2 for bi-square and empty for moving window :return: 2d array like with population intensity for all groups """ n_local = self.location.shape[0] n_subgroup = self.pop.shape[1] locality_temp = np.empty([n_local, n_subgroup]) for index in range(0, n_local): for index_sub in range(0, n_subgroup): cost = cdist(self.location[index, :], self.location) weight = self.getWeight(cost, bandwidth, weightmethod) locality_temp[index, index_sub] = np.sum(weight * np.asarray(self.pop[:, index_sub]))/np.sum(weight) self.locality = locality_temp self.locality[np.where(self.locality < 0)[0], np.where(self.locality < 0)[1]] = 0 return locality_temp def cal_localDissimilarity(self): """ Compute local dissimilarity for all groups. :return: 1d array like with results for all groups, size of localities """ if len(self.locality) == 0: lj = np.ravel(self.pop_sum) tjm = np.asarray(self.pop) * 1.0 / lj[:, None] tm = np.sum(self.pop, axis=0) * 1.0 / np.sum(self.pop) index_i = np.sum(np.asarray(tm) * np.asarray(1 - tm)) pop_total = np.sum(self.pop) local_diss = np.sum(1.0 * np.array(np.fabs(tjm - tm)) * np.asarray(self.pop_sum).ravel()[:, None] / (2 * pop_total * index_i), axis=1) else: lj = np.asarray(np.sum(self.locality, axis=1)) tjm = self.locality * 1.0 / lj[:, None] tm = np.sum(self.pop, axis=0) * 1.0 / np.sum(self.pop) index_i = np.sum(np.asarray(tm) * np.asarray(1 - tm)) pop_total = np.sum(self.pop) local_diss = np.sum(1.0 * np.array(np.fabs(tjm - tm)) * np.asarray(self.pop_sum).ravel()[:, None] / (2 * pop_total * index_i), axis=1) local_diss = np.nan_to_num(local_diss) return local_diss def cal_globalDissimilarity(self): """ This function call local dissimilarity and compute the sum from individual values. :return: display global value """ local_diss = self.cal_localDissimilarity() global_diss = np.sum(local_diss) return global_diss def cal_localExposure(self): """ This function computes the local exposure index of group m to group n. in situations where m=n, then the result is the isolation index. :return: 2d list with individual indexes """ m = self.n_group j = self.n_location exposure_rs = np.zeros((j, (m * m))) if len(self.locality) == 0: local_expo = np.asarray(self.pop) * 1.0 / np.asarray(np.sum(self.pop, axis=0)).ravel() locality_rate = np.asarray(self.pop) * 1.0 / np.asarray(np.sum(self.pop, axis=1)).ravel()[:, None] for i in range(m): exposure_rs[:, ((i * m) + 0):((i * m) + m)] = np.asarray(locality_rate) * \ np.asarray(local_expo[:, i]).ravel()[:, None] else: local_expo = np.asarray(self.pop) * 1.0 / np.asarray(np.sum(self.pop, axis=0)).ravel() locality_rate = np.asarray(self.locality) * 1.0 / np.asarray(np.sum(self.locality, axis=1)).ravel()[:, None] for i in range(m): exposure_rs[:, ((i * m) + 0):((i * m) + m)] = np.asarray(locality_rate) * \ np.asarray(local_expo[:, i]).ravel()[:, None] exposure_rs[np.isinf(exposure_rs)] = 0 exposure_rs[np.isnan(exposure_rs)] = 0 return exposure_rs def cal_globalExposure(self): """ This function call local exposure function and sum the results for the global index. :return: displays global number result """ m = self.n_group local_exp = self.cal_localExposure() global_exp = np.sum(local_exp, axis=0) global_exp = global_exp.reshape((m, m)) return global_exp def cal_localEntropy(self): """ This function computes the local entropy score for a unit area Ei (diversity). A unit within the metropolitan area, such as a census tract. If population intensity was previously computed, the spatial version will be returned, else the non spatial version will be selected (raw data). :return: 2d array with local indices """ if len(self.locality) == 0: proportion = np.asarray(self.pop / self.pop_sum) else: polygon_sum = np.sum(self.locality, axis=1).reshape(self.n_location, 1) proportion = np.asarray(self.locality / polygon_sum) entropy = proportion * np.log(1 / proportion) entropy[np.isnan(entropy)] = 0 entropy[np.isinf(entropy)] = 0 entropy = np.sum(entropy, axis=1) entropy = entropy.reshape((self.n_location, 1)) return entropy def cal_globalEntropy(self): """ This function computes the global entropy score E (diversity). A metropolitan area's entropy score. :return: diversity score """ group_score = [] pop_total = np.sum(self.pop_sum) prop = np.asarray(np.sum(self.pop, axis=0))[0] # loop at sum of each population groups for group in prop: group_idx = group / pop_total * np.log(1 / (group / pop_total)) group_score.append(group_idx) entropy = np.sum(group_score) return entropy def cal_localIndexH(self): """ This function computes the local entropy index H for all localities. The functions cal_localEntropy() for local diversity and cal_globalEntropy for global entropy are called as input. If population intensity was previously computed, the spatial version will be returned, else the non spatial version will be selected (raw data). :return: array like with scores for n groups (size groups) """ local_entropy = self.cal_localEntropy() global_entropy = self.cal_globalEntropy() et = global_entropy * np.sum(self.pop_sum) eei = np.asarray(global_entropy - local_entropy) h_local = np.asarray(self.pop_sum) * eei / et return h_local def cal_globalIndexH(self): """ Function to compute global index H returning the sum of local values. The function cal_localIndexH is called as input for sum of individual values. :return: values with global index for each group. """ h_local = self.cal_localIndexH() h_global = np.sum(h_local) return h_global
sandrofsousa/Resolution
Pysegreg/segregationMetrics.py
Python
mit
11,432
[ "Gaussian" ]
4308de787ea4028f75e72b355fd63989d51d397711a77a164dca88083787641d
""" This module contains code to actually perform searches in Goat. Idea is to take a search object, and pointers to the query, record, and results databases. Using the information in the search object, each query/database search is ran and used to generate a new results object in the results db. Each result object is also added to the search object in order to keep track of which results belong to which search. """ import os from tkinter import * from Bio.Blast import NCBIXML from bin.initialize_goat import configs from searches.blast import blast_setup from searches.hmmer import hmmer_setup, hmmer_parser from results import result_obj from gui.searches import threaded_search # Placeholder - should be through settings eventually blast_path = '/usr/local/ncbi/blast/bin' hmmer_path = '/Users/cklinger/src/hmmer-3.1b1-macosx-intel/src' tmp_dir = '/Users/cklinger/git/Goat/tmp' class SearchRunner: """Actually runs searches""" def __init__(self, search_name, search_obj, query_db, record_db, result_db, search_db, mode='new', fwd_search=None, threaded=False, gui=None, no_win=True, owidget=None): self.sobj = search_obj self.qdb = query_db self.rdb = record_db self.udb = result_db self.sdb = search_db self.sdb[search_name] = search_obj self.mode = mode self.fobj = fwd_search self.threaded = threaded # threaded or not self.search_list = [] # for threading searches self.gui = gui # used to close self.no_win = no_win # whether or not to close self.owidget = owidget # signal back to other widget def get_unique_outpath(self, query, db, sep='-'): """Returns an outpath for a given query and database""" out_string = sep.join([query, db, 'out.txt']) if self.sobj.output_location: # not None return os.path.join(self.sobj.output_location, out_string) else: return os.path.join(tmp_dir, out_string) def get_result_id(self, search_name, query, db, sep='-'): """Returns a unique name for each result object""" return sep.join([search_name, query, db]) def run(self): """Runs the search using information in the search object and databases""" for qid in self.sobj.queries: # list of qids if self.mode == 'new': # new search from user input qobj = self.qdb[qid] # fetch associated object from db elif self.mode == 'old': # search from previous search # This loop is kind of gross... maybe don't nest objects within search results? # Alternatively, find a more direct way of getting query without so much looping? qsobj = self.qdb.fetch_search(self.fobj.name) for uid in qsobj.list_entries(): #print(uid) uobj = qsobj.fetch_entry(uid) for query in uobj.list_entries(): #print(query) if query == qid: qobj = uobj.fetch_entry(query) if qobj.target_db: # i.e. is not None if not qobj.target_db in self.sobj.databases: # don't add duplicates self.sobj.databases.append(qobj.target_db) # keep track of databases self.call_run(self.sobj.name, qid, qobj, qobj.target_db) else: # run for all dbs for db in self.sobj.databases: self.call_run(self.sobj.name, qid, qobj, db) if self.threaded: if not self.gui: print('calling popup') popup = Tk() else: popup = self.gui ts = threaded_search.ProgressFrame(self.sobj.algorithm, self.search_list, callback = self.threaded_callback, parent=popup, no_win=self.no_win) ts.run() # store the thread on a global for program awareness configs['threads'].add_thread() else: # now ensure dbs are updated configs['search_db'].commit() configs['result_db'].commit() def call_run(self, sid, qid, qobj, db): """Calls the run_one for each query/db pair""" uniq_out = self.get_unique_outpath(qid, db) result_id = self.get_result_id(sid, qid, db) db_obj = self.rdb[db] for v in db_obj.files.values(): if v.filetype == self.sobj.db_type: dbf = v.filepath # worry about more than one possible file? if self.threaded: self.search_list.append([self.sobj,qid, db, qobj, dbf, uniq_out, self.udb, result_id]) else: self.run_one(qid, db, qobj, dbf, uniq_out, self.udb, result_id) def run_one(self, qid, db, qobj, dbf, outpath, result_db, result_id): """Runs each individual search""" if self.sobj.algorithm == 'blast': if self.sobj.q_type == 'protein' and self.sobj.db_type == 'protein': blast_search = blast_setup.BLASTp(blast_path, qobj, dbf, outpath) else: pass # sort out eventually blast_search.run_from_stdin() elif self.sobj.algorithm == 'hmmer': if self.sobj.q_type == 'protein' and self.sobj.db_type == 'protein': hmmer_search = hmmer_setup.ProtHMMer(hmmer_path, qobj, dbf, outpath) else: pass # sort out eventually hmmer_search.run_from_stdin() robj = result_obj.Result(result_id, self.sobj.algorithm, self.sobj.q_type, self.sobj.db_type, qid, db, self.sobj.name, outpath) #print("Adding {} result to {} search object".format(result_id,self.sobj)) self.sobj.add_result(result_id) # function ensures persistent object updated #print("Adding {} rid and {} robj to result db".format(result_id,robj)) self.udb[result_id] = robj # add to result db def parse(self): """Parses output files from search""" for result in self.sobj.results: robj = self.udb[result] # Parse result first if robj.algorithm == 'blast': blast_result = NCBIXML.read(open(robj.outpath)) robj.parsed_result = blast_result elif robj.algorithm == 'hmmer': # need to sort out prot/nuc later hmmer_result = hmmer_parser.HMMsearchParser(robj.outpath).parse() robj.parsed_result = hmmer_result # Set parsed flag and check for object removal robj.parsed = True if not self.sobj.keep_output: #and robj.parsed: os.remove(robj.outpath) self.udb[result] = robj # add back to db def threaded_callback(self, *robjs): """Takes care of doing things with the completed searches""" #print("Calling thread callback function") # remove thread from global first configs['threads'].remove_thread() try: for robj in robjs: rid = robj.name self.sobj.add_result(rid) self.udb[rid] = robj print('parsing output') self.parse() finally: # commit no matter what? # now ensure dbs are updated configs['search_db'].commit() configs['result_db'].commit() # signal to finish searches if self.owidget: self.owidget._cont()
chris-klinger/Goat
searches/search_runner.py
Python
gpl-3.0
7,582
[ "BLAST" ]
a53924938f8d49c0259e0dc6e59977358340d6d628a6ae17619d1a04974f5005
import random from genesys.generator import NameGenerator, GENDER_MALE, GENDER_FEMALE class AnimatronicNameGenerator(NameGenerator): glue = " " data = { GENDER_MALE: [ [ ["Abalone", "Ace the", "Achilles", "Acro the", "Acrobat", "Admiral", "Ajax the", "Alfie", "Alistair", "Alpha", "Ammo the", "Angel", "Anger the", "Apache the", "Apollo the", "Apple", "Aragog the", "Archer the", "Arrow the", "Artemis", "Artic", "Ash the", "Ashes", "Aslan the", "Asterix", "Astro the", "Athene the", "Atlas", "Aura the", "Avalanche", "Avalon the", "Axe the", "Axel the", "Axis the", "Azrael the"], ["Angel", "Astronaut", "Alligator", "Ant", "Ape", "Anaconda"] ], [ ["Babbit", "Bacon the", "Badger the", "Bailey", "Baltazar the", "Bambam", "Bandit the", "Bane the", "Baron", "Barry", "Basil", "Batista", "Baxter", "Bay the", "Bazal the", "Beacon the", "Beaker the", "Belch the", "Belcher", "Bingo", "Berry", "Beta the", "Big B the", "Bigglesworth", "Biggs the", "Biggy", "Bilbo", "Bing the", "Binky the", "Biscuit the", "Blackjack the", "Blade the", "Blaze the", "Blazer", "Bleach the", "Blight the", "Blister the", "Blitz the", "Blizz the", "Bloats the", "Blob the", "Blood the", "Blue the", "Bluster the", "Bob the", "Bolt the", "Bones the", "Booboo", "Booger the", "Boogy the", "Booker the", "Boomboom", "Boomer the", "Boomerang the", "Booth the", "Boots the", "Bosco the", "Boulder the", "Bounce th", "Bowser the", "Brawn the", "Brock the", "Brownie the", "Bruce the", "Brutus", "Bubba the", "Bubbles the", "Buck the", "Bud the", "Buddy", "Buff the", "Buffles the", "Bullet the", "Bully", "Bumble the", "Buster the", "Butch the", "Butters the", "Button", "Buttons the", "Buzz the"], ["Baboon", "Badger", "Bandicoot", "Bandit", "Bat", "Bear", "Beaver", "Bee", "Bigfoot", "Bird", "Bison", "Boar", "Buffalo"] ], [ ["Caine the", "Calvin the", "Camelot", "Captain", "Casanova the", "Cashew the", "Casper the", "Caspian the", "Catastrophe", "Caveman", "Chaos the", "Clacker the", "Claw the", "Clawde the", "Clawdius", "Clawford the", "Claws the", "Clawz the", "Clicker the", "Clipper the", "Cloud the", "Clyde the", "Coal the", "Cole the", "Coloss the", "Colt the", "Comet the", "Conan the", "Cookie the", "Cosmo the", "Cotton the", "Count", "Courage the", "Cozmo", "Crack the", "Crackle the", "Crash the", "Crazy", "Cream the", "Crook the", "Crooked", "Cruise the", "Crunch the", "Cruncher the", "Crunchy", "Crust the", "Crusty", "Cuddles the", "Cupcake the", "Cupid the", "Kaine the", "Kane the", "Kargo", "Khan the", "Killer", "Kindle the", "King"], ["Camel", "Cat", "Chameleon", "Cobra", "Cockroach", "Cougar", "Cow", "Coyote", "Crab", "Crane", "Croc", "Crow", "Kangaroo", "Koala", "Kobold", "Komodo"] ], [ ["Dagger the", "Dancer the", "Dane the", "Danger the", "Dapper the", "Darby the", "Darcy the", "Darkness the", "Dart the", "Darth the", "Dash the", "Dawson the", "Deacon", "Delta", "Deuce the", "Dexter the", "Diablo the", "Digger the", "Dillon the", "Dimitri the", "Ding", "Ding the", "Dipper the", "Diver the", "Doctor", "Doc te", "Doc", "Dodge the", "Dodger the", "Domino", "Doodle", "Doom", "Doom the", "Dova the", "Dover the", "Dozer the", "Drac the", "Dracula", "Drake the", "Dread the", "Dread", "Drummer the", "Dude the", "Duffy", "Duke", "Dune the", "Dusk the", "Dust the", "Dusty"], ["Dingo", "Demon", "Dwarf", "Deer", "Dino", "Dodo", "Dog", "Donkey", "Dragon", "Duck"] ], [ ["Echo the", "Eclipse the", "Edge the", "Elmo the", "Elwood the", "Equinox the", "Ernie the", "Excalibur the"], ["Elf", "Eagle", "Elephant"] ], [ ["Fable the", "Fang the", "Fangs the", "Farkas the", "Fatty", "Fetch the", "Fiddles the", "Fire", "Fizzle the", "Flapper the", "Flappy", "Flash the", "Flopsie the", "Fluff the", "Fluffy", "Flynn the", "Force", "Forest the", "Forester", "Frankenstein", "Freaky", "Freckles the", "Frenzy the", "Friskie the", "Frisky the", "Frosty the", "Fudge", "Fury", "Fury the", "Fuzz the", "Fuzzy", "Fyre the"], ["Phantom", "Falcon", "Ferret", "Fish", "Flamingo", "Fairy", "Fly", "Fox", "Frog", "Phoenix", "Pheasant"] ], [ ["Gadget the", "Gale the", "Gallop the", "Gambit the", "Garry", "Gargle the", "Gargoyle the", "Genghis", "George the", "Ghost", "Giggle the", "Giggles the", "Gil the", "Gillian", "Gizmo the", "Gloom the", "Glutton the", "Glyde the", "Gnaw the", "Gobbles the", "Goble the", "Godzilla", "Golem the", "Goliath the", "Gouge the", "Grand", "Gray the", "Grayson the", "Griffin the", "Grim the", "Grinch the", "Grog the", "Grouch the", "Grouchy", "Grave", "Grover the", "Grumpy", "Grump the", "Grunt the", "Gumball the", "Gunner the", "Gus the"], ["Gibbon", "Goat", "Goblin", "Ghost", "Griffin", "Goose", "Gopher", "Gator", "Gorilla"] ], [ ["Hades the", "Hambo the", "Hamilton", "Hamlet the", "Hammer the", "Handsome", "Hank the", "Hannibal", "Hardy the", "Harry", "Haven the", "Havoc the", "Havock the", "Hawke the", "Haze the", "Hector", "Hercules the", "Herman the", "Hermit the", "Hershel the", "Hogger the", "Hooch the", "Hopper the", "Hopscotch the", "Houdini", "Hudini", "Hulk", "Hunter the", "Hurley the", "Hyde the", "Hyperion the"], ["Hamster", "Hare", "Hawk", "Hedgehog", "Hippo", "Hog", "Horse", "Hunter", "Hound", "Human", "Hyena"] ], [ ["Jabba the", "Jackson the", "Jaffa the", "Jaws the", "Jax", "Jeckyll the", "Jet the", "Jethro the", "Jingle", "Jitters the", "Judge", "Jumbo the", "Junior", "Juno the"], ["Jackal", "Jaguar", "Giant"] ], [ ["Lad the", "Laddy the", "Laika the", "Lance the", "Lancelot the", "Lash the", "Leaps the", "Leapy the", "Lecter", "Legend the", "Leo the", "Leon the", "Licorice", "Lightning", "Lionel", "Lockhart the", "Lockjaw the", "Logan the", "Loki the", "Lucifer", "Lucky the", "Lupin the", "Lupus the", "Lycan the"], ["Lemming", "Lemur", "Lord", "Leopard", "Lion", "Lizard", "Llama", "Lobster", "Locust", "Lynx"] ], [ ["Macho", "Macho the", "Maddock the", "Madeye", "Magma", "Magnum the", "Magnus the", "Mako the", "Mambo the", "Mammoth", "Marble", "Marlin the", "Marlow the", "Mason the", "Matrix", "Maverick", "Max the", "Maximus", "Mayhem the", "Mello", "Mellow", "Menace the", "Mercury", "Merlin the", "Midas the", "Midnight the", "Miles the", "Mirage the", "Mittens the", "Moe the", "Mohawk", "Momo the", "Monty", "Mort the", "Muds the", "Muffin the", "Murdoch the", "Murky", "Muse the", "Myst the"], ["Macaw", "Mandrill", "Mantis", "Meerkat", "Mage", "Mobster", "Mutant", "Mole", "Mongoose", "Mongrel", "Monkey", "Monster", "Moose", "Moth", "Mouse", "Mule"] ], [ ["Nacho the", "Nanook the", "Nemesis the", "Nemo the", "Nemoo the", "Neo the", "Neptune the", "Nero the", "Newton the", "Nibbler the", "Nibbles the", "Nightmare", "Nightmare the", "Nightshade the", "Nightwing the", "Niles the", "Nocturn the", "Noodle the", "Norbert the", "Norton the", "Nova the", "Nugget the", "Nukem the", "Nyx the"], ["Gnoll", "Gnome", "Numbat", "Nightingale", "Neanderthal", "Knight", "Ninja", "Nymph", "Newt"] ], [ ["Oak the", "Obsidian", "Odin the", "Omega the", "Omega", "Omen the", "Onyx", "Onyx the", "Oreo the", "Orion the", "Otis the", "Outlaw", "Owen the", "Ozzy the"], ["Ocelot", "Oracle", "Orc", "Octopus", "Ogre", "Orc", "Ostrich", "Owl"] ], [ ["Pace the", "Paddington", "Paladin", "Pandora the", "Patch the", "Patches the", "Patriot", "Patton the", "Payne the", "Peanut the", "Pebble the", "Pebbles the", "Pepper the", "Piccolo", "Pickles the", "Pitch the", "Plunge the", "Pogo the", "Poison the", "Popcorn the", "Popeye the", "Poppers the", "Poseidon the", "Pounce the", "Prancer the", "Predator", "Pride the", "Prince", "Prometheus", "Puddle the", "Puddles the", "Pudge the", "Puff the", "Puggy", "Punky", "Pyre the", "Pyro the"], ["Panda", "Panther", "Pirate", "Parrot", "Peacock", "Pelican", "Penguin", "Pig", "Pigeon", "Piranha", "Pony", "Porcupine", "Possum", "Puma"] ], [ ["Rabies the", "Rage", "Ragget the", "Rain the", "Rainbow the", "Ralph the", "Rambo", "Rampage the", "Ranger", "Rascal", "Ray the", "Razor the", "Reaper the", "Rebel", "Rex the", "Rhonin the", "Riggs the", "Ripley the", "Rocky the", "Rogue", "Rogue the", "Rohan the", "Romulus", "Rosco the", "Rover the", "Rowan the", "Rowdy the", "Ruff the", "Rufus the", "Rumble the", "Russell the", "Rusty the", "Rusty"], ["Rabbit", "Ranger", "Rogue", "Raccoon", "Ram", "Rat", "Raven", "Rhino"] ], [ ["Sabath the", "Saber the", "Salt the", "Salty", "Satin the", "Saul the", "Savage the", "Sawyer the", "Scamper the", "Scandal the", "Scar the", "Scooter the", "Scourge the", "Scratches the", "Scratchy the", "Screech the", "Psych the", "Psyche the", "Psycho the", "Scruffy the", "Sebastion", "Shade the", "Shadow the", "Shamrock the", "Shawn the", "Shepherd the", "Sherlock the", "Shimmy the", "Shmooch the", "Shrapnel the", "Shredder the", "Sid the", "Sidney", "Silver the", "Skinner the", "Skipper the", "Skittles the", "Slate the", "Slick the", "Slimes the", "Slinky the", "Sly the", "Smeagol the", "Smiles the", "Smokey the", "Smooch the", "Smudge the", "Snapper the", "Snookums the", "Snowball the", "Snowflake the", "Snuffles the", "Snyder the", "Solace the", "Soots the", "Sparks the", "Sparky the", "Spartacus the", "Spartan the", "Spectre the", "Speedy the", "Spike the", "Spitfire", "Splinter the", "Sprite the", "Spudnik the", "Steele the", "Stitches the", "Summit the", "Sunny the", "Storm the"], ["Salamander", "Satyr", "Scorpion", "Centipede", "Seal", "Shark", "Sheep", "Skunk", "Sloth", "Slug", "Snail", "Snake", "Sparrow", "Centaur", "Scout", "Spy", "Spider", "Squid", "Squirrel", "Stork", "Swallow", "Swan"] ], [ ["Taboo the", "Tad the", "Tango the", "Tank the", "Terror", "Thor the", "Thunder the", "Thunder", "Tiberius", "Tickles the", "Timber the", "Tiny", "Titan the", "Titanium", "Tooth the", "Torment the", "Trace the", "Tremor the", "Triton the", "Triumph the", "Trouble the", "Troy the", "Tumble the", "Tumnus the", "Tweedle the", "Twitch the", "Tyde the", "Tyson the"], ["Tarantula", "Tiger", "Toad", "Tortoise", "Toucan", "Troll", "Turkey", "Turtle"] ], [ ["Vamp the", "Vanilla", "Vapor the", "Vegas the", "Venom the", "Victor", "Vlad the", "Vladimir"], ["Vampire", "Viper", "Vulture"] ], [ ["Waddle the", "Waddles the", "Walnut the", "Ward the", "Warpath the", "Wasabi the", "Wayde the", "Wayne the", "Weirdo the", "Wellington", "Whisper the", "Wicked", "Wiggles the", "Wilburt", "Willow the", "Wolfgang the", "Woods the", "Woody", "Wrath the"], ["Walrus", "Warthog", "Wasp", "Weasel", "Wolf", "Wolverine", "Wombat", "Werewolf", "Wizard", "Woodpecker", "Worm"] ], [ ["Yoghi the", "Yoghurt the", "Yogi the"], ["Yak"] ], [ ["Ziggy the", "Zion the", "Zug the"], ["Zebra"] ] ], GENDER_FEMALE: [ [ ["Abalone", "Abby", "Acadia the", "Aerial the", "Aggie", "Aggy", "Agnes the", "Alexi", "Alexia", "Alexis", "Algee", "Alibi the", "Alize the", "Alpine the", "Amazone the", "Amazonia the", "Amber", "Amethyst the", "Angel the", "Angi", "Angie", "Annabella", "Aphrodite the", "Apple the", "April the", "Aqua", "Ares the", "Aria", "Arial the", "Ariel the", "Arizona", "Artica the", "Ash the", "Ashelia", "Ashes the", "Ashley", "Aspen the", "Astral", "Athena the", "Atilla the", "Atolle the", "Aura", "Aurora the", "Autumn", "Azraelle the", "Azura the", "Azure the", "Azurys the"], ["Angel", "Astronaut", "Alligator", "Ant", "Anaconda", "Ape"] ], [ ["Barbara", "Babe the", "Babes the", "Babette the", "Baby", "Badge the", "Bambi the", "Bambino", "Bandetta the", "Banshee the", "Bash the", "Bashful the", "Bashy the", "Batsy", "Batty", "Beauty the", "Becky", "Belchy the", "Bella", "Belle", "Bernice the", "Bertha the", "Bessy", "Beth the", "Betsy the", "Betty", "Biscuit the", "Bitsy the", "Blaze the", "Blinks the", "Blinky", "Blitz the", "Blitze the", "Blitzen the", "Bloats the", "Blossom the", "Blush the", "Bones the", "Bonnie", "Booboo", "Booboo the", "Boots the", "Boubou", "Bounce the", "Bouncy the", "Brandy", "Breeze the", "Breezy", "Brew the", "Brizzie", "Brooke the", "Brownie the", "Bubble the", "Bubbles the", "Buffy the", "Bullette the", "Bumble the", "Bumbles the", "Bunny the", "Buttercup", "Button the", "Buttons the"], ["Baboon", "Badger", "Bandicoot", "Bandit", "Bat", "Bear", "Beaver", "Bee", "Bigfoot", "Bird", "Bison", "Boar", "Buffalo"] ], [ ["Cake the", "Cakes the", "Calico the", "Calypso the", "Cami the", "Candy", "Capri the", "Cara the", "Caramel", "Caramelle", "Carapace", "Carmen the", "Cascade the", "Clacks the", "Clacky the", "Clarabella", "Clarice the", "Clarity", "Clawdia", "Claws the", "Clemency the", "Clementine", "Cleo the", "Cleopatra", "Clippy the", "Clips the", "Cloe the", "Clover the", "Cobbles the", "Coco the", "Codex the", "Comette the", "Cookie the", "Cora", "Coral the", "Coralia", "Coraline", "Corona", "Cosmo the", "Cotton the", "Crackle the", "Crackles the", "Crash the", "Creepette the", "Crunchey", "Crystal", "Cuddle the", "Cuddles thes", "Cupcake the", "Cushion the", "Cutie", "Karma the", "Kat the", "Kate the", "Kathy", "Kiss the", "Kisses the", "Kitty", "Kylla the"], ["Camel", "Cat", "Chameleon", "Cobra", "Cockroach", "Cougar", "Cow", "Coyote", "Crab", "Crane", "Croc", "Crow", "Kangaroo", "Koala", "Kobold", "Komodo"] ], [ ["Daahling the", "Daffodil the", "Dahlia", "Daisy the", "Dakota the", "Dandy", "Daphne the", "Darla the", "Darling", "Dash the", "Dashful the", "Dawn the", "Dawne the", "Dawnstar the", "Dazzle", "Dee the", "Deedee the", "Delilah the", "Delta the", "Destiny", "Dew the", "Dharma the", "Dirty", "Diva", "Diva the", "Dixie", "Dodger the", "Dolly", "Dora the", "Doris the", "Dot the", "Dots the", "Dottie the", "Dotty the", "Draculette", "Dream the", "Duchess", "Duchess the", "Duffy"], ["Dingo", "Dino", "Dodo", "Demon", "Dwarf", "Deer", "Dog", "Donkey", "Dragon", "Duck"] ], [ ["Ebony", "Echo the", "Eclipse the", "Eek the", "Eep the", "Elain the", "Eleanor", "Ember the", "Enigma the", "Enya the", "Equina the", "Equinox the", "Eve the"], ["Elf", "Eagle", "Elephant"] ], [ ["Faith the", "Fancy", "Fang the", "Fangie the", "Fangs the", "Faune the", "Faye the", "Fiddle the", "Fierra the", "Fire the", "Fizzle the", "Flame", "Flappy", "Flopsy the", "Flower the", "Flubby the", "Fluffy", "Fluffy the", "Flufkins the", "Flutters the", "Fortuna the", "Fortune the", "Frazzle", "Freakey", "Freckles the", "Frizzle the", "Fuzzles the", "Fuzzy", "Fye the", "Fyre the"], ["Phantom", "Falcon", "Ferret", "Fish", "Flamingo", "Fly", "Fox", "Frog", "Phoenix", "Fairy", "Pheasant"] ], [ ["Gadget the", "Gambles the", "Gargles the", "Gemini", "Gemma the", "Geo the", "Gertrude the", "Gia the", "Gidget the", "Giggles the", "Ginger the", "Ginny the", "Gloria", "Gobbles the", "Goldilocks", "Gooey", "Gorgeous the", "Grace the", "Gracie the", "Granny", "Gripes the", "Gummy the", "Gwen"], ["Gibbon", "Ghost", "Griffin", "Goat", "Goblin", "Goose", "Gopher", "Gator", "Gorilla"] ], [ ["Hailey the", "Happy the", "Happy", "Harley", "Harmony the", "Haze the", "Hazel the", "Heather the", "Heiress", "Helen the", "Helena", "Hermi the", "Hermine", "Hermione", "Hinda the", "Hippity", "Hipscotch the", "Honey the", "Hope the", "Hoppity", "Hugsie the", "Huntress the", "Hydris the", "Hymn the", "Hynde the", "Hyve the"], ["Hamster", "Hare", "Hawk", "Hedgehog", "Hippo", "Hog", "Hunter", "Horse", "Hound", "Human", "Hyena"] ], [ ["Jade the", "Jaffa the", "Jasmin the", "Jasmine the", "Jazzy", "Jess the", "Jewel the", "Jinx the", "Jitters the", "Juno the", "Jynx the"], ["Jackal", "Jaguar", "Giant"] ], [ ["Labyrinth the", "Lace the", "Lacy the", "Lady", "Laguna the", "Laika the", "Lana the", "Lane the", "Lavender", "Leaps the", "Leapy the", "Legs the", "Levi", "Lexis the", "Libby the", "Liberty", "Lilly the", "Linsey the", "Lola the", "Lore the", "Lotus the", "Lucky the", "Lucy the", "Lullaby", "Lulu the", "Lumina", "Luna the", "Lyla the", "Lyric the"], ["Lemming", "Lemur", "Leopard", "Lion", "Lizard", "Llama", "Lobster", "Locust", "Lynx"] ], [ ["Mable the", "Mae the", "Maggie", "Magnolia", "Maiden", "Malibu", "Mango the", "Maple the", "Marbles the", "Marigold", "Marinna", "Marsha the", "Martha the", "Maryn the", "Maxima", "Meadow the", "Medusa the", "Melancholy", "Melanie", "Mello", "Mellow", "Melody", "Mercy the", "Midnight the", "Mila the", "Milo the", "Mime the", "Minty the", "Mischief the", "Missy", "Mistress", "Misty the", "Mittens the", "Mocha", "Molly the", "Momma", "Mona the", "Momo the", "Moonbeam the", "Morticia the", "Muffin the", "Muriel", "Mysti the", "Mystique the", "Myth the"], ["Macaw", "Mandrill", "Mage", "Mutant", "Mantis", "Meerkat", "Mole", "Mongoose", "Mongrel", "Monkey", "Monster", "Moose", "Moth", "Mouse", "Mule"] ], [ ["Nahla the", "Nala the", "Nanook the", "Nebula", "Neko the", "Nell the", "Nemo the", "Nemoo the", "Neptuna the", "Nibbles the", "Nighte the", "Nipsey the", "Nixie the", "Noodle the", "Noodles the", "Nora", "Nova the", "Nugget the", "Nutmeg the", "Nymph the", "Nyx the"], ["Gnoll", "Gnome", "Numbat", "Nightingale", "Knight", "Ninja", "Nymph", "Neanderthal", "Newt"] ], [ ["Oasis", "Oasis the", "Oceana the", "Oceane the", "Olive the", "Olympia", "Omen the", "Onyxia the", "Opal the", "Oracle", "Orbit the", "Orchid the", "Oreo the", "Ozone the"], ["Oracle", "Orc", "Ocelot", "Octopus", "Ogre", "Orc", "Ostrich", "Owl"] ], [ ["Pace the", "Pandora the", "Paprika", "Patches the", "Patience the", "Paws the", "Peaches the", "Pearl the", "Pebble the", "Pebbles the", "Peeps the", "Penelope", "Penny the", "Pepper the", "Petunia", "Pickles the", "Pinky the", "Pitch the", "Pixie the", "Poison the", "Pookie the", "Popcorn the", "Poppy the", "Precious the", "Princess", "Prudence the", "Pudge the", "Pudgy the", "Puds the", "Puffy", "Pumpkin the", "Pyro the"], ["Panda", "Panther", "Pirate", "Parrot", "Peacock", "Pelican", "Penguin", "Pig", "Pigeon", "Piranha", "Polar Bear", "Pony", "Porcupine", "Possum", "Puma"] ], [ ["Rags the", "Raidrop the", "Rainbow the", "Raine the", "Raisin the", "Raleigh the", "Razzle the", "Rebel", "Rebel the", "Rhyme the", "Ria", "Ribbon the", "Ripley the", "Ripple", "Ripples the", "Riva", "River the", "Robin", "Rogue the", "Rogue", "Rose the", "Rosemary", "Rosie the", "Roxy", "Ruby the", "Rune the", "Ruth the"], ["Rabbit", "Ranger", "Rogue", "Raccoon", "Ram", "Rat", "Raven", "Rhino"] ], [ ["Sable the", "Sabre the", "Sabrina", "Sade the", "Saffron the", "Sage the", "Sally", "Salmone the", "Sandy the", "Sanguine the", "Sapphire", "Satin the", "Savanah the", "Scarlet the", "Psyche the", "Scratches the", "Scruffles the", "Selena", "Serenity", "Shade the", "Shadow the", "Shaye the", "Shelob the", "Shiba the", "Shmooches the", "Shye the", "Siera the", "Silver the", "Siren the", "Sirena", "Skylar the", "Sludges the", "Smooches the", "Smudges the", "Snappy the", "Snickers the", "Snoots the", "Snowball the", "Snuffles the", "Snuggles the", "Sona", "Sora the", "Sparkles the", "Speckles the", "Spice the", "Spindle the", "Squiggles the", "Stitches the", "Storme the", "Strawberry", "Stripes the", "Stuffles the", "Sugar", "Summer", "Sweetie", "Sweetpea the"], ["Salamander", "Satyr", "Scorpion", "Centipede", "Seal", "Shark", "Sheep", "Skunk", "Sloth", "Slug", "Snail", "Snake", "Centaur", "Scout", "Spy", "Sparrow", "Spider", "Squid", "Squirrel", "Stork", "Swallow", "Swan"] ], [ ["Tabby the", "Tabitha", "Tawny the", "Teeny the", "Termina the", "Thistle the", "Tibby the", "Tickles the", "Tiggles the", "Tilly the", "Tinkerbell", "Tinkerbelle", "Tiny", "Theresa", "Toffee the", "Toots the", "Tootsie the", "Trixie the", "Trixy the", "Truffles the", "Tulip the", "Twiggy the", "Twinkie the", "Twinkles the", "Tyra the"], ["Tarantula", "Tiger", "Toad", "Tortoise", "Toucan", "Troll", "Turkey", "Turtle"] ], [ ["Valentine", "Vanilla the", "Vanity", "Vapor the", "Velvet the", "Venom the", "Venus the", "Victoria", "Viola", "Violet the", "Vixen the"], ["Viper", "Vampire", "Vulture"] ], [ ["Waddles the", "Waffles the", "Wendy", "Whisper the", "Wiggles the", "Wilde the", "Willow the", "Winter the", "Wobbles the"], ["Walrus", "Warthog", "Wasp", "Weasel", "Wolf", "Wolverine", "Wombat", "Werewolf", "Witch", "Woodpecker", "Worm"] ], [ ["Yoghi the", "Yoghurt the", "Yogi the"], ["Yak"] ], [ ["Zelda the", "Ziggy the", "Zippy the", "Zoe the"], ["Zebra"] ] ], } @classmethod def generate_parts(cls, gender=GENDER_MALE): return [random.choice(parts) for parts in random.choice(cls.data[gender])] def animatronic_names_generate(gender=GENDER_MALE): return AnimatronicNameGenerator.generate(gender)
d2emon/generator-pack
src/genesys/generator/fng/name/fantasy/animatronic.py
Python
gpl-3.0
25,393
[ "Amber", "CRYSTAL", "Jaguar", "MOE", "MOOSE", "Octopus" ]
b6f53cb8c4251fdd26b361edccaab7f3603454fe986cb339593ec1e24c261b39
#!/usr/bin/env python from __future__ import absolute_import import re from markdown import Markdown from markdown.util import AMP_SUBSTITUTE, HTML_PLACEHOLDER_RE from markdown.odict import OrderedDict from docutils import nodes from docutils import parsers try: from html import entities except ImportError: import htmlentitydefs as entities MAILTO = ('\x02amp\x03#109;\x02amp\x03#97;\x02amp\x03#105;\x02amp\x03#108;' '\x02amp\x03#116;\x02amp\x03#111;\x02amp\x03#58;\x02') INLINE_NODES = ( nodes.emphasis, nodes.strong, nodes.literal, nodes.reference, nodes.image, ) HAVING_BLOCK_NODE = ( nodes.list_item, ) class SectionPostprocessor(object): def run(self, node): i = 0 while i < len(node): if isinstance(node[i], nodes.section): for subnode in node[i + 1:]: if isinstance(subnode, nodes.section) and subnode['level'] == node[i]['level']: break node.remove(subnode) node[i] += subnode self.run(node[i]) i += 1 return node class StripPostprocessor(object): def run(self, node): class FakeStripper(object): def strip(self): return node return FakeStripper() def unescape_email(text): result = [] n = len(AMP_SUBSTITUTE) for char in text.split(';'): if char.startswith(AMP_SUBSTITUTE + "#"): result.append(chr(int(char[n + 1:]))) elif char.startswith(AMP_SUBSTITUTE): result.append(entities.name2codepoint.get(char[n:])) else: result.append(char) return ''.join(result) class Serializer(object): def __init__(self, markdown): self.markdown = markdown def __call__(self, element): return self.visit(element) def visit(self, element): method = "visit_%s" % element.tag if not hasattr(self, method): raise RuntimeError('Unknown element: %r' % element) else: return getattr(self, method)(element) def unescape_char(self, text, rawHtml=False): def unescape(matched): return chr(int(matched.group(1))) def expand_rawhtml(matched): html_id = int(matched.group(1)) html, safe = self.markdown.htmlStash.rawHtmlBlocks[html_id] if rawHtml or re.match(r'(&[\#a-zA-Z0-9]*;)', html): return html # unescape HTML entities only else: return matched.group(0) text = re.sub('\x02(\d\d)\x03', unescape, text) text = HTML_PLACEHOLDER_RE.sub(expand_rawhtml, text) return text def make_node(self, cls, element): node = cls() having_block_node = cls in HAVING_BLOCK_NODE if element.text and element.text != "\n": text = self.unescape_char(element.text) if HTML_PLACEHOLDER_RE.search(text): html_text = self.unescape_char(text, rawHtml=True) if html_text.startswith("<!--math"): g = re.match(r"<!--math(.*?)-->", html_text, re.DOTALL) if g: node += nodes.math( text=g.group(1).strip(), latex=g.group(1).strip() ) else: node += nodes.raw(format='html', text=html_text) elif having_block_node: node += nodes.paragraph(text=text) else: node += nodes.Text(text) for child in element: subnode = self.visit(child) if having_block_node and isinstance(subnode, INLINE_NODES): all_nodes_is_in_paragraph = True if len(node) == 0: node += nodes.paragraph() node[0] += subnode else: all_nodes_is_in_paragraph = False node += subnode if child.tail and child.tail != "\n": tail = self.unescape_char(child.tail) if HTML_PLACEHOLDER_RE.search(tail): node += nodes.raw(format='html', text=tail) elif all_nodes_is_in_paragraph: node[0] += nodes.Text(tail) elif having_block_node: node += nodes.paragraph(text=tail) else: node += nodes.Text(tail) return node def visit_div(self, element): return self.make_node(nodes.container, element) def visit_headings(self, element): section = nodes.section(level=int(element.tag[1])) section += self.make_node(nodes.title, element) return section visit_h1 = visit_headings visit_h2 = visit_headings visit_h3 = visit_headings visit_h4 = visit_headings visit_h5 = visit_headings visit_h6 = visit_headings def visit_p(self, element): return self.make_node(nodes.paragraph, element) def visit_em(self, element): return self.make_node(nodes.emphasis, element) def visit_strong(self, element): return self.make_node(nodes.strong, element) def visit_code(self, element): return nodes.literal(text=self.unescape_char(element.text)) def visit_a(self, element): refnode = self.make_node(nodes.reference, element) href = element.get('href') if href: if href.startswith(MAILTO): refnode['refuri'] = unescape_email(href) if href.endswith(refnode[0]): refnode.pop(0) refnode.insert(0, nodes.Text(refnode['refuri'][7:])) # strip mailto: else: refnode['refuri'] = href if element.get('title'): refnode['reftitle'] = self.unescape_char(element.get('title')) return refnode def visit_img(self, element): image = self.make_node(nodes.image, element) if element.get('alt'): image['alt'] = self.unescape_char(element.get('alt')) if element.get('src'): image['uri'] = self.unescape_char(element.get('src')) if element.get('title'): # FIXME: Sphinx does not process reftitle attribute image['reftitle'] = self.unescape_char(element.get('title')) return image def visit_ul(self, element): return self.make_node(nodes.bullet_list, element) def visit_ol(self, element): return self.make_node(nodes.enumerated_list, element) def visit_li(self, element): return self.make_node(nodes.list_item, element) def visit_pre(self, element): return nodes.literal_block(text=self.unescape_char(element[0].text)) def visit_blockquote(self, element): return self.make_node(nodes.literal_block, element) def visit_br(self, _): return nodes.raw(format='html', text="<br/>") def visit_table(self, element): headers = [] rows = [[]] for ch_element in element.iter(): if ch_element.tag == "th": headers.append(ch_element.text) elif ch_element.tag == "td": rows[-1].append((ch_element.text, ch_element.attrib.get("align"))) elif ch_element.tag == "tr": if rows[-1]: rows.append([]) # Not: http://agateau.com/2015/docutils-snippets/ table_node = nodes.table() tgroup_node = nodes.tgroup(cols=len(headers)) table_node += tgroup_node # add colspec for x in range(len(headers)): tgroup_node += nodes.colspec(colwidth=1) # add thead thead_node = nodes.thead() tgroup_node += thead_node header_row_node = nodes.row() thead_node += header_row_node for header in headers: entry = nodes.entry() header_row_node += entry entry += nodes.paragraph(text=header) # add tbody tbody_node = nodes.tbody() tgroup_node += tbody_node for row in rows: row_node = nodes.row() for text, align in row: entry = nodes.entry() row_node += entry entry += nodes.paragraph(text=text, align=align) tbody_node += row_node return table_node def md2node(text): md = Markdown(["gfm"]) md.serializer = Serializer(md) md.stripTopLevelTags = False md.postprocessors = OrderedDict() md.postprocessors['section'] = SectionPostprocessor() md.postprocessors['strip'] = StripPostprocessor() text = preprocess(text) return md.convert(text) def preprocess(text): parse_re = re.compile("^\s*```\s*math\s*$") end_re = re.compile("^\s*```\s*$") new_lines = [] for line in text.splitlines(): if parse_re.match(line): new_lines += ["<!--math"] elif end_re.match(line): new_lines += ["-->"] else: new_lines += [line] return "\n".join(new_lines) class MarkdownParser(parsers.Parser): def parse(self, inputstring, document): self.setup_parse(inputstring, document) self.document = document for node in md2node(inputstring): self.document += node # assign IDs to all sections for node in self.document.traverse(nodes.section): self.document.note_implicit_target(node) self.finish_parse()
pashango2/sphinx-explorer
sphinx_explorer/settings/extensions/github_markdown.py
Python
mit
9,563
[ "VisIt" ]
7497ab776c5a783410ea96a8df5e3e88ebc812a016211476ec3db5f9f10ec9f6
import numpy from scipy import integrate _ERASESTR= " " def localfehdist(feh): #From 2 Gaussian XD fit to Casagrande et al. (2011) fehdist= 0.8/0.15*numpy.exp(-0.5*(feh-0.016)**2./0.15**2.)\ +0.2/0.22*numpy.exp(-0.5*(feh+0.15)**2./0.22**2.) return fehdist def zsolar(): return 0.017 def int_newton_cotes(x,f,p=5): def newton_cotes(x, f): if x.shape[0] < 2: return 0 rn = (x.shape[0]-1)*(x-x[0])/(x[-1]-x[0]) # Just making sure ... rn[0]= 0 rn[-1]= len(rn)-1 weights= integrate.newton_cotes(rn)[0] return (x[-1]-x[0])/(x.shape[0]-1)*numpy.dot(weights,f) ret = 0 for indx in range(0,x.shape[0],p-1): ret+= newton_cotes(x[indx:indx+p],f[indx:indx+p]) return ret
jobovy/apogee
apogee/util/__init__.py
Python
bsd-3-clause
856
[ "Gaussian" ]
9ec9b01b4680cc18761b5b25d8092acbb77380b0db403ce4aab3d37b2e322014
""" SIMD vector nodes supported by ctree. """ from ctree.nodes import CtreeNode class SimdNode(CtreeNode): """Base class for all SIMD nodes supported by ctree.""" def codegen(self, indent=0): from ctree.sse.codegen import SimdCodeGen return SimdCodeGen(indent).visit(self) def label(self): from ctree.sse.dotgen import SimdDotLabeller return SimdDotLabeller().visit(self)
ucb-sejits/ctree
ctree/simd/nodes.py
Python
bsd-2-clause
423
[ "VisIt" ]
d228999dfb9a3cc7db7523da09a128cf7c245e603771b8ef3c2d1abf67361c47
""" This module attempts to make it easy to create VTK-Python unittests. The module uses unittest for the test interface. For more documentation on what unittests are and how to use them, please read these: http://www.python.org/doc/current/lib/module-unittest.html http://www.diveintopython.org/roman_divein.html This VTK-Python test module supports image based tests with multiple images per test suite and multiple images per individual test as well. It also prints information appropriate for CDash (http://open.kitware.com/). This module defines several useful classes and functions to make writing tests easy. The most important of these are: class vtkTest: Subclass this for your tests. It also has a few useful internal functions that can be used to do some simple blackbox testing. compareImage(renwin, img_fname, threshold=10): Compares renwin with image and generates image if it does not exist. The threshold determines how closely the images must match. The function also handles multiple images and finds the best matching image. compareImageWithSavedImage(src_img, img_fname, threshold=10): Compares given source image (in the form of a vtkImageData) with saved image and generates the image if it does not exist. The threshold determines how closely the images must match. The function also handles multiple images and finds the best matching image. getAbsImagePath(img_basename): Returns the full path to the image given the basic image name. main(cases): Does the testing given a list of tuples containing test classes and the starting string of the functions used for testing. interact(): Interacts with the user if necessary. The behavior of this is rather trivial and works best when using Tkinter. It does not do anything by default and stops to interact with the user when given the appropriate command line arguments. isInteractive(): If interact() is not good enough, use this to find if the mode is interactive or not and do whatever is necessary to generate an interactive view. Examples: The best way to learn on how to use this module is to look at a few examples. The end of this file contains a trivial example. Please also look at the following examples: Rendering/Testing/Python/TestTkRenderWidget.py, Rendering/Testing/Python/TestTkRenderWindowInteractor.py Created: September, 2002 Prabhu Ramachandran <prabhu@aero.iitb.ac.in> """ import sys, os, time import os.path import unittest, getopt import vtk import BlackBox # location of the VTK data files. Set via command line args or # environment variable. VTK_DATA_ROOT = "" # location of the VTK baseline images. Set via command line args or # environment variable. VTK_BASELINE_ROOT = "" # location of the VTK difference images for failed tests. Set via # command line args or environment variable. VTK_TEMP_DIR = "" # Verbosity of the test messages (used by unittest) _VERBOSE = 0 # Determines if it is necessary to interact with the user. If zero # dont interact if 1 interact. Set via command line args _INTERACT = 0 # This will be set to 1 when the image test will not be performed. # This option is used internally by the script and set via command # line arguments. _NO_IMAGE = 0 class vtkTest(unittest.TestCase): """A simple default VTK test class that defines a few useful blackbox tests that can be readily used. Derive your test cases from this class and use the following if you'd like to. Note: Unittest instantiates this class (or your subclass) each time it tests a method. So if you do not want that to happen when generating VTK pipelines you should create the pipeline in the class definition as done below for _blackbox. """ _blackbox = BlackBox.Tester(debug=0) # Due to what seems to be a bug in python some objects leak. # Avoid the exit-with-error in vtkDebugLeaks. dl = vtk.vtkDebugLeaks() dl.SetExitError(0) dl = None def _testParse(self, obj): """Does a blackbox test by attempting to parse the class for its various methods using vtkMethodParser. This is a useful test because it gets all the methods of the vtkObject, parses them and sorts them into different classes of objects.""" self._blackbox.testParse(obj) def _testGetSet(self, obj, excluded_methods=[]): """Checks the Get/Set method pairs by setting the value using the current state and making sure that it equals the value it was originally. This effectively calls _testParse internally. """ self._blackbox.testGetSet(obj, excluded_methods) def _testBoolean(self, obj, excluded_methods=[]): """Checks the Boolean methods by setting the value on and off and making sure that the GetMethod returns the the set value. This effectively calls _testParse internally. """ self._blackbox.testBoolean(obj, excluded_methods) def interact(): """Interacts with the user if necessary. """ global _INTERACT if _INTERACT: raw_input("\nPress Enter/Return to continue with the testing. --> ") def isInteractive(): """Returns if the currently chosen mode is interactive or not based on command line options.""" return _INTERACT def getAbsImagePath(img_basename): """Returns the full path to the image given the basic image name.""" global VTK_BASELINE_ROOT return os.path.join(VTK_BASELINE_ROOT, img_basename) def _getTempImagePath(img_fname): x = os.path.join(VTK_TEMP_DIR, os.path.split(img_fname)[1]) return os.path.abspath(x) def compareImageWithSavedImage(src_img, img_fname, threshold=10): """Compares a source image (src_img, which is a vtkImageData) with the saved image file whose name is given in the second argument. If the image file does not exist the image is generated and stored. If not the source image is compared to that of the figure. This function also handles multiple images and finds the best matching image. """ global _NO_IMAGE if _NO_IMAGE: return f_base, f_ext = os.path.splitext(img_fname) if not os.path.isfile(img_fname): # generate the image pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(img_fname)) pngw.SetInputConnection(src_img.GetOutputPort()) pngw.Write() _printCDashImageNotFoundError(img_fname) msg = "Missing baseline image: " + img_fname + "\nTest image created: " + _getTempImagePath(img_fname) sys.tracebacklimit = 0 raise RuntimeError, msg pngr = vtk.vtkPNGReader() pngr.SetFileName(img_fname) pngr.Update() idiff = vtk.vtkImageDifference() idiff.SetInputConnection(src_img.GetOutputPort()) idiff.SetImageConnection(pngr.GetOutputPort()) idiff.Update() min_err = idiff.GetThresholdedError() img_err = min_err err_index = 0 count = 0 if min_err > threshold: count = 1 test_failed = 1 err_index = -1 while 1: # keep trying images till we get the best match. new_fname = f_base + "_%d.png"%count if not os.path.exists(new_fname): # no other image exists. break # since file exists check if it matches. pngr.SetFileName(new_fname) pngr.Update() idiff.Update() alt_err = idiff.GetThresholdedError() if alt_err < threshold: # matched, err_index = count test_failed = 0 min_err = alt_err img_err = alt_err break else: if alt_err < min_err: # image is a better match. err_index = count min_err = alt_err img_err = alt_err count = count + 1 # closes while loop. if test_failed: _handleFailedImage(idiff, pngr, img_fname) # Print for CDash. _printCDashImageError(img_err, err_index, f_base) msg = "Failed image test: %f\n"%idiff.GetThresholdedError() sys.tracebacklimit = 0 raise RuntimeError, msg # output the image error even if a test passed _printCDashImageSuccess(img_err, err_index) def compareImage(renwin, img_fname, threshold=10): """Compares renwin's (a vtkRenderWindow) contents with the image file whose name is given in the second argument. If the image file does not exist the image is generated and stored. If not the image in the render window is compared to that of the figure. This function also handles multiple images and finds the best matching image. """ global _NO_IMAGE if _NO_IMAGE: return w2if = vtk.vtkWindowToImageFilter() w2if.ReadFrontBufferOff() w2if.SetInput(renwin) w2if.Update() try: compareImageWithSavedImage(w2if, img_fname, threshold) except RuntimeError: w2if.ReadFrontBufferOn() compareImageWithSavedImage(w2if, img_fname, threshold) return def _printCDashImageError(img_err, err_index, img_base): """Prints the XML data necessary for CDash.""" img_base = _getTempImagePath(img_base) print "Failed image test with error: %f"%img_err print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">", print "%f </DartMeasurement>"%img_err if err_index <= 0: print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>", else: print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">", print "%d </DartMeasurement>"%err_index print "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.png') print "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.diff.png') print "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">", print "%s </DartMeasurementFile>"%(img_base + '.valid.png') def _printCDashImageNotFoundError(img_fname): """Prints the XML data necessary for Dart when the baseline image is not found.""" print "<DartMeasurement name=\"ImageNotFound\" type=\"text/string\">" + img_fname + "</DartMeasurement>" def _printCDashImageSuccess(img_err, err_index): "Prints XML data for Dart when image test succeeded." print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">", print "%f </DartMeasurement>"%img_err if err_index <= 0: print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>", else: print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">", print "%d </DartMeasurement>"%err_index def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write the difference image gamma adjusted for the dashboard. gamma = vtk.vtkImageShiftScale() gamma.SetInputConnection(idiff.GetOutputPort()) gamma.SetShift(0) gamma.SetScale(10) pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInputConnection(gamma.GetOutputPort()) pngw.Write() # Write out the image that was generated. Write it out as full so that # it may be used as a baseline image if the tester deems it valid. pngw.SetInputConnection(idiff.GetInputConnection(0,0)) pngw.SetFileName(_getTempImagePath(f_base + ".png")) pngw.Write() # write out the valid image that matched. pngw.SetInputConnection(idiff.GetInputConnection(1,0)) pngw.SetFileName(_getTempImagePath(f_base + ".valid.png")) pngw.Write() def main(cases): """ Pass a list of tuples containing test classes and the starting string of the functions used for testing. Example: main ([(vtkTestClass, 'test'), (vtkTestClass1, 'test')]) """ processCmdLine() timer = vtk.vtkTimerLog() s_time = timer.GetCPUTime() s_wall_time = time.time() # run the tests result = test(cases) tot_time = timer.GetCPUTime() - s_time tot_wall_time = float(time.time() - s_wall_time) # output measurements for CDash print "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">", print " %f </DartMeasurement>"%tot_wall_time print "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">", print " %f </DartMeasurement>"%tot_time # Delete these to eliminate debug leaks warnings. del cases, timer if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) def test(cases): """ Pass a list of tuples containing test classes and the functions used for testing. It returns a unittest._TextTestResult object. Example: test = test_suite([(vtkTestClass, 'test'), (vtkTestClass1, 'test')]) """ # Make the test suites from the arguments. suites = [] for case in cases: suites.append(unittest.makeSuite(case[0], case[1])) test_suite = unittest.TestSuite(suites) # Now run the tests. runner = unittest.TextTestRunner(verbosity=_VERBOSE) result = runner.run(test_suite) return result def usage(): msg="""Usage:\nTestScript.py [options]\nWhere options are:\n -D /path/to/VTKData --data-dir /path/to/VTKData Directory containing VTK Data use for tests. If this option is not set via the command line the environment variable VTK_DATA_ROOT is used. If the environment variable is not set the value defaults to '../../../../../VTKData'. -B /path/to/valid/image_dir/ --baseline-root /path/to/valid/image_dir/ This is a path to the directory containing the valid images for comparison. If this option is not set via the command line the environment variable VTK_BASELINE_ROOT is used. If the environment variable is not set the value defaults to the same value set for -D (--data-dir). -T /path/to/valid/temporary_dir/ --temp-dir /path/to/valid/temporary_dir/ This is a path to the directory where the image differences are written. If this option is not set via the command line the environment variable VTK_TEMP_DIR is used. If the environment variable is not set the value defaults to '../../../../Testing/Temporary'. -v level --verbose level Sets the verbosity of the test runner. Valid values are 0, 1, and 2 in increasing order of verbosity. -I --interact Interacts with the user when chosen. If this is not chosen the test will run and exit as soon as it is finished. When enabled, the behavior of this is rather trivial and works best when the test uses Tkinter. -n --no-image Does not do any image comparisons. This is useful if you want to run the test and not worry about test images or image failures etc. -h --help Prints this message. """ return msg def parseCmdLine(): arguments = sys.argv[1:] options = "B:D:T:v:hnI" long_options = ['baseline-root=', 'data-dir=', 'temp-dir=', 'verbose=', 'help', 'no-image', 'interact'] try: opts, args = getopt.getopt(arguments, options, long_options) except getopt.error, msg: print usage() print '-'*70 print msg sys.exit (1) return opts, args def processCmdLine(): opts, args = parseCmdLine() global VTK_DATA_ROOT, VTK_BASELINE_ROOT, VTK_TEMP_DIR global _VERBOSE, _NO_IMAGE, _INTERACT # setup defaults try: VTK_DATA_ROOT = os.environ['VTK_DATA_ROOT'] except KeyError: VTK_DATA_ROOT = os.path.normpath("../../../../../VTKData") try: VTK_BASELINE_ROOT = os.environ['VTK_BASELINE_ROOT'] except KeyError: pass try: VTK_TEMP_DIR = os.environ['VTK_TEMP_DIR'] except KeyError: VTK_TEMP_DIR = os.path.normpath("../../../../Testing/Temporary") for o, a in opts: if o in ('-D', '--data-dir'): VTK_DATA_ROOT = os.path.abspath(a) if o in ('-B', '--baseline-root'): VTK_BASELINE_ROOT = os.path.abspath(a) if o in ('-T', '--temp-dir'): VTK_TEMP_DIR = os.path.abspath(a) if o in ('-n', '--no-image'): _NO_IMAGE = 1 if o in ('-I', '--interact'): _INTERACT = 1 if o in ('-v', '--verbose'): try: _VERBOSE = int(a) except: msg="Verbosity should be an integer. 0, 1, 2 are valid." print msg sys.exit(1) if o in ('-h', '--help'): print usage() sys.exit() if not VTK_BASELINE_ROOT: # default value. VTK_BASELINE_ROOT = VTK_DATA_ROOT if __name__ == "__main__": ###################################################################### # A Trivial test case to illustrate how this module works. class SampleTest(vtkTest): obj = vtk.vtkActor() def testParse(self): "Test if class is parseable" self._testParse(self.obj) def testGetSet(self): "Testing Get/Set methods" self._testGetSet(self.obj) def testBoolean(self): "Testing Boolean methods" self._testBoolean(self.obj) # Test with the above trivial sample test. main( [ (SampleTest, 'test') ] )
msmolens/VTK
Wrapping/Python/vtk/test/Testing.py
Python
bsd-3-clause
17,878
[ "VTK" ]
a36abf9efeadcf79e3b3f0c48d502df3e33de9908f084be631d543f6f101e3f4
# -*- coding: utf-8 -*- # Copyright: (c) 2017, Cisco and/or its affiliates. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from ansible.module_utils.basic import env_fallback from ansible.module_utils.urls import open_url from ansible.module_utils._text import to_text import json import re try: unicode HAVE_UNICODE = True except NameError: unicode = str HAVE_UNICODE = False nso_argument_spec = dict( url=dict(type='str', required=True), username=dict(type='str', required=True, fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), password=dict(type='str', required=True, no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD'])), timeout=dict(type='int', default=300), validate_certs=dict(type='bool', default=False) ) class State(object): SET = 'set' PRESENT = 'present' ABSENT = 'absent' CHECK_SYNC = 'check-sync' DEEP_CHECK_SYNC = 'deep-check-sync' IN_SYNC = 'in-sync' DEEP_IN_SYNC = 'deep-in-sync' SYNC_STATES = ('check-sync', 'deep-check-sync', 'in-sync', 'deep-in-sync') class ModuleFailException(Exception): def __init__(self, message): super(ModuleFailException, self).__init__(message) self.message = message class NsoException(Exception): def __init__(self, message, error): super(NsoException, self).__init__(message) self.message = message self.error = error class JsonRpc(object): def __init__(self, url, timeout, validate_certs): self._url = url self._timeout = timeout self._validate_certs = validate_certs self._id = 0 self._trans = {} self._headers = {'Content-Type': 'application/json'} self._conn = None self._system_settings = {} def login(self, user, passwd): payload = { 'method': 'login', 'params': {'user': user, 'passwd': passwd} } resp, resp_json = self._call(payload) self._headers['Cookie'] = resp.headers['set-cookie'] def logout(self): payload = {'method': 'logout', 'params': {}} self._call(payload) def get_system_setting(self, setting): if setting not in self._system_settings: payload = {'method': 'get_system_setting', 'params': {'operation': setting}} resp, resp_json = self._call(payload) self._system_settings[setting] = resp_json['result'] return self._system_settings[setting] def new_trans(self, **kwargs): payload = {'method': 'new_trans', 'params': kwargs} resp, resp_json = self._call(payload) return resp_json['result']['th'] def delete_trans(self, th): payload = {'method': 'delete_trans', 'params': {'th': th}} resp, resp_json = self._call(payload) def validate_trans(self, th): payload = {'method': 'validate_trans', 'params': {'th': th}} resp, resp_json = self._write_call(payload) return resp_json['result'] def get_trans_changes(self, th): payload = {'method': 'get_trans_changes', 'params': {'th': th}} resp, resp_json = self._write_call(payload) return resp_json['result']['changes'] def validate_commit(self, th): payload = {'method': 'validate_commit', 'params': {'th': th}} resp, resp_json = self._write_call(payload) return resp_json['result'].get('warnings', []) def commit(self, th): payload = {'method': 'commit', 'params': {'th': th}} resp, resp_json = self._write_call(payload) return resp_json['result'] def get_schema(self, **kwargs): payload = {'method': 'get_schema', 'params': kwargs} resp, resp_json = self._read_call(payload) return resp_json['result'] def get_module_prefix_map(self): payload = {'method': 'get_module_prefix_map', 'params': {}} resp, resp_json = self._call(payload) return resp_json['result'] def get_value(self, path): payload = { 'method': 'get_value', 'params': {'path': path} } resp, resp_json = self._read_call(payload) return resp_json['result'] def exists(self, path): payload = {'method': 'exists', 'params': {'path': path}} try: resp, resp_json = self._read_call(payload) return resp_json['result']['exists'] except NsoException as ex: # calling exists on a sub-list when the parent list does # not exists will cause data.not_found errors on recent # NSO if 'type' in ex.error and ex.error['type'] == 'data.not_found': return False raise def create(self, th, path): payload = {'method': 'create', 'params': {'th': th, 'path': path}} self._write_call(payload) def delete(self, th, path): payload = {'method': 'delete', 'params': {'th': th, 'path': path}} self._write_call(payload) def set_value(self, th, path, value): payload = { 'method': 'set_value', 'params': {'th': th, 'path': path, 'value': value} } resp, resp_json = self._write_call(payload) return resp_json['result'] def show_config(self, path, operational=False): payload = { 'method': 'show_config', 'params': { 'path': path, 'result_as': 'json', 'with_oper': operational} } resp, resp_json = self._read_call(payload) return resp_json['result'] def query(self, xpath, fields): payload = { 'method': 'query', 'params': { 'xpath_expr': xpath, 'selection': fields } } resp, resp_json = self._read_call(payload) return resp_json['result']['results'] def run_action(self, th, path, params=None): if params is None: params = {} if is_version(self, [(4, 5), (4, 4, 3)]): result_format = 'json' else: result_format = 'normal' payload = { 'method': 'run_action', 'params': { 'format': result_format, 'path': path, 'params': params } } if th is None: resp, resp_json = self._read_call(payload) else: payload['params']['th'] = th resp, resp_json = self._call(payload) if result_format == 'normal': # this only works for one-level results, list entries, # containers etc will have / in their name. result = {} for info in resp_json['result']: result[info['name']] = info['value'] else: result = resp_json['result'] return result def _call(self, payload): self._id += 1 if 'id' not in payload: payload['id'] = self._id if 'jsonrpc' not in payload: payload['jsonrpc'] = '2.0' data = json.dumps(payload) resp = open_url( self._url, timeout=self._timeout, method='POST', data=data, headers=self._headers, validate_certs=self._validate_certs) if resp.code != 200: raise NsoException( 'NSO returned HTTP code {0}, expected 200'.format(resp.status), {}) resp_body = to_text(resp.read()) resp_json = json.loads(resp_body) if 'error' in resp_json: self._handle_call_error(payload, resp_json) return resp, resp_json def _handle_call_error(self, payload, resp_json): method = payload['method'] error = resp_json['error'] error_type = error['type'][len('rpc.method.'):] if error_type in ('unexpected_params', 'unknown_params_value', 'invalid_params', 'invalid_params_type', 'data_not_found'): key = error['data']['param'] error_type_s = error_type.replace('_', ' ') if key == 'path': msg = 'NSO {0} {1}. path = {2}'.format( method, error_type_s, payload['params']['path']) else: path = payload['params'].get('path', 'unknown') msg = 'NSO {0} {1}. path = {2}. {3} = {4}'.format( method, error_type_s, path, key, payload['params'][key]) else: msg = 'NSO {0} returned JSON-RPC error: {1}'.format(method, error) raise NsoException(msg, error) def _read_call(self, payload): if 'th' not in payload['params']: payload['params']['th'] = self._get_th(mode='read') return self._call(payload) def _write_call(self, payload): if 'th' not in payload['params']: payload['params']['th'] = self._get_th(mode='read_write') return self._call(payload) def _get_th(self, mode='read'): if mode not in self._trans: th = self.new_trans(mode=mode) self._trans[mode] = th return self._trans[mode] class ValueBuilder(object): PATH_RE = re.compile('{[^}]*}') class Value(object): __slots__ = ['path', 'tag_path', 'state', 'value', 'deps'] def __init__(self, path, state, value, deps): self.path = path self.tag_path = ValueBuilder.PATH_RE.sub('', path) self.state = state self.value = value self.deps = deps # nodes can depend on themselves if self.tag_path in self.deps: self.deps.remove(self.tag_path) def __lt__(self, rhs): l_len = len(self.path.split('/')) r_len = len(rhs.path.split('/')) if l_len == r_len: return self.path.__lt__(rhs.path) return l_len < r_len def __str__(self): return 'Value<path={0}, state={1}, value={2}>'.format( self.path, self.state, self.value) def __init__(self, client, mode='config'): self._client = client self._mode = mode self._schema_cache = {} self._module_prefix_map_cache = None self._values = [] self._values_dirty = False def build(self, parent, maybe_qname, value, schema=None): qname, name = self.get_prefix_name(maybe_qname) if name is None: path = parent else: path = '{0}/{1}'.format(parent, qname) if schema is None: schema = self._get_schema(path) if self._is_leaf_list(schema) and is_version(self._client, [(4, 5)]): self._build_leaf_list(path, schema, value) elif self._is_leaf(schema): deps = schema.get('deps', []) if self._is_empty_leaf(schema): exists = self._client.exists(path) if exists and value != [None]: self._add_value(path, State.ABSENT, None, deps) elif not exists and value == [None]: self._add_value(path, State.PRESENT, None, deps) else: if maybe_qname is None: value_type = self.get_type(path) else: value_type = self._get_child_type(parent, qname) if 'identityref' in value_type: if isinstance(value, list): value = [ll_v for ll_v, t_ll_v in [self.get_prefix_name(v) for v in value]] else: value, t_value = self.get_prefix_name(value) self._add_value(path, State.SET, value, deps) elif isinstance(value, dict): self._build_dict(path, schema, value) elif isinstance(value, list): self._build_list(path, schema, value) else: raise ModuleFailException( 'unsupported schema {0} at {1}'.format( schema['kind'], path)) @property def values(self): if self._values_dirty: self._values = ValueBuilder.sort_values(self._values) self._values_dirty = False return self._values @staticmethod def sort_values(values): class N(object): def __init__(self, v): self.tmp_mark = False self.mark = False self.v = v sorted_values = [] nodes = [N(v) for v in sorted(values)] def get_node(tag_path): return next((m for m in nodes if m.v.tag_path == tag_path), None) def is_cycle(n, dep, visited): visited.add(n.v.tag_path) if dep in visited: return True dep_n = get_node(dep) if dep_n is not None: for sub_dep in dep_n.v.deps: if is_cycle(dep_n, sub_dep, visited): return True return False # check for dependency cycles, remove if detected. sort will # not be 100% but allows for a best-effort to work around # issue in NSO. for n in nodes: for dep in n.v.deps: if is_cycle(n, dep, set()): n.v.deps.remove(dep) def visit(n): if n.tmp_mark: return False if not n.mark: n.tmp_mark = True for m in nodes: if m.v.tag_path in n.v.deps: if not visit(m): return False n.tmp_mark = False n.mark = True sorted_values.insert(0, n.v) return True n = next((n for n in nodes if not n.mark), None) while n is not None: visit(n) n = next((n for n in nodes if not n.mark), None) return sorted_values[::-1] def _build_dict(self, path, schema, value): keys = schema.get('key', []) for dict_key, dict_value in value.items(): qname, name = self.get_prefix_name(dict_key) if dict_key in ('__state', ) or name in keys: continue child_schema = self._find_child(path, schema, qname) self.build(path, dict_key, dict_value, child_schema) def _build_leaf_list(self, path, schema, value): deps = schema.get('deps', []) entry_type = self.get_type(path, schema) if self._mode == 'verify': for entry in value: if 'identityref' in entry_type: entry, t_entry = self.get_prefix_name(entry) entry_path = '{0}{{{1}}}'.format(path, entry) if not self._client.exists(entry_path): self._add_value(entry_path, State.ABSENT, None, deps) else: # remove leaf list if treated as a list and then re-create the # expected list entries. self._add_value(path, State.ABSENT, None, deps) for entry in value: if 'identityref' in entry_type: entry, t_entry = self.get_prefix_name(entry) entry_path = '{0}{{{1}}}'.format(path, entry) self._add_value(entry_path, State.PRESENT, None, deps) def _build_list(self, path, schema, value): deps = schema.get('deps', []) for entry in value: entry_key = self._build_key(path, entry, schema['key']) entry_path = '{0}{{{1}}}'.format(path, entry_key) entry_state = entry.get('__state', 'present') entry_exists = self._client.exists(entry_path) if entry_state == 'absent': if entry_exists: self._add_value(entry_path, State.ABSENT, None, deps) else: if not entry_exists: self._add_value(entry_path, State.PRESENT, None, deps) if entry_state in State.SYNC_STATES: self._add_value(entry_path, entry_state, None, deps) self.build(entry_path, None, entry) def _build_key(self, path, entry, schema_keys): key_parts = [] for key in schema_keys: value = entry.get(key, None) if value is None: raise ModuleFailException( 'required leaf {0} in {1} not set in data'.format( key, path)) value_type = self._get_child_type(path, key) if 'identityref' in value_type: value, t_value = self.get_prefix_name(value) key_parts.append(self._quote_key(value)) return ' '.join(key_parts) def _quote_key(self, key): if isinstance(key, bool): return key and 'true' or 'false' q_key = [] for c in str(key): if c in ('{', '}', "'", '\\'): q_key.append('\\') q_key.append(c) q_key = ''.join(q_key) if ' ' in q_key: return '{0}'.format(q_key) return q_key def _find_child(self, path, schema, qname): if 'children' not in schema: schema = self._get_schema(path) # look for the qualified name if : is in the name child_schema = self._get_child(schema, qname) if child_schema is not None: return child_schema # no child was found, look for a choice with a child matching for child_schema in schema['children']: if child_schema['kind'] != 'choice': continue choice_child_schema = self._get_choice_child(child_schema, qname) if choice_child_schema is not None: return choice_child_schema raise ModuleFailException( 'no child in {0} with name {1}. children {2}'.format( path, qname, ','.join((c.get('qname', c.get('name', None)) for c in schema['children'])))) def _add_value(self, path, state, value, deps): self._values.append(ValueBuilder.Value(path, state, value, deps)) self._values_dirty = True def get_prefix_name(self, qname): if not isinstance(qname, (str, unicode)): return qname, None if ':' not in qname: return qname, qname module_prefix_map = self._get_module_prefix_map() module, name = qname.split(':', 1) if module not in module_prefix_map: raise ModuleFailException( 'no module mapping for module {0}. loaded modules {1}'.format( module, ','.join(sorted(module_prefix_map.keys())))) return '{0}:{1}'.format(module_prefix_map[module], name), name def _get_schema(self, path): return self._ensure_schema_cached(path)['data'] def _get_child_type(self, parent_path, key): all_schema = self._ensure_schema_cached(parent_path) parent_schema = all_schema['data'] meta = all_schema['meta'] schema = self._find_child(parent_path, parent_schema, key) return self.get_type(parent_path, schema, meta) def get_type(self, path, schema=None, meta=None): if schema is None or meta is None: all_schema = self._ensure_schema_cached(path) schema = all_schema['data'] meta = all_schema['meta'] if self._is_leaf(schema): def get_type(meta, curr_type): if curr_type.get('primitive', False): return [curr_type['name']] if 'namespace' in curr_type: curr_type_key = '{0}:{1}'.format( curr_type['namespace'], curr_type['name']) type_info = meta['types'][curr_type_key][-1] return get_type(meta, type_info) if 'leaf_type' in curr_type: return get_type(meta, curr_type['leaf_type'][-1]) if 'union' in curr_type: union_types = [] for union_type in curr_type['union']: union_types.extend(get_type(meta, union_type[-1])) return union_types return [curr_type.get('name', 'unknown')] return get_type(meta, schema['type']) return None def _ensure_schema_cached(self, path): path = ValueBuilder.PATH_RE.sub('', path) if path not in self._schema_cache: schema = self._client.get_schema(path=path, levels=1) self._schema_cache[path] = schema return self._schema_cache[path] def _get_module_prefix_map(self): if self._module_prefix_map_cache is None: self._module_prefix_map_cache = self._client.get_module_prefix_map() return self._module_prefix_map_cache def _get_child(self, schema, qname): # no child specified, return parent if qname is None: return schema name_key = ':' in qname and 'qname' or 'name' return next((c for c in schema['children'] if c.get(name_key, None) == qname), None) def _get_choice_child(self, schema, qname): name_key = ':' in qname and 'qname' or 'name' for child_case in schema['cases']: # look for direct child choice_child_schema = next( (c for c in child_case['children'] if c.get(name_key, None) == qname), None) if choice_child_schema is not None: return choice_child_schema # look for nested choice for child_schema in child_case['children']: if child_schema['kind'] != 'choice': continue choice_child_schema = self._get_choice_child(child_schema, qname) if choice_child_schema is not None: return choice_child_schema return None def _is_leaf_list(self, schema): return schema.get('kind', None) == 'leaf-list' def _is_leaf(self, schema): # still checking for leaf-list here to be compatible with pre # 4.5 versions of NSO. return schema.get('kind', None) in ('key', 'leaf', 'leaf-list') def _is_empty_leaf(self, schema): return (schema.get('kind', None) == 'leaf' and schema['type'].get('primitive', False) and schema['type'].get('name', '') == 'empty') def connect(params): client = JsonRpc(params['url'], params['timeout'], params['validate_certs']) client.login(params['username'], params['password']) return client def verify_version(client, required_versions): version_str = client.get_system_setting('version') if not verify_version_str(version_str, required_versions): supported_versions = ', '.join( ['.'.join([str(p) for p in required_version]) for required_version in required_versions]) raise ModuleFailException( 'unsupported NSO version {0}. {1} or later supported'.format( version_str, supported_versions)) def is_version(client, required_versions): version_str = client.get_system_setting('version') return verify_version_str(version_str, required_versions) def verify_version_str(version_str, required_versions): version = [int(p) for p in version_str.split('.')] if len(version) < 2: raise ModuleFailException( 'unsupported NSO version format {0}'.format(version_str)) def check_version(required_version, version): for pos in range(len(required_version)): if pos >= len(version): return False if version[pos] > required_version[pos]: return True if version[pos] < required_version[pos]: return False return True for required_version in required_versions: if check_version(required_version, version): return True return False def normalize_value(expected_value, value, key): if value is None: return None if (isinstance(expected_value, bool) and isinstance(value, (str, unicode))): return value == 'true' if isinstance(expected_value, int): try: return int(value) except TypeError: raise ModuleFailException( 'returned value {0} for {1} is not a valid integer'.format( key, value)) if isinstance(expected_value, float): try: return float(value) except TypeError: raise ModuleFailException( 'returned value {0} for {1} is not a valid float'.format( key, value)) if isinstance(expected_value, (list, tuple)): if not isinstance(value, (list, tuple)): raise ModuleFailException( 'returned value {0} for {1} is not a list'.format(value, key)) if len(expected_value) != len(value): raise ModuleFailException( 'list length mismatch for {0}'.format(key)) normalized_value = [] for i in range(len(expected_value)): normalized_value.append( normalize_value(expected_value[i], value[i], '{0}[{1}]'.format(key, i))) return normalized_value if isinstance(expected_value, dict): if not isinstance(value, dict): raise ModuleFailException( 'returned value {0} for {1} is not a dict'.format(value, key)) if len(expected_value) != len(value): raise ModuleFailException( 'dict length mismatch for {0}'.format(key)) normalized_value = {} for k in expected_value.keys(): n_k = normalize_value(k, k, '{0}[{1}]'.format(key, k)) if n_k not in value: raise ModuleFailException('missing {0} in value'.format(n_k)) normalized_value[n_k] = normalize_value(expected_value[k], value[k], '{0}[{1}]'.format(key, k)) return normalized_value if HAVE_UNICODE: if isinstance(expected_value, unicode) and isinstance(value, str): return value.decode('utf-8') if isinstance(expected_value, str) and isinstance(value, unicode): return value.encode('utf-8') else: if hasattr(expected_value, 'encode') and hasattr(value, 'decode'): return value.decode('utf-8') if hasattr(expected_value, 'decode') and hasattr(value, 'encode'): return value.encode('utf-8') return value
dagwieers/ansible
lib/ansible/module_utils/network/nso/nso.py
Python
gpl-3.0
26,808
[ "VisIt" ]
ca325ca2b1a5af81966e34e1aa1f92cd3be61cf0afbb549e507df87a14b5cd3e
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2012 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## 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., or visit: http://www.gnu.org/. ## ## Author(s): Stoq Team <stoq-devel@async.com.br> ## from stoqlib.database.runtime import get_current_branch from stoqlib.domain.product import StockTransactionHistory from stoqlib.gui.editors.productioneditor import ProductionMaterialAllocateEditor from stoqlib.gui.test.uitestutils import GUITest class TestProductionMaterialAllocateEditor(GUITest): def test_show(self): material = self.create_production_material() editor = ProductionMaterialAllocateEditor(self.store, material) editor.identifier.set_label("12345") self.check_editor(editor, 'editor-productionmaterialallocate-show') def test_allocate(self): branch = get_current_branch(self.store) material = self.create_production_material() storable = material.product.storable storable.increase_stock(5, branch, StockTransactionHistory.TYPE_INITIAL, None) editor = ProductionMaterialAllocateEditor(self.store, material) allocated = material.allocated editor.quantity.update(3) self.click(editor.main_dialog.ok_button) self.assertEquals(material.allocated, allocated + 3)
andrebellafronte/stoq
stoqlib/gui/test/test_productionmaterialallocateeditor.py
Python
gpl-2.0
2,018
[ "VisIt" ]
7aa9eb4f887dc12d59ae774995f95e3f1edf31be1d8a33e30cede6ca529311a9
# # 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 import warnings from pyspark import since, keyword_only from pyspark.ml.util import * from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, JavaWrapper from pyspark.ml.param.shared import * from pyspark.ml.common import inherit_doc, _java2py from pyspark.ml.stat import MultivariateGaussian from pyspark.sql import DataFrame __all__ = ['BisectingKMeans', 'BisectingKMeansModel', 'BisectingKMeansSummary', 'KMeans', 'KMeansModel', 'GaussianMixture', 'GaussianMixtureModel', 'GaussianMixtureSummary', 'LDA', 'LDAModel', 'LocalLDAModel', 'DistributedLDAModel', 'PowerIterationClustering'] class ClusteringSummary(JavaWrapper): """ Clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("2.1.0") def predictionCol(self): """ Name for column of predicted clusters in `predictions`. """ return self._call_java("predictionCol") @property @since("2.1.0") def predictions(self): """ DataFrame produced by the model's `transform` method. """ return self._call_java("predictions") @property @since("2.1.0") def featuresCol(self): """ Name for column of features in `predictions`. """ return self._call_java("featuresCol") @property @since("2.1.0") def k(self): """ The number of clusters the model was trained with. """ return self._call_java("k") @property @since("2.1.0") def cluster(self): """ DataFrame of predicted cluster centers for each training data point. """ return self._call_java("cluster") @property @since("2.1.0") def clusterSizes(self): """ Size of (number of data points in) each cluster. """ return self._call_java("clusterSizes") @property @since("2.4.0") def numIter(self): """ Number of iterations. """ return self._call_java("numIter") @inherit_doc class _GaussianMixtureParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasProbabilityCol, HasTol, HasAggregationDepth, HasWeightCol): """ Params for :py:class:`GaussianMixture` and :py:class:`GaussianMixtureModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "Number of independent Gaussians in the mixture model. " + "Must be > 1.", typeConverter=TypeConverters.toInt) @since("2.0.0") def getK(self): """ Gets the value of `k` """ return self.getOrDefault(self.k) class GaussianMixtureModel(JavaModel, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by GaussianMixture. .. versionadded:: 2.0.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 setProbabilityCol(self, value): """ Sets the value of :py:attr:`probabilityCol`. """ return self._set(probabilityCol=value) @property @since("2.0.0") def weights(self): """ Weight for each Gaussian distribution in the mixture. This is a multinomial probability distribution over the k Gaussians, where weights[i] is the weight for Gaussian i, and weights sum to 1. """ return self._call_java("weights") @property @since("3.0.0") def gaussians(self): """ Array of :py:class:`MultivariateGaussian` where gaussians[i] represents the Multivariate Gaussian (Normal) Distribution for Gaussian i """ sc = SparkContext._active_spark_context jgaussians = self._java_obj.gaussians() return [ MultivariateGaussian(_java2py(sc, jgaussian.mean()), _java2py(sc, jgaussian.cov())) for jgaussian in jgaussians] @property @since("2.0.0") def gaussiansDF(self): """ Retrieve Gaussian distributions as a DataFrame. Each row represents a Gaussian Distribution. The DataFrame has two columns: mean (Vector) and cov (Matrix). """ return self._call_java("gaussiansDF") @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return GaussianMixtureSummary(super(GaussianMixtureModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @since("3.0.0") def predictProbability(self, value): """ Predict probability for the given features. """ return self._call_java("predictProbability", value) @inherit_doc class GaussianMixture(JavaEstimator, _GaussianMixtureParams, JavaMLWritable, JavaMLReadable): """ GaussianMixture clustering. This class performs expectation maximization for multivariate Gaussian Mixture Models (GMMs). A GMM represents a composite distribution of independent Gaussian distributions with associated "mixing" weights specifying each's contribution to the composite. Given a set of sample points, this class will maximize the log-likelihood for a mixture of k Gaussians, iterating until the log-likelihood changes by less than convergenceTol, or until it has reached the max number of iterations. While this process is generally guaranteed to converge, it is not guaranteed to find a global optimum. .. note:: For high-dimensional data (with many features), this algorithm may perform poorly. This is due to high-dimensional data (a) making it difficult to cluster at all (based on statistical/theoretical arguments) and (b) numerical issues with Gaussian distributions. >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([-0.1, -0.05 ]),), ... (Vectors.dense([-0.01, -0.1]),), ... (Vectors.dense([0.9, 0.8]),), ... (Vectors.dense([0.75, 0.935]),), ... (Vectors.dense([-0.83, -0.68]),), ... (Vectors.dense([-0.91, -0.76]),)] >>> df = spark.createDataFrame(data, ["features"]) >>> gm = GaussianMixture(k=3, tol=0.0001, seed=10) >>> gm.getMaxIter() 100 >>> gm.setMaxIter(30) GaussianMixture... >>> gm.getMaxIter() 30 >>> model = gm.fit(df) >>> model.getAggregationDepth() 2 >>> model.getFeaturesCol() 'features' >>> model.setPredictionCol("newPrediction") GaussianMixtureModel... >>> model.predict(df.head().features) 2 >>> model.predictProbability(df.head().features) DenseVector([0.0, 0.0, 1.0]) >>> model.hasSummary True >>> summary = model.summary >>> summary.k 3 >>> summary.clusterSizes [2, 2, 2] >>> summary.logLikelihood 65.02945... >>> weights = model.weights >>> len(weights) 3 >>> gaussians = model.gaussians >>> len(gaussians) 3 >>> gaussians[0].mean DenseVector([0.825, 0.8675]) >>> gaussians[0].cov DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], 0) >>> gaussians[1].mean DenseVector([-0.87, -0.72]) >>> gaussians[1].cov DenseMatrix(2, 2, [0.0016, 0.0016, 0.0016, 0.0016], 0) >>> gaussians[2].mean DenseVector([-0.055, -0.075]) >>> gaussians[2].cov DenseMatrix(2, 2, [0.002, -0.0011, -0.0011, 0.0006], 0) >>> model.gaussiansDF.select("mean").head() Row(mean=DenseVector([0.825, 0.8675])) >>> model.gaussiansDF.select("cov").head() Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[4].newPrediction == rows[5].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> gmm_path = temp_path + "/gmm" >>> gm.save(gmm_path) >>> gm2 = GaussianMixture.load(gmm_path) >>> gm2.getK() 3 >>> model_path = temp_path + "/gmm_model" >>> model.save(model_path) >>> model2 = GaussianMixtureModel.load(model_path) >>> model2.hasSummary False >>> model2.weights == model.weights True >>> model2.gaussians[0].mean == model.gaussians[0].mean True >>> model2.gaussians[0].cov == model.gaussians[0].cov True >>> model2.gaussians[1].mean == model.gaussians[1].mean True >>> model2.gaussians[1].cov == model.gaussians[1].cov True >>> model2.gaussians[2].mean == model.gaussians[2].mean True >>> model2.gaussians[2].cov == model.gaussians[2].cov True >>> model2.gaussiansDF.select("mean").head() Row(mean=DenseVector([0.825, 0.8675])) >>> model2.gaussiansDF.select("cov").head() Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False)) >>> gm2.setWeightCol("weight") GaussianMixture... .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", k=2, probabilityCol="probability", tol=0.01, maxIter=100, seed=None, aggregationDepth=2, weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", k=2, \ probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ aggregationDepth=2, weightCol=None) """ super(GaussianMixture, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.GaussianMixture", self.uid) self._setDefault(k=2, tol=0.01, maxIter=100, aggregationDepth=2) kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): return GaussianMixtureModel(java_model) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", predictionCol="prediction", k=2, probabilityCol="probability", tol=0.01, maxIter=100, seed=None, aggregationDepth=2, weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", k=2, \ probabilityCol="probability", tol=0.01, maxIter=100, seed=None, \ aggregationDepth=2, weightCol=None) Sets params for GaussianMixture. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=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 setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("2.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("2.0.0") def setProbabilityCol(self, value): """ Sets the value of :py:attr:`probabilityCol`. """ return self._set(probabilityCol=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 setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("2.0.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("3.0.0") def setAggregationDepth(self, value): """ Sets the value of :py:attr:`aggregationDepth`. """ return self._set(aggregationDepth=value) class GaussianMixtureSummary(ClusteringSummary): """ Gaussian mixture clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("2.1.0") def probabilityCol(self): """ Name for column of predicted probability of each cluster in `predictions`. """ return self._call_java("probabilityCol") @property @since("2.1.0") def probability(self): """ DataFrame of probabilities of each cluster for each training data point. """ return self._call_java("probability") @property @since("2.2.0") def logLikelihood(self): """ Total log-likelihood for this model on the given data. """ return self._call_java("logLikelihood") class KMeansSummary(ClusteringSummary): """ Summary of KMeans. .. versionadded:: 2.1.0 """ @property @since("2.4.0") def trainingCost(self): """ K-means cost (sum of squared distances to the nearest centroid for all points in the training dataset). This is equivalent to sklearn's inertia. """ return self._call_java("trainingCost") @inherit_doc class _KMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasTol, HasDistanceMeasure, HasWeightCol): """ Params for :py:class:`KMeans` and :py:class:`KMeansModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of clusters to create. Must be > 1.", typeConverter=TypeConverters.toInt) initMode = Param(Params._dummy(), "initMode", "The initialization algorithm. This can be either \"random\" to " + "choose random points as initial cluster centers, or \"k-means||\" " + "to use a parallel variant of k-means++", typeConverter=TypeConverters.toString) initSteps = Param(Params._dummy(), "initSteps", "The number of steps for k-means|| " + "initialization mode. Must be > 0.", typeConverter=TypeConverters.toInt) @since("1.5.0") def getK(self): """ Gets the value of `k` """ return self.getOrDefault(self.k) @since("1.5.0") def getInitMode(self): """ Gets the value of `initMode` """ return self.getOrDefault(self.initMode) @since("1.5.0") def getInitSteps(self): """ Gets the value of `initSteps` """ return self.getOrDefault(self.initSteps) class KMeansModel(JavaModel, _KMeansParams, GeneralJavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by KMeans. .. versionadded:: 1.5.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("1.5.0") def clusterCenters(self): """Get the cluster centers, represented as a list of NumPy arrays.""" return [c.toArray() for c in self._call_java("clusterCenters")] @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return KMeansSummary(super(KMeansModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @inherit_doc class KMeans(JavaEstimator, _KMeansParams, JavaMLWritable, JavaMLReadable): """ K-means clustering with a k-means++ like initialization mode (the k-means|| algorithm by Bahmani et al). >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] >>> df = spark.createDataFrame(data, ["features", "weighCol"]) >>> kmeans = KMeans(k=2) >>> kmeans.setSeed(1) KMeans... >>> kmeans.setWeightCol("weighCol") KMeans... >>> kmeans.setMaxIter(10) KMeans... >>> kmeans.getMaxIter() 10 >>> kmeans.clear(kmeans.maxIter) >>> model = kmeans.fit(df) >>> model.getDistanceMeasure() 'euclidean' >>> model.setPredictionCol("newPrediction") KMeansModel... >>> model.predict(df.head().features) 0 >>> centers = model.clusterCenters() >>> len(centers) 2 >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[0].newPrediction == rows[1].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> model.hasSummary True >>> summary = model.summary >>> summary.k 2 >>> summary.clusterSizes [2, 2] >>> summary.trainingCost 4.0 >>> kmeans_path = temp_path + "/kmeans" >>> kmeans.save(kmeans_path) >>> kmeans2 = KMeans.load(kmeans_path) >>> kmeans2.getK() 2 >>> model_path = temp_path + "/kmeans_model" >>> model.save(model_path) >>> model2 = KMeansModel.load(model_path) >>> model2.hasSummary False >>> model.clusterCenters()[0] == model2.clusterCenters()[0] array([ True, True], dtype=bool) >>> model.clusterCenters()[1] == model2.clusterCenters()[1] array([ True, True], dtype=bool) .. versionadded:: 1.5.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, distanceMeasure="euclidean", weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", k=2, \ initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ distanceMeasure="euclidean", weightCol=None) """ super(KMeans, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.KMeans", self.uid) self._setDefault(k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, distanceMeasure="euclidean") kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): return KMeansModel(java_model) @keyword_only @since("1.5.0") def setParams(self, featuresCol="features", predictionCol="prediction", k=2, initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, distanceMeasure="euclidean", weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", k=2, \ initMode="k-means||", initSteps=2, tol=1e-4, maxIter=20, seed=None, \ distanceMeasure="euclidean", weightCol=None) Sets params for KMeans. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("1.5.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("1.5.0") def setInitMode(self, value): """ Sets the value of :py:attr:`initMode`. """ return self._set(initMode=value) @since("1.5.0") def setInitSteps(self, value): """ Sets the value of :py:attr:`initSteps`. """ return self._set(initSteps=value) @since("2.4.0") def setDistanceMeasure(self, value): """ Sets the value of :py:attr:`distanceMeasure`. """ return self._set(distanceMeasure=value) @since("1.5.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("1.5.0") def setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("1.5.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("1.5.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("1.5.0") def setTol(self, value): """ Sets the value of :py:attr:`tol`. """ return self._set(tol=value) @since("3.0.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @inherit_doc class _BisectingKMeansParams(HasMaxIter, HasFeaturesCol, HasSeed, HasPredictionCol, HasDistanceMeasure, HasWeightCol): """ Params for :py:class:`BisectingKMeans` and :py:class:`BisectingKMeansModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The desired number of leaf clusters. Must be > 1.", typeConverter=TypeConverters.toInt) minDivisibleClusterSize = Param(Params._dummy(), "minDivisibleClusterSize", "The minimum number of points (if >= 1.0) or the minimum " + "proportion of points (if < 1.0) of a divisible cluster.", typeConverter=TypeConverters.toFloat) @since("2.0.0") def getK(self): """ Gets the value of `k` or its default value. """ return self.getOrDefault(self.k) @since("2.0.0") def getMinDivisibleClusterSize(self): """ Gets the value of `minDivisibleClusterSize` or its default value. """ return self.getOrDefault(self.minDivisibleClusterSize) class BisectingKMeansModel(JavaModel, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable, HasTrainingSummary): """ Model fitted by BisectingKMeans. .. versionadded:: 2.0.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("2.0.0") def clusterCenters(self): """Get the cluster centers, represented as a list of NumPy arrays.""" return [c.toArray() for c in self._call_java("clusterCenters")] @since("2.0.0") def computeCost(self, dataset): """ Computes the sum of squared distances between the input points and their corresponding cluster centers. ..note:: Deprecated in 3.0.0. It will be removed in future versions. Use ClusteringEvaluator instead. You can also get the cost on the training dataset in the summary. """ warnings.warn("Deprecated in 3.0.0. It will be removed in future versions. Use " "ClusteringEvaluator instead. You can also get the cost on the training " "dataset in the summary.", DeprecationWarning) return self._call_java("computeCost", dataset) @property @since("2.1.0") def summary(self): """ Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the training set. An exception is thrown if no summary exists. """ if self.hasSummary: return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary) else: raise RuntimeError("No training summary available for this %s" % self.__class__.__name__) @since("3.0.0") def predict(self, value): """ Predict label for the given features. """ return self._call_java("predict", value) @inherit_doc class BisectingKMeans(JavaEstimator, _BisectingKMeansParams, JavaMLWritable, JavaMLReadable): """ A bisecting k-means algorithm based on the paper "A comparison of document clustering techniques" by Steinbach, Karypis, and Kumar, with modification to fit Spark. The algorithm starts from a single cluster that contains all points. Iteratively it finds divisible clusters on the bottom level and bisects each of them using k-means, until there are `k` leaf clusters in total or no leaf clusters are divisible. The bisecting steps of clusters on the same level are grouped together to increase parallelism. If bisecting all divisible clusters on the bottom level would result more than `k` leaf clusters, larger clusters get higher priority. >>> from pyspark.ml.linalg import Vectors >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0), ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)] >>> df = spark.createDataFrame(data, ["features", "weighCol"]) >>> bkm = BisectingKMeans(k=2, minDivisibleClusterSize=1.0) >>> bkm.setMaxIter(10) BisectingKMeans... >>> bkm.getMaxIter() 10 >>> bkm.clear(bkm.maxIter) >>> bkm.setSeed(1) BisectingKMeans... >>> bkm.setWeightCol("weighCol") BisectingKMeans... >>> bkm.getSeed() 1 >>> bkm.clear(bkm.seed) >>> model = bkm.fit(df) >>> model.getMaxIter() 20 >>> model.setPredictionCol("newPrediction") BisectingKMeansModel... >>> model.predict(df.head().features) 0 >>> centers = model.clusterCenters() >>> len(centers) 2 >>> model.computeCost(df) 2.0 >>> model.hasSummary True >>> summary = model.summary >>> summary.k 2 >>> summary.clusterSizes [2, 2] >>> summary.trainingCost 4.000... >>> transformed = model.transform(df).select("features", "newPrediction") >>> rows = transformed.collect() >>> rows[0].newPrediction == rows[1].newPrediction True >>> rows[2].newPrediction == rows[3].newPrediction True >>> bkm_path = temp_path + "/bkm" >>> bkm.save(bkm_path) >>> bkm2 = BisectingKMeans.load(bkm_path) >>> bkm2.getK() 2 >>> bkm2.getDistanceMeasure() 'euclidean' >>> model_path = temp_path + "/bkm_model" >>> model.save(model_path) >>> model2 = BisectingKMeansModel.load(model_path) >>> model2.hasSummary False >>> model.clusterCenters()[0] == model2.clusterCenters()[0] array([ True, True], dtype=bool) >>> model.clusterCenters()[1] == model2.clusterCenters()[1] array([ True, True], dtype=bool) .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", predictionCol="prediction", maxIter=20, seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", weightCol=None): """ __init__(self, featuresCol="features", predictionCol="prediction", maxIter=20, \ seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ weightCol=None) """ super(BisectingKMeans, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.BisectingKMeans", self.uid) self._setDefault(maxIter=20, k=4, minDivisibleClusterSize=1.0) kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", predictionCol="prediction", maxIter=20, seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", weightCol=None): """ setParams(self, featuresCol="features", predictionCol="prediction", maxIter=20, \ seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure="euclidean", \ weightCol=None) Sets params for BisectingKMeans. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("2.0.0") def setMinDivisibleClusterSize(self, value): """ Sets the value of :py:attr:`minDivisibleClusterSize`. """ return self._set(minDivisibleClusterSize=value) @since("2.4.0") def setDistanceMeasure(self, value): """ Sets the value of :py:attr:`distanceMeasure`. """ return self._set(distanceMeasure=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 setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @since("2.0.0") def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value) @since("2.0.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) def _create_model(self, java_model): return BisectingKMeansModel(java_model) class BisectingKMeansSummary(ClusteringSummary): """ Bisecting KMeans clustering results for a given model. .. versionadded:: 2.1.0 """ @property @since("3.0.0") def trainingCost(self): """ Sum of squared distances to the nearest centroid for all points in the training dataset. This is equivalent to sklearn's inertia. """ return self._call_java("trainingCost") @inherit_doc class _LDAParams(HasMaxIter, HasFeaturesCol, HasSeed, HasCheckpointInterval): """ Params for :py:class:`LDA` and :py:class:`LDAModel`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of topics (clusters) to infer. Must be > 1.", typeConverter=TypeConverters.toInt) optimizer = Param(Params._dummy(), "optimizer", "Optimizer or inference algorithm used to estimate the LDA model. " "Supported: online, em", typeConverter=TypeConverters.toString) learningOffset = Param(Params._dummy(), "learningOffset", "A (positive) learning parameter that downweights early iterations." " Larger values make early iterations count less", typeConverter=TypeConverters.toFloat) learningDecay = Param(Params._dummy(), "learningDecay", "Learning rate, set as an" "exponential decay rate. This should be between (0.5, 1.0] to " "guarantee asymptotic convergence.", typeConverter=TypeConverters.toFloat) subsamplingRate = Param(Params._dummy(), "subsamplingRate", "Fraction of the corpus to be sampled and used in each iteration " "of mini-batch gradient descent, in range (0, 1].", typeConverter=TypeConverters.toFloat) optimizeDocConcentration = Param(Params._dummy(), "optimizeDocConcentration", "Indicates whether the docConcentration (Dirichlet parameter " "for document-topic distribution) will be optimized during " "training.", typeConverter=TypeConverters.toBoolean) docConcentration = Param(Params._dummy(), "docConcentration", "Concentration parameter (commonly named \"alpha\") for the " "prior placed on documents' distributions over topics (\"theta\").", typeConverter=TypeConverters.toListFloat) topicConcentration = Param(Params._dummy(), "topicConcentration", "Concentration parameter (commonly named \"beta\" or \"eta\") for " "the prior placed on topic' distributions over terms.", typeConverter=TypeConverters.toFloat) topicDistributionCol = Param(Params._dummy(), "topicDistributionCol", "Output column with estimates of the topic mixture distribution " "for each document (often called \"theta\" in the literature). " "Returns a vector of zeros for an empty document.", typeConverter=TypeConverters.toString) keepLastCheckpoint = Param(Params._dummy(), "keepLastCheckpoint", "(For EM optimizer) If using checkpointing, this indicates whether" " to keep the last checkpoint. If false, then the checkpoint will be" " deleted. Deleting the checkpoint can cause failures if a data" " partition is lost, so set this bit with care.", TypeConverters.toBoolean) @since("2.0.0") def getK(self): """ Gets the value of :py:attr:`k` or its default value. """ return self.getOrDefault(self.k) @since("2.0.0") def getOptimizer(self): """ Gets the value of :py:attr:`optimizer` or its default value. """ return self.getOrDefault(self.optimizer) @since("2.0.0") def getLearningOffset(self): """ Gets the value of :py:attr:`learningOffset` or its default value. """ return self.getOrDefault(self.learningOffset) @since("2.0.0") def getLearningDecay(self): """ Gets the value of :py:attr:`learningDecay` or its default value. """ return self.getOrDefault(self.learningDecay) @since("2.0.0") def getSubsamplingRate(self): """ Gets the value of :py:attr:`subsamplingRate` or its default value. """ return self.getOrDefault(self.subsamplingRate) @since("2.0.0") def getOptimizeDocConcentration(self): """ Gets the value of :py:attr:`optimizeDocConcentration` or its default value. """ return self.getOrDefault(self.optimizeDocConcentration) @since("2.0.0") def getDocConcentration(self): """ Gets the value of :py:attr:`docConcentration` or its default value. """ return self.getOrDefault(self.docConcentration) @since("2.0.0") def getTopicConcentration(self): """ Gets the value of :py:attr:`topicConcentration` or its default value. """ return self.getOrDefault(self.topicConcentration) @since("2.0.0") def getTopicDistributionCol(self): """ Gets the value of :py:attr:`topicDistributionCol` or its default value. """ return self.getOrDefault(self.topicDistributionCol) @since("2.0.0") def getKeepLastCheckpoint(self): """ Gets the value of :py:attr:`keepLastCheckpoint` or its default value. """ return self.getOrDefault(self.keepLastCheckpoint) @inherit_doc class LDAModel(JavaModel, _LDAParams): """ Latent Dirichlet Allocation (LDA) model. This abstraction permits for different underlying representations, including local and distributed data structures. .. versionadded:: 2.0.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 setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("3.0.0") def setTopicDistributionCol(self, value): """ Sets the value of :py:attr:`topicDistributionCol`. """ return self._set(topicDistributionCol=value) @since("2.0.0") def isDistributed(self): """ Indicates whether this instance is of type DistributedLDAModel """ return self._call_java("isDistributed") @since("2.0.0") def vocabSize(self): """Vocabulary size (number of terms or words in the vocabulary)""" return self._call_java("vocabSize") @since("2.0.0") def topicsMatrix(self): """ Inferred topics, where each topic is represented by a distribution over terms. This is a matrix of size vocabSize x k, where each column is a topic. No guarantees are given about the ordering of the topics. WARNING: If this model is actually a :py:class:`DistributedLDAModel` instance produced by the Expectation-Maximization ("em") `optimizer`, then this method could involve collecting a large amount of data to the driver (on the order of vocabSize x k). """ return self._call_java("topicsMatrix") @since("2.0.0") def logLikelihood(self, dataset): """ Calculates a lower bound on the log likelihood of the entire corpus. See Equation (16) in the Online LDA paper (Hoffman et al., 2010). WARNING: If this model is an instance of :py:class:`DistributedLDAModel` (produced when :py:attr:`optimizer` is set to "em"), this involves collecting a large :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. """ return self._call_java("logLikelihood", dataset) @since("2.0.0") def logPerplexity(self, dataset): """ Calculate an upper bound on perplexity. (Lower is better.) See Equation (16) in the Online LDA paper (Hoffman et al., 2010). WARNING: If this model is an instance of :py:class:`DistributedLDAModel` (produced when :py:attr:`optimizer` is set to "em"), this involves collecting a large :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future. """ return self._call_java("logPerplexity", dataset) @since("2.0.0") def describeTopics(self, maxTermsPerTopic=10): """ Return the topics described by their top-weighted terms. """ return self._call_java("describeTopics", maxTermsPerTopic) @since("2.0.0") def estimatedDocConcentration(self): """ Value for :py:attr:`LDA.docConcentration` estimated from data. If Online LDA was used and :py:attr:`LDA.optimizeDocConcentration` was set to false, then this returns the fixed (given) value for the :py:attr:`LDA.docConcentration` parameter. """ return self._call_java("estimatedDocConcentration") @inherit_doc class DistributedLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): """ Distributed model fitted by :py:class:`LDA`. This type of model is currently only produced by Expectation-Maximization (EM). This model stores the inferred topics, the full training dataset, and the topic distribution for each training document. .. versionadded:: 2.0.0 """ @since("2.0.0") def toLocal(self): """ Convert this distributed model to a local representation. This discards info about the training dataset. WARNING: This involves collecting a large :py:func:`topicsMatrix` to the driver. """ model = LocalLDAModel(self._call_java("toLocal")) # SPARK-10931: Temporary fix to be removed once LDAModel defines Params model._create_params_from_java() model._transfer_params_from_java() return model @since("2.0.0") def trainingLogLikelihood(self): """ Log likelihood of the observed tokens in the training set, given the current parameter estimates: log P(docs | topics, topic distributions for docs, Dirichlet hyperparameters) Notes: - This excludes the prior; for that, use :py:func:`logPrior`. - Even with :py:func:`logPrior`, this is NOT the same as the data log likelihood given the hyperparameters. - This is computed from the topic distributions computed during training. If you call :py:func:`logLikelihood` on the same training dataset, the topic distributions will be computed again, possibly giving different results. """ return self._call_java("trainingLogLikelihood") @since("2.0.0") def logPrior(self): """ Log probability of the current parameter estimate: log P(topics, topic distributions for docs | alpha, eta) """ return self._call_java("logPrior") @since("2.0.0") def getCheckpointFiles(self): """ If using checkpointing and :py:attr:`LDA.keepLastCheckpoint` is set to true, then there may be saved checkpoint files. This method is provided so that users can manage those files. .. note:: Removing the checkpoints can cause failures if a partition is lost and is needed by certain :py:class:`DistributedLDAModel` methods. Reference counting will clean up the checkpoints when this model and derivative data go out of scope. :return List of checkpoint files from training """ return self._call_java("getCheckpointFiles") @inherit_doc class LocalLDAModel(LDAModel, JavaMLReadable, JavaMLWritable): """ Local (non-distributed) model fitted by :py:class:`LDA`. This model stores the inferred topics only; it does not store info about the training dataset. .. versionadded:: 2.0.0 """ pass @inherit_doc class LDA(JavaEstimator, _LDAParams, JavaMLReadable, JavaMLWritable): """ Latent Dirichlet Allocation (LDA), a topic model designed for text documents. Terminology: - "term" = "word": an element of the vocabulary - "token": instance of a term appearing in a document - "topic": multinomial distribution over terms representing some concept - "document": one piece of text, corresponding to one row in the input data Original LDA paper (journal version): Blei, Ng, and Jordan. "Latent Dirichlet Allocation." JMLR, 2003. Input data (featuresCol): LDA is given a collection of documents as input data, via the featuresCol parameter. Each document is specified as a :py:class:`Vector` of length vocabSize, where each entry is the count for the corresponding term (word) in the document. Feature transformers such as :py:class:`pyspark.ml.feature.Tokenizer` and :py:class:`pyspark.ml.feature.CountVectorizer` can be useful for converting text to word count vectors. >>> from pyspark.ml.linalg import Vectors, SparseVector >>> from pyspark.ml.clustering import LDA >>> df = spark.createDataFrame([[1, Vectors.dense([0.0, 1.0])], ... [2, SparseVector(2, {0: 1.0})],], ["id", "features"]) >>> lda = LDA(k=2, seed=1, optimizer="em") >>> lda.setMaxIter(10) LDA... >>> lda.getMaxIter() 10 >>> lda.clear(lda.maxIter) >>> model = lda.fit(df) >>> model.setSeed(1) DistributedLDAModel... >>> model.getTopicDistributionCol() 'topicDistribution' >>> model.isDistributed() True >>> localModel = model.toLocal() >>> localModel.isDistributed() False >>> model.vocabSize() 2 >>> model.describeTopics().show() +-----+-----------+--------------------+ |topic|termIndices| termWeights| +-----+-----------+--------------------+ | 0| [1, 0]|[0.50401530077160...| | 1| [0, 1]|[0.50401530077160...| +-----+-----------+--------------------+ ... >>> model.topicsMatrix() DenseMatrix(2, 2, [0.496, 0.504, 0.504, 0.496], 0) >>> lda_path = temp_path + "/lda" >>> lda.save(lda_path) >>> sameLDA = LDA.load(lda_path) >>> distributed_model_path = temp_path + "/lda_distributed_model" >>> model.save(distributed_model_path) >>> sameModel = DistributedLDAModel.load(distributed_model_path) >>> local_model_path = temp_path + "/lda_local_model" >>> localModel.save(local_model_path) >>> sameLocalModel = LocalLDAModel.load(local_model_path) .. versionadded:: 2.0.0 """ @keyword_only def __init__(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, docConcentration=None, topicConcentration=None, topicDistributionCol="topicDistribution", keepLastCheckpoint=True): """ __init__(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ subsamplingRate=0.05, optimizeDocConcentration=True,\ docConcentration=None, topicConcentration=None,\ topicDistributionCol="topicDistribution", keepLastCheckpoint=True) """ super(LDA, self).__init__() self._java_obj = self._new_java_obj("org.apache.spark.ml.clustering.LDA", self.uid) self._setDefault(maxIter=20, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, topicDistributionCol="topicDistribution", keepLastCheckpoint=True) kwargs = self._input_kwargs self.setParams(**kwargs) def _create_model(self, java_model): if self.getOptimizer() == "em": return DistributedLDAModel(java_model) else: return LocalLDAModel(java_model) @keyword_only @since("2.0.0") def setParams(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10, k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51, subsamplingRate=0.05, optimizeDocConcentration=True, docConcentration=None, topicConcentration=None, topicDistributionCol="topicDistribution", keepLastCheckpoint=True): """ setParams(self, featuresCol="features", maxIter=20, seed=None, checkpointInterval=10,\ k=10, optimizer="online", learningOffset=1024.0, learningDecay=0.51,\ subsamplingRate=0.05, optimizeDocConcentration=True,\ docConcentration=None, topicConcentration=None,\ topicDistributionCol="topicDistribution", keepLastCheckpoint=True) Sets params for LDA. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.0.0") def setCheckpointInterval(self, value): """ Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value) @since("2.0.0") def setSeed(self, value): """ Sets the value of :py:attr:`seed`. """ return self._set(seed=value) @since("2.0.0") def setK(self, value): """ Sets the value of :py:attr:`k`. >>> algo = LDA().setK(10) >>> algo.getK() 10 """ return self._set(k=value) @since("2.0.0") def setOptimizer(self, value): """ Sets the value of :py:attr:`optimizer`. Currently only support 'em' and 'online'. >>> algo = LDA().setOptimizer("em") >>> algo.getOptimizer() 'em' """ return self._set(optimizer=value) @since("2.0.0") def setLearningOffset(self, value): """ Sets the value of :py:attr:`learningOffset`. >>> algo = LDA().setLearningOffset(100) >>> algo.getLearningOffset() 100.0 """ return self._set(learningOffset=value) @since("2.0.0") def setLearningDecay(self, value): """ Sets the value of :py:attr:`learningDecay`. >>> algo = LDA().setLearningDecay(0.1) >>> algo.getLearningDecay() 0.1... """ return self._set(learningDecay=value) @since("2.0.0") def setSubsamplingRate(self, value): """ Sets the value of :py:attr:`subsamplingRate`. >>> algo = LDA().setSubsamplingRate(0.1) >>> algo.getSubsamplingRate() 0.1... """ return self._set(subsamplingRate=value) @since("2.0.0") def setOptimizeDocConcentration(self, value): """ Sets the value of :py:attr:`optimizeDocConcentration`. >>> algo = LDA().setOptimizeDocConcentration(True) >>> algo.getOptimizeDocConcentration() True """ return self._set(optimizeDocConcentration=value) @since("2.0.0") def setDocConcentration(self, value): """ Sets the value of :py:attr:`docConcentration`. >>> algo = LDA().setDocConcentration([0.1, 0.2]) >>> algo.getDocConcentration() [0.1..., 0.2...] """ return self._set(docConcentration=value) @since("2.0.0") def setTopicConcentration(self, value): """ Sets the value of :py:attr:`topicConcentration`. >>> algo = LDA().setTopicConcentration(0.5) >>> algo.getTopicConcentration() 0.5... """ return self._set(topicConcentration=value) @since("2.0.0") def setTopicDistributionCol(self, value): """ Sets the value of :py:attr:`topicDistributionCol`. >>> algo = LDA().setTopicDistributionCol("topicDistributionCol") >>> algo.getTopicDistributionCol() 'topicDistributionCol' """ return self._set(topicDistributionCol=value) @since("2.0.0") def setKeepLastCheckpoint(self, value): """ Sets the value of :py:attr:`keepLastCheckpoint`. >>> algo = LDA().setKeepLastCheckpoint(False) >>> algo.getKeepLastCheckpoint() False """ return self._set(keepLastCheckpoint=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 setFeaturesCol(self, value): """ Sets the value of :py:attr:`featuresCol`. """ return self._set(featuresCol=value) @inherit_doc class _PowerIterationClusteringParams(HasMaxIter, HasWeightCol): """ Params for :py:class:`PowerIterationClustering`. .. versionadded:: 3.0.0 """ k = Param(Params._dummy(), "k", "The number of clusters to create. Must be > 1.", typeConverter=TypeConverters.toInt) initMode = Param(Params._dummy(), "initMode", "The initialization algorithm. This can be either " + "'random' to use a random vector as vertex properties, or 'degree' to use " + "a normalized sum of similarities with other vertices. Supported options: " + "'random' and 'degree'.", typeConverter=TypeConverters.toString) srcCol = Param(Params._dummy(), "srcCol", "Name of the input column for source vertex IDs.", typeConverter=TypeConverters.toString) dstCol = Param(Params._dummy(), "dstCol", "Name of the input column for destination vertex IDs.", typeConverter=TypeConverters.toString) @since("2.4.0") def getK(self): """ Gets the value of :py:attr:`k` or its default value. """ return self.getOrDefault(self.k) @since("2.4.0") def getInitMode(self): """ Gets the value of :py:attr:`initMode` or its default value. """ return self.getOrDefault(self.initMode) @since("2.4.0") def getSrcCol(self): """ Gets the value of :py:attr:`srcCol` or its default value. """ return self.getOrDefault(self.srcCol) @since("2.4.0") def getDstCol(self): """ Gets the value of :py:attr:`dstCol` or its default value. """ return self.getOrDefault(self.dstCol) @inherit_doc class PowerIterationClustering(_PowerIterationClusteringParams, JavaParams, JavaMLReadable, JavaMLWritable): """ Power Iteration Clustering (PIC), a scalable graph clustering algorithm developed by `Lin and Cohen <http://www.cs.cmu.edu/~frank/papers/icml2010-pic-final.pdf>`_. From the abstract: PIC finds a very low-dimensional embedding of a dataset using truncated power iteration on a normalized pair-wise similarity matrix of the data. This class is not yet an Estimator/Transformer, use :py:func:`assignClusters` method to run the PowerIterationClustering algorithm. .. seealso:: `Wikipedia on Spectral clustering <http://en.wikipedia.org/wiki/Spectral_clustering>`_ >>> data = [(1, 0, 0.5), ... (2, 0, 0.5), (2, 1, 0.7), ... (3, 0, 0.5), (3, 1, 0.7), (3, 2, 0.9), ... (4, 0, 0.5), (4, 1, 0.7), (4, 2, 0.9), (4, 3, 1.1), ... (5, 0, 0.5), (5, 1, 0.7), (5, 2, 0.9), (5, 3, 1.1), (5, 4, 1.3)] >>> df = spark.createDataFrame(data).toDF("src", "dst", "weight").repartition(1) >>> pic = PowerIterationClustering(k=2, weightCol="weight") >>> pic.setMaxIter(40) PowerIterationClustering... >>> assignments = pic.assignClusters(df) >>> assignments.sort(assignments.id).show(truncate=False) +---+-------+ |id |cluster| +---+-------+ |0 |0 | |1 |0 | |2 |0 | |3 |0 | |4 |0 | |5 |1 | +---+-------+ ... >>> pic_path = temp_path + "/pic" >>> pic.save(pic_path) >>> pic2 = PowerIterationClustering.load(pic_path) >>> pic2.getK() 2 >>> pic2.getMaxIter() 40 .. versionadded:: 2.4.0 """ @keyword_only def __init__(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", weightCol=None): """ __init__(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ weightCol=None) """ super(PowerIterationClustering, self).__init__() self._java_obj = self._new_java_obj( "org.apache.spark.ml.clustering.PowerIterationClustering", self.uid) self._setDefault(k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst") kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only @since("2.4.0") def setParams(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst", weightCol=None): """ setParams(self, k=2, maxIter=20, initMode="random", srcCol="src", dstCol="dst",\ weightCol=None) Sets params for PowerIterationClustering. """ kwargs = self._input_kwargs return self._set(**kwargs) @since("2.4.0") def setK(self, value): """ Sets the value of :py:attr:`k`. """ return self._set(k=value) @since("2.4.0") def setInitMode(self, value): """ Sets the value of :py:attr:`initMode`. """ return self._set(initMode=value) @since("2.4.0") def setSrcCol(self, value): """ Sets the value of :py:attr:`srcCol`. """ return self._set(srcCol=value) @since("2.4.0") def setDstCol(self, value): """ Sets the value of :py:attr:`dstCol`. """ return self._set(dstCol=value) @since("2.4.0") def setMaxIter(self, value): """ Sets the value of :py:attr:`maxIter`. """ return self._set(maxIter=value) @since("2.4.0") def setWeightCol(self, value): """ Sets the value of :py:attr:`weightCol`. """ return self._set(weightCol=value) @since("2.4.0") def assignClusters(self, dataset): """ Run the PIC algorithm and returns a cluster assignment for each input vertex. :param dataset: A dataset with columns src, dst, weight representing the affinity matrix, which is the matrix A in the PIC paper. Suppose the src column value is i, the dst column value is j, the weight column value is similarity s,,ij,, which must be nonnegative. This is a symmetric matrix and hence s,,ij,, = s,,ji,,. For any (i, j) with nonzero similarity, there should be either (i, j, s,,ij,,) or (j, i, s,,ji,,) in the input. Rows with i = j are ignored, because we assume s,,ij,, = 0.0. :return: A dataset that contains columns of vertex id and the corresponding cluster for the id. The schema of it will be: - id: Long - cluster: Int .. versionadded:: 2.4.0 """ self._transfer_params_to_java() jdf = self._java_obj.assignClusters(dataset._jdf) return DataFrame(jdf, dataset.sql_ctx) if __name__ == "__main__": import doctest import numpy import pyspark.ml.clustering from pyspark.sql import SparkSession try: # Numpy 1.14+ changed it's string format. numpy.set_printoptions(legacy='1.13') except TypeError: pass globs = pyspark.ml.clustering.__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.clustering 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)
goldmedal/spark
python/pyspark/ml/clustering.py
Python
apache-2.0
60,631
[ "Gaussian" ]
01757be9d0453622bb5a8d40084b0dec7a992453309930954c472156bbfcab7a
from __future__ import print_function import json import logging import os import time import ctk import numpy import qt import vtk import slicer from slicer.ScriptedLoadableModule import * class PickAndPaint(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) parent.title = "Pick 'n Paint " parent.categories = ["Quantification"] parent.dependencies = [] parent.contributors = [ 'Lucie Macron (University of Michigan)', 'Jean-Baptiste Vimort (University of Michigan)', 'James Hoctor (Kitware Inc.)', ] parent.helpText = """ The Pick 'n Paint tool allows users to select ROIs on a reference model and to propagate them over different time point models. """ parent.acknowledgementText = """ This work was supported by the National Institute of Dental and Craniofacial Research and the National Institute of Biomedical Imaging and Bioengineering of the National Institutes of Health under Award Number R01DE024450. """ self.parent = parent class PickAndPaintWidget(ScriptedLoadableModuleWidget): def setup(self): logging.debug("-------Pick And Paint Widget Setup--------") ScriptedLoadableModuleWidget.setup(self) # reload the logic if there is any change self.logic = PickAndPaintLogic(self) self.interactionNode = slicer.mrmlScene.GetNodeByID( "vtkMRMLInteractionNodeSingleton") # UI setup loader = qt.QUiLoader() moduleName = 'PickAndPaint' scriptedModulesPath = eval( 'slicer.modules.%s.path' % moduleName.lower()) scriptedModulesPath = os.path.dirname(scriptedModulesPath) path = os.path.join(scriptedModulesPath, 'Resources', 'UI', '%s.ui' % moduleName) qfile = qt.QFile(path) qfile.open(qt.QFile.ReadOnly) widget = loader.load(qfile, self.parent) self.layout = self.parent.layout() self.widget = widget self.layout.addWidget(widget) # this attribute is useful for Longitudinal quantification extension self.inputModelLabel = self.logic.get("inputModelLabel") # this attribute is useful for Longitudinal quantification extension self.inputLandmarksLabel = self.logic.get("inputLandmarksLabel") self.inputModelSelector = self.logic.get("inputModelSelector") self.inputModelSelector.setMRMLScene(slicer.mrmlScene) self.inputLandmarksSelector = self.logic.get("inputLandmarksSelector") self.inputLandmarksSelector.setMRMLScene(slicer.mrmlScene) self.inputLandmarksSelector.addEnabled = True # The "enable" property seems to not be imported from the .ui self.inputLandmarksSelector.setEnabled(False) self.loadLandmarksOnSurfacCheckBox = self.logic.get( "loadLandmarksOnSurfacCheckBox") self.landmarksScaleWidget = self.logic.get("landmarksScaleWidget") self.addLandmarksButton = self.logic.get("addLandmarksButton") self.surfaceDeplacementCheckBox = self.logic.get( "surfaceDeplacementCheckBox") self.landmarkComboBox = self.logic.get("landmarkComboBox") self.radiusDefinitionWidget = self.logic.get("radiusDefinitionWidget") self.cleanerButton = self.logic.get("cleanerButton") self.correspondentShapes = self.logic.get("correspondentShapes") self.nonCorrespondentShapes = self.logic.get("nonCorrespondentShapes") self.propagationInputComboBox = self.logic.get( "propagationInputComboBox") self.propagationInputComboBox.setMRMLScene(slicer.mrmlScene) self.propagateButton = self.logic.get("propagateButton") # ------------------------------------------------------------------------------------ # CONNECTIONS # ------------------------------------------------------------------------------------ self.inputModelSelector.connect( 'currentNodeChanged(vtkMRMLNode*)', self.onModelChanged) self.inputLandmarksSelector.connect( 'currentNodeChanged(vtkMRMLNode*)', self.onLandmarksChanged) self.addLandmarksButton.connect('clicked()', self.onAddButton) self.cleanerButton.connect('clicked()', self.onCleanButton) self.landmarksScaleWidget.connect( 'valueChanged(double)', self.onLandmarksScaleChanged) self.surfaceDeplacementCheckBox.connect( 'stateChanged(int)', self.onSurfaceDeplacementStateChanged) self.landmarkComboBox.connect( 'currentIndexChanged(QString)', self.onLandmarkComboBoxChanged) self.radiusDefinitionWidget.connect( 'valueChanged(double)', self.onRadiusValueChanged) self.propagationInputComboBox.connect( 'checkedNodesChanged()', self.onPropagationInputComboBoxCheckedNodesChanged) self.propagateButton.connect('clicked()', self.onPropagateButton) slicer.mrmlScene.AddObserver( slicer.mrmlScene.EndCloseEvent, self.onCloseScene) def enter(self): logging.debug('------- in function: enter --------') # See Slicer/Base/QTGUI/qSlicerAbstractModuleWidget.h for an # explanation of when this is called. model = self.inputModelSelector.currentNode() fidlist = self.inputLandmarksSelector.currentNode() if fidlist: if fidlist.GetAttribute("connectedModelID") != model.GetID(): self.inputModelSelector.setCurrentNode(None) self.inputLandmarksSelector.setCurrentNode(None) self.landmarkComboBox.clear() self.UpdateInterface() # Checking the names of the fiducials list_ = slicer.mrmlScene.GetNodesByClass("vtkMRMLMarkupsFiducialNode") end = list_.GetNumberOfItems() for i in range(end): fidList = list_.GetItemAsObject(i) landmarkDescription = self.logic.decodeJSON( fidList.GetAttribute("landmarkDescription")) if landmarkDescription: for n in range(fidList.GetNumberOfMarkups()): markupID = fidList.GetNthMarkupID(n) markupLabel = fidList.GetNthMarkupLabel(n) landmarkDescription[markupID]["landmarkLabel"] = markupLabel fidList.SetAttribute("landmarkDescription", self.logic.encodeJSON(landmarkDescription)) def onCloseScene(self, obj, event): list_ = slicer.mrmlScene.GetNodesByClass("vtkMRMLModelNode") end = list_.GetNumberOfItems() for i in range(end): model = list_.GetItemAsObject(i) hardenModel = slicer.mrmlScene.GetNodesByName( model.GetName()).GetItemAsObject(0) slicer.mrmlScene.RemoveNode(hardenModel) self.radiusDefinitionWidget.value = 0.0 self.landmarksScaleWidget.value = 2.0 self.landmarkComboBox.clear() self.logic.selectedFidList = None self.logic.selectedModel = None def UpdateInterface(self): if not self.logic.selectedModel: return activeInput = self.logic.selectedModel if not self.logic.selectedFidList: return fidList = self.logic.selectedFidList selectedFidReflID = self.logic.findIDFromLabel( fidList, self.landmarkComboBox.currentText) if activeInput: # Update values on widgets. landmarkDescription = self.logic.decodeJSON( fidList.GetAttribute("landmarkDescription")) if landmarkDescription and selectedFidReflID: activeDictLandmarkValue = landmarkDescription[selectedFidReflID] self.radiusDefinitionWidget.value = activeDictLandmarkValue["ROIradius"] if activeDictLandmarkValue["projection"]["isProjected"]: self.surfaceDeplacementCheckBox.setChecked(True) else: self.surfaceDeplacementCheckBox.setChecked(False) else: self.radiusDefinitionWidget.value = 0.0 self.logic.UpdateThreeDView(self.landmarkComboBox.currentText) def onModelChanged(self): logging.debug("-------Model Changed--------") if self.logic.selectedModel: Model = self.logic.selectedModel try: Model.RemoveObserver(self.logic.decodeJSON( self.logic.selectedModel.GetAttribute("modelModifieTagEvent"))) except: pass self.logic.selectedModel = self.inputModelSelector.currentNode() self.logic.ModelChanged(self.inputModelSelector, self.inputLandmarksSelector) self.inputLandmarksSelector.setCurrentNode(None) def onLandmarksChanged(self): logging.debug("-------Landmarks Changed--------") if self.inputModelSelector.currentNode(): self.logic.FidList = self.inputLandmarksSelector.currentNode() self.logic.selectedFidList = self.inputLandmarksSelector.currentNode() self.logic.selectedModel = self.inputModelSelector.currentNode() if self.inputLandmarksSelector.currentNode(): onSurface = self.loadLandmarksOnSurfacCheckBox.isChecked() self.logic.connectLandmarks(self.inputModelSelector, self.inputLandmarksSelector, onSurface) else: self.landmarkComboBox.clear() def onAddButton(self): # Add fiducial on the scene. # If no input model selected, the addition of fiducial shouldn't be possible. selectionNode = slicer.mrmlScene.GetNodeByID( "vtkMRMLSelectionNodeSingleton") selectionNode.SetReferenceActivePlaceNodeClassName( "vtkMRMLMarkupsFiducialNode") if self.logic.selectedModel: if self.logic.selectedFidList: selectionNode.SetActivePlaceNodeID( self.logic.selectedFidList.GetID()) self.interactionNode.SetCurrentInteractionMode(1) else: self.logic.warningMessage("Please select a fiducial list") else: self.logic.warningMessage("Please select a model") def onLandmarksScaleChanged(self): if not self.logic.selectedFidList: self.logic.warningMessage("Please select a fiducial list") return logging.debug("------------Landmark scaled change-----------") displayFiducialNode = self.logic.selectedFidList.GetMarkupsDisplayNode() disabledModify = displayFiducialNode.StartModify() displayFiducialNode.SetGlyphScale(self.landmarksScaleWidget.value) displayFiducialNode.SetTextScale(self.landmarksScaleWidget.value) displayFiducialNode.EndModify(disabledModify) def onSurfaceDeplacementStateChanged(self): activeInput = self.logic.selectedModel if not activeInput: return fidList = self.logic.selectedFidList if not fidList: return # The following case can occur if a new MarkupsFiducial is generated to hold new # landmarks. The list will start empty and the landmark combo box will hold nothing. # In this case there is no need to continue with this routine. if self.landmarkComboBox.currentText == '': return selectedFidReflID = self.logic.findIDFromLabel( fidList, self.landmarkComboBox.currentText) isOnSurface = self.surfaceDeplacementCheckBox.isChecked() landmarkDescription = self.logic.decodeJSON( fidList.GetAttribute("landmarkDescription")) if isOnSurface: hardenModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("hardenModelID")) landmarkDescription[selectedFidReflID]["projection"]["isProjected"] = True landmarkDescription[selectedFidReflID]["projection"]["closestPointIndex"] =\ self.logic.projectOnSurface( hardenModel, fidList, selectedFidReflID) else: landmarkDescription[selectedFidReflID]["projection"]["isProjected"] = False landmarkDescription[selectedFidReflID]["projection"]["closestPointIndex"] = None landmarkDescription[selectedFidReflID]["ROIradius"] = 0 fidList.SetAttribute("landmarkDescription", self.logic.encodeJSON(landmarkDescription)) def onLandmarkComboBoxChanged(self): logging.debug("-------- ComboBox changement --------") self.UpdateInterface() def onRadiusValueChanged(self): logging.debug("--------- ROI radius modification ----------") fidList = self.logic.selectedFidList if not fidList: return selectedFidReflID = self.logic.findIDFromLabel( fidList, self.landmarkComboBox.currentText) if selectedFidReflID: landmarkDescription = self.logic.decodeJSON( fidList.GetAttribute("landmarkDescription")) activeLandmarkState = landmarkDescription[selectedFidReflID] activeLandmarkState["ROIradius"] = self.radiusDefinitionWidget.value if not activeLandmarkState["projection"]["isProjected"]: self.surfaceDeplacementCheckBox.setChecked(True) hardenModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("hardenModelID")) landmarkDescription[selectedFidReflID]["projection"]["isProjected"] = True landmarkDescription[selectedFidReflID]["projection"]["closestPointIndex"] =\ self.logic.projectOnSurface( hardenModel, fidList, selectedFidReflID) fidList.SetAttribute("landmarkDescription", self.logic.encodeJSON(landmarkDescription)) self.logic.findROI(fidList) def onCleanButton(self): messageBox = ctk.ctkMessageBox() messageBox.setWindowTitle(" /!\ WARNING /!\ ") messageBox.setIcon(messageBox.Warning) messageBox.setText("Your model is about to be modified") messageBox.setInformativeText("Do you want to continue?") messageBox.setStandardButtons(messageBox.No | messageBox.Yes) choice = messageBox.exec_() if choice == messageBox.Yes: selectedLandmark = self.landmarkComboBox.currentText self.logic.cleanMesh(selectedLandmark) self.onRadiusValueChanged() else: messageBox.setText(" Region not modified") messageBox.setStandardButtons(messageBox.Ok) messageBox.setInformativeText("") messageBox.exec_() def onPropagationInputComboBoxCheckedNodesChanged(self): if not self.inputModelSelector.currentNode(): return if not self.inputLandmarksSelector.currentNode(): return modelToPropList = self.propagationInputComboBox.checkedNodes() finalList = list() for model in modelToPropList: if model.GetID() != self.inputModelSelector.currentNode().GetID(): finalList.append(model.GetID()) self.inputLandmarksSelector.currentNode().SetAttribute( "modelToPropList", self.logic.encodeJSON({"modelToPropList": finalList})) def onPropagateButton(self): logging.debug(" ------------------------------------ onPropagateButton -------------------------------------- ") if not self.inputModelSelector.currentNode(): return if not self.inputLandmarksSelector.currentNode(): return model = self.inputModelSelector.currentNode() self.logic.cleanerAndTriangleFilter(model) hardenModel = self.logic.createIntermediateHardenModel(model) model.SetAttribute("hardenModelID", hardenModel.GetID()) fidList = self.inputLandmarksSelector.currentNode() decoded_json = self.logic.decodeJSON( fidList.GetAttribute("modelToPropList")) modelToPropagateList = [] if decoded_json is not None: modelToPropagateList = decoded_json["modelToPropList"] for IDmodelToPropagate in modelToPropagateList: modelToPropagate = slicer.mrmlScene.GetNodeByID(IDmodelToPropagate) isClean = self.logic.decodeJSON(fidList.GetAttribute("isClean")) if isClean: if not isClean["isClean"]: self.logic.cleanerAndTriangleFilter(modelToPropagate) hardenModel = self.logic.createIntermediateHardenModel( modelToPropagate) modelToPropagate.SetAttribute( "hardenModelID", hardenModel.GetID()) else: self.logic.cleanerAndTriangleFilter(modelToPropagate) hardenModel = self.logic.createIntermediateHardenModel( modelToPropagate) modelToPropagate.SetAttribute( "hardenModelID", hardenModel.GetID()) if self.correspondentShapes.isChecked(): fidList.SetAttribute("typeOfPropagation", "correspondentShapes") self.logic.propagateCorrespondent( fidList, model, modelToPropagate) else: fidList.SetAttribute("typeOfPropagation", "nonCorrespondentShapes") self.logic.propagateNonCorrespondent(fidList, modelToPropagate) self.UpdateInterface() class PickAndPaintLogic(ScriptedLoadableModuleLogic): ROI_ARRAY_NAME = '{0}_{1}_ROI' def __init__(self, interface): self.selectedModel = None self.selectedFidList = None self.interface = interface def get(self, objectName): return self.findWidget(self.interface.widget, objectName) def findWidget(self, widget, objectName): if widget.objectName == objectName: return widget else: for w in widget.children(): resulting_widget = self.findWidget(w, objectName) if resulting_widget: return resulting_widget return None def UpdateThreeDView(self, landmarkLabel): # Update the 3D view on Slicer if not self.selectedFidList: return if not self.selectedModel: return logging.debug("UpdateThreeDView") active = self.selectedFidList # deactivate all landmarks list_ = slicer.mrmlScene.GetNodesByClass("vtkMRMLMarkupsFiducialNode") end = list_.GetNumberOfItems() selectedFidReflID = self.findIDFromLabel(active, landmarkLabel) for i in range(end): fidList = list_.GetItemAsObject(i) landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) if not landmarkDescription: # Not a PickAndPaint markup fiducial list continue for key in landmarkDescription.keys(): markupsIndex = fidList.GetNthControlPointIndexByID(key) if key != selectedFidReflID: fidList.SetNthMarkupLocked(markupsIndex, True) else: fidList.SetNthMarkupLocked(markupsIndex, False) displayNode = self.selectedModel.GetModelDisplayNode() displayNode.SetScalarVisibility(False) if selectedFidReflID != False: displayNode.SetScalarVisibility(True) def createIntermediateHardenModel(self, model): hardenModel = slicer.mrmlScene.GetNodesByName("SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str( slicer.app.applicationPid())).GetItemAsObject(0) if hardenModel is None: hardenModel = slicer.vtkMRMLModelNode() hardenPolyData = vtk.vtkPolyData() hardenPolyData.DeepCopy(model.GetPolyData()) hardenModel.SetAndObservePolyData(hardenPolyData) hardenModel.SetName( "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid())) if model.GetParentTransformNode(): hardenModel.SetAndObserveTransformNodeID( model.GetParentTransformNode().GetID()) hardenModel.HideFromEditorsOn() slicer.mrmlScene.AddNode(hardenModel) logic = slicer.vtkSlicerTransformLogic() logic.hardenTransform(hardenModel) return hardenModel def onModelModified(self, obj, event): # recompute the harden model hardenModel = self.createIntermediateHardenModel(obj) obj.SetAttribute("hardenModelID", hardenModel.GetID()) # for each fiducial list list_ = slicer.mrmlScene.GetNodesByClass("vtkMRMLMarkupsFiducialNode") end = list_.GetNumberOfItems() for i in range(end): # If landmarks are projected on the modified model fidList = list_.GetItemAsObject(i) if fidList.GetAttribute("connectedModelID"): if fidList.GetAttribute("connectedModelID") == obj.GetID(): # replace the harden model with the new one fidList.SetAttribute("hardenModelID", hardenModel.GetID()) # reproject the fiducials on the new model landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) for n in range(fidList.GetNumberOfMarkups()): markupID = fidList.GetNthMarkupID(n) if landmarkDescription[markupID]["projection"]["isProjected"] == True: hardenModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("hardenModelID")) markupsIndex = fidList.GetNthControlPointIndexByID(markupID) self.replaceLandmark(hardenModel.GetPolyData(), fidList, markupsIndex, landmarkDescription[markupID]["projection"]["closestPointIndex"]) fidList.SetAttribute( "landmarkDescription", self.encodeJSON(landmarkDescription)) def ModelChanged(self, inputModelSelector, inputLandmarksSelector): inputModel = inputModelSelector.currentNode() # if a Model Node is present if inputModel: self.selectedModel = inputModel hardenModel = self.createIntermediateHardenModel(inputModel) inputModel.SetAttribute("hardenModelID", hardenModel.GetID()) modelModifieTagEvent = inputModel.AddObserver( inputModel.TransformModifiedEvent, self.onModelModified) inputModel.SetAttribute("modelModifieTagEvent", self.encodeJSON( {"modelModifieTagEvent": modelModifieTagEvent})) inputLandmarksSelector.setEnabled(True) # if no model is selected else: # Update the fiducial list selector inputLandmarksSelector.setCurrentNode(None) inputLandmarksSelector.setEnabled(False) def isUnderTransform(self, markups): if markups.GetParentTransformNode(): messageBox = ctk.ctkMessageBox() messageBox.setWindowTitle(" /!\ WARNING /!\ ") messageBox.setIcon(messageBox.Warning) messageBox.setText("Your Markup Fiducial Node is currently modified by a transform," "if you choose to continue the program will apply the transform" "before doing anything else!") messageBox.setInformativeText("Do you want to continue?") messageBox.setStandardButtons(messageBox.No | messageBox.Yes) choice = messageBox.exec_() if choice == messageBox.Yes: logic = slicer.vtkSlicerTransformLogic() logic.hardenTransform(markups) return False else: messageBox.setText(" Node not modified") messageBox.setStandardButtons(messageBox.Ok) messageBox.setInformativeText("") messageBox.exec_() return True else: return False def connectedModelChangement(self): messageBox = ctk.ctkMessageBox() messageBox.setWindowTitle(" /!\ WARNING /!\ ") messageBox.setIcon(messageBox.Warning) messageBox.setText("The Markup Fiducial Node selected is curently projected on an" "other model, if you chose to continue the fiducials will be " "reprojected, and this could impact the functioning of other modules") messageBox.setInformativeText("Do you want to continue?") messageBox.setStandardButtons(messageBox.No | messageBox.Yes) choice = messageBox.exec_() if choice == messageBox.Yes: return True else: messageBox.setText(" Node not modified") messageBox.setStandardButtons(messageBox.Ok) messageBox.setInformativeText("") messageBox.exec_() return False def createNewDataStructure(self, landmarks, model, onSurface): landmarks.SetAttribute("connectedModelID", model.GetID()) landmarks.SetAttribute( "hardenModelID", model.GetAttribute("hardenModelID")) landmarkDescription = dict() for n in range(landmarks.GetNumberOfMarkups()): markupID = landmarks.GetNthMarkupID(n) landmarkDescription[markupID] = dict() landmarkLabel = landmarks.GetNthMarkupLabel(n) landmarkDescription[markupID]["landmarkLabel"] = landmarkLabel landmarkDescription[markupID]["ROIradius"] = 0 landmarkDescription[markupID]["projection"] = dict() if onSurface: landmarkDescription[markupID]["projection"]["isProjected"] = True hardenModel = slicer.app.mrmlScene().GetNodeByID( landmarks.GetAttribute("hardenModelID")) landmarkDescription[markupID]["projection"]["closestPointIndex"] = \ self.projectOnSurface(hardenModel, landmarks, markupID) else: landmarkDescription[markupID]["projection"]["isProjected"] = False landmarkDescription[markupID]["projection"]["closestPointIndex"] = None landmarkDescription[markupID]["midPoint"] = dict() landmarkDescription[markupID]["midPoint"]["definedByThisMarkup"] = [] landmarkDescription[markupID]["midPoint"]["isMidPoint"] = False landmarkDescription[markupID]["midPoint"]["Point1"] = None landmarkDescription[markupID]["midPoint"]["Point2"] = None landmarks.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) planeDescription = dict() landmarks.SetAttribute( "planeDescription", self.encodeJSON(planeDescription)) landmarks.SetAttribute("isClean", self.encodeJSON({"isClean": False})) landmarks.SetAttribute("lastTransformID", None) landmarks.SetAttribute("arrayName", self.ROI_ARRAY_NAME.format(model.GetName(), landmarks.GetName())) landmarks.SetAttribute("arrayPartNames", self.encodeJSON([])) def changementOfConnectedModel(self, landmarks, model, onSurface): landmarks.SetAttribute("connectedModelID", model.GetID()) landmarks.SetAttribute( "hardenModelID", model.GetAttribute("hardenModelID")) landmarkDescription = self.decodeJSON( landmarks.GetAttribute("landmarkDescription")) for n in range(landmarks.GetNumberOfMarkups()): markupID = landmarks.GetNthMarkupID(n) if onSurface: if landmarkDescription[markupID]["projection"]["isProjected"] == True: hardenModel = slicer.app.mrmlScene().GetNodeByID( landmarks.GetAttribute("hardenModelID")) landmarkDescription[markupID]["projection"]["closestPointIndex"] = \ self.projectOnSurface(hardenModel, landmarks, markupID) else: landmarkDescription[markupID]["projection"]["isProjected"] = False landmarkDescription[markupID]["projection"]["closestPointIndex"] = None landmarks.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) landmarks.SetAttribute("isClean", self.encodeJSON({"isClean": False})) def connectLandmarks(self, modelSelector, landmarkSelector, onSurface): model = modelSelector.currentNode() landmarks = landmarkSelector.currentNode() self.selectedFidList = landmarks self.selectedModel = model if not (model and landmarks): return if self.isUnderTransform(landmarks): landmarkSelector.setCurrentNode(None) return connectedModelID = landmarks.GetAttribute("connectedModelID") try: tag = self.decodeJSON(landmarks.GetAttribute("PointAddedEventTag")) landmarks.RemoveObserver(tag["PointAddedEventTag"]) logging.debug("PointAddedEvent observers removed!") except: pass try: tag = self.decodeJSON( landmarks.GetAttribute("PointModifiedEventTag")) landmarks.RemoveObserver(tag["PointModifiedEventTag"]) logging.debug("PointModifiedEvent observers removed!") except: pass try: tag = self.decodeJSON( landmarks.GetAttribute("PointRemovedEventTag")) landmarks.RemoveObserver(tag["PointRemovedEventTag"]) logging.debug("PointRemovedEvent observers removed!") except: pass if connectedModelID: if connectedModelID != model.GetID(): if self.connectedModelChangement(): self.changementOfConnectedModel( landmarks, model, onSurface) else: landmarkSelector.setCurrentNode(None) return else: landmarks.SetAttribute( "hardenModelID", model.GetAttribute("hardenModelID")) # creation of the data structure else: self.createNewDataStructure(landmarks, model, onSurface) # update of the landmark Combo Box self.updateLandmarkComboBox(landmarks) # adding of listeners PointAddedEventTag = landmarks.AddObserver( landmarks.PointAddedEvent, self.onPointAddedEvent) landmarks.SetAttribute("PointAddedEventTag", self.encodeJSON( {"PointAddedEventTag": PointAddedEventTag})) PointModifiedEventTag = landmarks.AddObserver( landmarks.PointModifiedEvent, self.onPointModifiedEvent) landmarks.SetAttribute("PointModifiedEventTag", self.encodeJSON( {"PointModifiedEventTag": PointModifiedEventTag})) PointRemovedEventTag = landmarks.AddObserver( landmarks.PointRemovedEvent, self.onPointRemovedEvent) landmarks.SetAttribute("PointRemovedEventTag", self.encodeJSON( {"PointRemovedEventTag": PointRemovedEventTag})) # Called when a landmark is added on a model def onPointAddedEvent(self, obj, event): logging.debug("------markup adding-------") landmarkDescription = self.decodeJSON( obj.GetAttribute("landmarkDescription")) numOfMarkups = obj.GetNumberOfMarkups() # because every time a new node is added, its index is the last one on the list: markupID = obj.GetNthMarkupID(numOfMarkups - 1) landmarkDescription[markupID] = dict() landmarkLabel = obj.GetNthMarkupLabel(numOfMarkups - 1) landmarkDescription[markupID]["landmarkLabel"] = landmarkLabel landmarkDescription[markupID]["ROIradius"] = 0 landmarkDescription[markupID]["projection"] = dict() landmarkDescription[markupID]["projection"]["isProjected"] = True # The landmark will be projected by onPointModifiedEvent landmarkDescription[markupID]["midPoint"] = dict() landmarkDescription[markupID]["midPoint"]["definedByThisMarkup"] = list() landmarkDescription[markupID]["midPoint"]["isMidPoint"] = False landmarkDescription[markupID]["midPoint"]["Point1"] = None landmarkDescription[markupID]["midPoint"]["Point2"] = None obj.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) self.interface.landmarkComboBox.addItem(landmarkLabel) self.interface.landmarkComboBox.setCurrentIndex( self.interface.landmarkComboBox.count - 1) self.interface.UpdateInterface() qt.QTimer.singleShot(0, lambda: self.onPointModifiedEvent(obj, None)) def calculateMidPointCoord(self, fidList, landmark1ID, landmark2ID): """Set the midpoint when you know the the mrml nodes""" landmark1Index = fidList.GetNthControlPointIndexByID(landmark1ID) landmark2Index = fidList.GetNthControlPointIndexByID(landmark2ID) coord1 = [-1, -1, -1] coord2 = [-1, -1, -1] fidList.GetNthFiducialPosition(landmark1Index, coord1) fidList.GetNthFiducialPosition(landmark2Index, coord2) midCoord = [-1, -1, -1] midCoord[0] = (coord1[0] + coord2[0])/2 midCoord[1] = (coord1[1] + coord2[1])/2 midCoord[2] = (coord1[2] + coord2[2])/2 return midCoord def updateMidPoint(self, fidList, landmarkID): landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) for midPointID in landmarkDescription[landmarkID]["midPoint"]["definedByThisMarkup"]: if landmarkDescription[midPointID]["midPoint"]["isMidPoint"]: landmark1ID = landmarkDescription[midPointID]["midPoint"]["Point1"] landmark2ID = landmarkDescription[midPointID]["midPoint"]["Point2"] coord = self.calculateMidPointCoord( fidList, landmark1ID, landmark2ID) index = fidList.GetNthControlPointIndexByID(midPointID) fidList.SetNthFiducialPositionFromArray(index, coord) if landmarkDescription[midPointID]["projection"]["isProjected"]: hardenModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("hardenModelID")) landmarkDescription[midPointID]["projection"]["closestPointIndex"] = \ self.projectOnSurface(hardenModel, fidList, landmarkID) fidList.SetAttribute( "landmarkDescription", self.encodeJSON(landmarkDescription)) self.updateMidPoint(fidList, midPointID) # Called when a landmarks is moved def onPointModifiedEvent(self, obj, event): logging.debug("----onPointModifiedEvent PandP-----") landmarkDescription = self.decodeJSON( obj.GetAttribute("landmarkDescription")) if not landmarkDescription: return selectedLandmarkID = self.findIDFromLabel( obj, self.interface.landmarkComboBox.currentText) # remove observer to make sure, the callback function won't work.. tag = self.decodeJSON(obj.GetAttribute("PointModifiedEventTag")) obj.RemoveObserver(tag["PointModifiedEventTag"]) if selectedLandmarkID: activeLandmarkState = landmarkDescription[selectedLandmarkID] if activeLandmarkState["projection"]["isProjected"]: hardenModel = slicer.app.mrmlScene().GetNodeByID( obj.GetAttribute("hardenModelID")) activeLandmarkState["projection"]["closestPointIndex"] = \ self.projectOnSurface(hardenModel, obj, selectedLandmarkID) obj.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) self.updateMidPoint(obj, selectedLandmarkID) self.findROI(obj) time.sleep(0.08) # Add the observer again PointModifiedEventTag = obj.AddObserver( obj.PointModifiedEvent, self.onPointModifiedEvent) obj.SetAttribute("PointModifiedEventTag", self.encodeJSON( {"PointModifiedEventTag": PointModifiedEventTag})) def onPointRemovedEvent(self, obj, event): logging.debug("------markup deleting-------") landmarkDescription = self.decodeJSON( obj.GetAttribute("landmarkDescription")) IDs = [] for ID, value in landmarkDescription.items(): isFound = False for n in range(obj.GetNumberOfMarkups()): markupID = obj.GetNthMarkupID(n) if ID == markupID: isFound = True if not isFound: logging.debug(ID) IDs.append(ID) for ID in IDs: landmarkDescription.pop(ID, None) obj.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) self.updateLandmarkComboBox(obj) def updateLandmarkComboBox(self, fidList, displayMidPoint=True): if not fidList: return landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) self.interface.landmarkComboBox.blockSignals(True) self.interface.landmarkComboBox.clear() numOfFid = fidList.GetNumberOfMarkups() if numOfFid > 0: for i in range(numOfFid): ID = fidList.GetNthMarkupID(i) if not landmarkDescription[ID]["midPoint"]["isMidPoint"]: landmarkLabel = fidList.GetNthMarkupLabel(i) self.interface.landmarkComboBox.addItem(landmarkLabel) self.interface.landmarkComboBox.blockSignals(False) def findIDFromLabel(self, fidList, landmarkLabel): # find the ID of the markupsNode from the label of a landmark! landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) for ID, value in landmarkDescription.items(): if value["landmarkLabel"] == landmarkLabel: return ID return None def getClosestPointIndex(self, fidNode, inputPolyData, landmarkID): landmarkCoord = numpy.zeros(3) landmarkCoord[1] = 42 fidNode.GetNthFiducialPosition(landmarkID, landmarkCoord) pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(inputPolyData) pointLocator.AutomaticOn() pointLocator.BuildLocator() indexClosestPoint = pointLocator.FindClosestPoint(landmarkCoord) return indexClosestPoint def replaceLandmark(self, inputModelPolyData, fidNode, landmarkID, indexClosestPoint): landmarkCoord = [-1, -1, -1] inputModelPolyData.GetPoints().GetPoint(indexClosestPoint, landmarkCoord) fidNode.SetNthFiducialPositionFromArray(landmarkID, landmarkCoord) def projectOnSurface(self, modelOnProject, fidNode, selectedFidReflID): if selectedFidReflID: markupsIndex = fidNode.GetNthControlPointIndexByID( selectedFidReflID) indexClosestPoint = self.getClosestPointIndex( fidNode, modelOnProject.GetPolyData(), markupsIndex) self.replaceLandmark(modelOnProject.GetPolyData(), fidNode, markupsIndex, indexClosestPoint) return indexClosestPoint def defineNeighbor(self, connectedVerticesList, inputModelNodePolyData, indexClosestPoint, distance): self.GetConnectedVertices( connectedVerticesList, inputModelNodePolyData, indexClosestPoint) if distance > 1: for dist in range(1, int(distance)): for i in range(connectedVerticesList.GetNumberOfIds()): self.GetConnectedVertices(connectedVerticesList, inputModelNodePolyData, connectedVerticesList.GetId(i)) return connectedVerticesList def GetConnectedVertices(self, connectedVerticesIDList, polyData, pointID): # Return IDs of all the vertices that compose the first neighbor. cellList = vtk.vtkIdList() connectedVerticesIDList.InsertUniqueId(pointID) # Get cells that vertex 'pointID' belongs to polyData.GetPointCells(pointID, cellList) numberOfIds = cellList.GetNumberOfIds() for i in range(numberOfIds): # Get points which compose all cells pointIdList = vtk.vtkIdList() polyData.GetCellPoints(cellList.GetId(i), pointIdList) for j in range(pointIdList.GetNumberOfIds()): connectedVerticesIDList.InsertUniqueId(pointIdList.GetId(j)) return connectedVerticesIDList def addArrayFromIdList(self, connectedIdList, inputModelNode, arrayName): if not inputModelNode: return inputModelNodePolydata = inputModelNode.GetPolyData() pointData = inputModelNodePolydata.GetPointData() numberofIds = connectedIdList.GetNumberOfIds() hasArrayInt = pointData.HasArray(arrayName) if hasArrayInt == 1: # ROI Array found pointData.RemoveArray(arrayName) arrayToAdd = vtk.vtkDoubleArray() arrayToAdd.SetName(arrayName) for i in range(inputModelNodePolydata.GetNumberOfPoints()): arrayToAdd.InsertNextValue(0.0) for i in range(numberofIds): arrayToAdd.SetValue(connectedIdList.GetId(i), 1.0) lut = vtk.vtkLookupTable() tableSize = 2 lut.SetNumberOfTableValues(tableSize) lut.Build() displayNode = inputModelNode.GetDisplayNode() if displayNode: rgb = displayNode.GetColor() lut.SetTableValue(0, rgb[0], rgb[1], rgb[2], 1) else: lut.SetTableValue(0, 0.0, 1.0, 0.0, 1) lut.SetTableValue(1, 1.0, 0.0, 0.0, 1) arrayToAdd.SetLookupTable(lut) pointData.AddArray(arrayToAdd) inputModelNodePolydata.Modified() return True def displayROI(self, inputModelNode, scalarName): PolyData = inputModelNode.GetPolyData() PolyData.Modified() displayNode = inputModelNode.GetModelDisplayNode() displayNode.SetScalarVisibility(False) disabledModify = displayNode.StartModify() displayNode.SetActiveScalarName(scalarName) displayNode.SetScalarVisibility(True) displayNode.EndModify(disabledModify) def findROI(self, fidList): hardenModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("hardenModelID")) connectedModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("connectedModelID")) landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) arrayName = fidList.GetAttribute("arrayName") arrayPartNames = set() ROIPointListID = vtk.vtkIdList() for key, activeLandmarkState in landmarkDescription.items(): currentROIPointListID = vtk.vtkIdList() currentArrayPartName = self.ROI_ARRAY_NAME.format( connectedModel.GetName(), activeLandmarkState['landmarkLabel'], ) if activeLandmarkState["ROIradius"] != 0: self.defineNeighbor(currentROIPointListID, hardenModel.GetPolyData(), activeLandmarkState["projection"]["closestPointIndex"], activeLandmarkState["ROIradius"]) self.addArrayFromIdList(currentROIPointListID, connectedModel, currentArrayPartName) arrayPartNames.add(currentArrayPartName) for j in range(currentROIPointListID.GetNumberOfIds()): ROIPointListID.InsertUniqueId(currentROIPointListID.GetId(j)) fidList.SetAttribute("arrayPartNames", self.encodeJSON(list(arrayPartNames))) listID = ROIPointListID self.addArrayFromIdList(listID, connectedModel, arrayName) self.displayROI(connectedModel, arrayName) return ROIPointListID def cleanerAndTriangleFilter(self, inputModel): cleanerPolydata = vtk.vtkCleanPolyData() cleanerPolydata.SetInputData(inputModel.GetPolyData()) cleanerPolydata.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(cleanerPolydata.GetOutput()) triangleFilter.Update() inputModel.SetAndObservePolyData(triangleFilter.GetOutput()) def cleanMesh(self, selectedLandmark): activeInput = self.selectedModel fidList = self.selectedFidList hardenModel = slicer.app.mrmlScene().GetNodeByID( activeInput.GetAttribute("hardenModelID")) if activeInput: # Clean the mesh with vtkCleanPolyData cleaner and vtkTriangleFilter: self.cleanerAndTriangleFilter(activeInput) self.cleanerAndTriangleFilter(hardenModel) # Define the new ROI: selectedLandmarkID = self.findIDFromLabel( fidList, selectedLandmark) if selectedLandmarkID: landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) landmarkDescription[selectedLandmarkID]["projection"]["closestPointIndex"] = \ self.projectOnSurface(hardenModel, fidList, selectedLandmarkID) fidList.SetAttribute("landmarkDescription", self.encodeJSON(landmarkDescription)) fidList.SetAttribute("isClean", self.encodeJSON({"isClean": True})) def propagateCorrespondent(self, fidList, referenceInputModel, propagatedInputModel): arrayName = fidList.GetAttribute("arrayName") arrayPartNames = self.decodeJSON(fidList.GetAttribute("arrayPartNames")) referencePointData = referenceInputModel.GetPolyData().GetPointData() propagatedPointData = propagatedInputModel.GetPolyData().GetPointData() for name in [arrayName, *arrayPartNames]: arrayToPropagate = referencePointData.GetArray(name) if arrayToPropagate: if propagatedPointData.GetArray(name): # Array already exists propagatedPointData.RemoveArray(name) propagatedPointData.AddArray(arrayToPropagate) self.displayROI(propagatedInputModel, name) else: logging.warning(" NO ROI ARRAY %s FOUND. PLEASE DEFINE ONE BEFORE.", name) continue def propagateNonCorrespondent(self, fidList, modelToPropagate): logging.debug(modelToPropagate.GetAttribute("hardenModelID")) connectedModel = slicer.app.mrmlScene().GetNodeByID( fidList.GetAttribute("connectedModel")) hardenModel = slicer.app.mrmlScene().GetNodeByID( modelToPropagate.GetAttribute("hardenModelID")) landmarkDescription = self.decodeJSON( fidList.GetAttribute("landmarkDescription")) arrayName = fidList.GetAttribute("arrayName") ROIPointListID = vtk.vtkIdList() for key, activeLandmarkState in landmarkDescription.items(): currentROIPointListID = vtk.vtkIdList() currentArrayPartName = self.ROI_ARRAY_NAME.format( connectedModel.GetName(), activeLandmarkState['landmarkLabel'] ) markupsIndex = fidList.GetNthControlPointIndexByID(key) indexClosestPoint = self.getClosestPointIndex( fidList, modelToPropagate.GetPolyData(), markupsIndex ) if activeLandmarkState["ROIradius"] != 0: self.defineNeighbor( currentROIPointListID, hardenModel.GetPolyData(), indexClosestPoint, activeLandmarkState["ROIradius"] ) self.addArrayFromIdList(currentROIPointListID, modelToPropagate, currentArrayPartName) for j in range(currentROIPointListID.GetNumberOfIds()): ROIPointListID.InsertUniqueId(currentROIPointListID.GetId(j)) listID = ROIPointListID self.addArrayFromIdList(listID, modelToPropagate, arrayName) self.displayROI(modelToPropagate, arrayName) def warningMessage(self, message): messageBox = ctk.ctkMessageBox() messageBox.setWindowTitle(" /!\ WARNING /!\ ") messageBox.setIcon(messageBox.Warning) messageBox.setText(message) messageBox.setStandardButtons(messageBox.Ok) messageBox.exec_() def encodeJSON(self, input): encodedString = json.dumps(input) encodedString = encodedString.replace('\"', '\'') return encodedString def decodeJSON(self, input): if input: input = input.replace('\'', '\"') return json.loads(input) return None class PickAndPaintTest(ScriptedLoadableModuleTest): def setUp(self): slicer.mrmlScene.Clear(0) def runTest(self): self.setUp() self.delayDisplay(' Starting tests ') self.delayDisplay(' Test getClosestPointIndex Function ') self.assertTrue(self.testGetClosestPointIndexFunction()) self.delayDisplay(' Test replaceLandmark Function ') self.assertTrue(self.testReplaceLandmarkFunction()) self.delayDisplay(' Test DefineNeighbors Function ') self.assertTrue(self.testDefineNeighborsFunction()) self.delayDisplay(' Test addArrayFromIdList Function ') self.assertTrue(self.testAddArrayFromIdListFunction()) self.delayDisplay(' Tests Passed! ') def testGetClosestPointIndexFunction(self): sphereModel = self.defineSphere() slicer.mrmlScene.AddNode(sphereModel) closestPointIndexList = list() polyData = sphereModel.GetPolyData() logic = PickAndPaintLogic(slicer.modules.PickAndPaintWidget) markupsLogic = self.defineMarkupsLogic() closestPointIndexList.append(logic.getClosestPointIndex(slicer.mrmlScene.GetNodeByID(markupsLogic.GetActiveListID()), polyData, 0)) closestPointIndexList.append(logic.getClosestPointIndex(slicer.mrmlScene.GetNodeByID(markupsLogic.GetActiveListID()), polyData, 1)) closestPointIndexList.append(logic.getClosestPointIndex(slicer.mrmlScene.GetNodeByID(markupsLogic.GetActiveListID()), polyData, 2)) if closestPointIndexList[0] != 9 or closestPointIndexList[1] != 35 or closestPointIndexList[2] != 1: return False return True def testReplaceLandmarkFunction(self): logging.info(' Test replaceLandmark Function ') logic = PickAndPaintLogic(slicer.modules.PickAndPaintWidget) sphereModel = self.defineSphere() polyData = sphereModel.GetPolyData() markupsLogic = self.defineMarkupsLogic() listCoordinates = list() listCoordinates.append( [55.28383255004883, 55.28383255004883, 62.34897994995117]) listCoordinates.append( [-68.93781280517578, -68.93781280517578, -22.252094268798828]) listCoordinates.append([0.0, 0.0, -100.0]) closestPointIndexList = [9, 35, 1] coord = [-1, -1, -1] for i in range(slicer.mrmlScene.GetNodeByID(markupsLogic.GetActiveListID()).GetNumberOfFiducials()): logic.replaceLandmark(polyData, slicer.mrmlScene.GetNodeByID(markupsLogic.GetActiveListID()), i, closestPointIndexList[i]) slicer.mrmlScene.GetNodeByID( markupsLogic.GetActiveListID()).GetNthFiducialPosition(i, coord) if coord != listCoordinates[i]: logging.warning(f'{i} - Failed ') return False else: logging.info(f'{i} - Passed! ') return True def testDefineNeighborsFunction(self): logic = PickAndPaintLogic(slicer.modules.PickAndPaintWidget) sphereModel = self.defineSphere() polyData = sphereModel.GetPolyData() closestPointIndexList = [9, 35, 1] connectedVerticesReferenceList = list() connectedVerticesReferenceList.append([9, 2, 3, 8, 10, 15, 16]) connectedVerticesReferenceList.append( [35, 28, 29, 34, 36, 41, 42, 21, 22, 27, 23, 30, 33, 40, 37, 43, 47, 48, 49]) connectedVerticesReferenceList.append( [1, 7, 13, 19, 25, 31, 37, 43, 49, 6, 48, 12, 18, 24, 30, 36, 42, 5, 47, 41, 11, 17, 23, 29, 35]) connectedVerticesTestedList = list() for i in range(3): inter = vtk.vtkIdList() logic.defineNeighbor(inter, polyData, closestPointIndexList[i], i + 1) connectedVerticesTestedList.append(inter) list1 = list() for j in range(connectedVerticesTestedList[i].GetNumberOfIds()): list1.append(int(connectedVerticesTestedList[i].GetId(j))) connectedVerticesTestedList[i] = list1 if connectedVerticesTestedList[i] != connectedVerticesReferenceList[i]: logging.warning(f'test {i} AddArrayFromIdList: failed') return False else: logging.info(f'test {i} AddArrayFromIdList: succeed') return True def testAddArrayFromIdListFunction(self): logic = PickAndPaintLogic(slicer.modules.PickAndPaintWidget) sphereModel = self.defineSphere() polyData = sphereModel.GetPolyData() closestPointIndexList = [9, 35, 1] for i in range(3): inter = vtk.vtkIdList() logic.defineNeighbor( inter, polyData, closestPointIndexList[i], i + 1) logic.addArrayFromIdList(inter, sphereModel, 'Test_' + str(i + 1)) if polyData.GetPointData().HasArray('Test_' + str(i + 1)) != 1: logging.warning(f'test {i} AddArrayFromIdList: failed') return False else: logging.info(f'test {i} AddArrayFromIdList: succeed') return True def defineSphere(self): sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(100.0) sphereSource.Update() model = slicer.vtkMRMLModelNode() model.SetAndObservePolyData(sphereSource.GetOutput()) modelDisplay = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) modelDisplay.SetInputPolyDataConnection(sphereSource.GetOutputPort()) return model def defineMarkupsLogic(self): slicer.mrmlScene.Clear(0) markupsLogic = slicer.modules.markups.logic() markupsLogic.AddFiducial(58.602, 41.692, 62.569) markupsLogic.AddFiducial(-59.713, -67.347, -19.529) markupsLogic.AddFiducial(-10.573, -3.036, -93.381) return markupsLogic
DCBIA-OrthoLab/PickAndPaintExtension
PickAndPaint/PickAndPaint.py
Python
apache-2.0
56,605
[ "VTK" ]
4a979099eb8c9c8f7199590ad2d6a1f8dea04302d8f5b7d818b71feb405fac5b
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import os class Paraview(CMakePackage): """ParaView is an open-source, multi-platform data analysis and visualization application.""" homepage = 'http://www.paraview.org' url = "http://www.paraview.org/files/v5.3/ParaView-v5.3.0.tar.gz" _urlfmt = 'http://www.paraview.org/files/v{0}/ParaView-v{1}{2}.tar.gz' version('5.4.1', '4030c70477ec5a85aa72d6fc86a30753') version('5.4.0', 'b92847605bac9036414b644f33cb7163') version('5.3.0', '68fbbbe733aa607ec13d1db1ab5eba71') version('5.2.0', '4570d1a2a183026adb65b73c7125b8b0') version('5.1.2', '44fb32fc8988fcdfbc216c9e40c3e925') version('5.0.1', 'fdf206113369746e2276b95b257d2c9b') version('4.4.0', 'fa1569857dd680ebb4d7ff89c2227378') variant('plugins', default=True, description='Install include files for plugins support') variant('python', default=False, description='Enable Python support') variant('mpi', default=True, description='Enable MPI support') variant('osmesa', default=False, description='Enable OSMesa support') variant('qt', default=False, description='Enable Qt (gui) support') variant('opengl2', default=True, description='Enable OpenGL2 backend') variant('examples', default=False, description="Build examples") variant('hdf5', default=False, description="Use external HDF5") depends_on('python@2:2.8', when='+python') depends_on('py-numpy', when='+python', type='run') depends_on('py-matplotlib', when='+python', type='run') depends_on('mpi', when='+mpi') depends_on('qt+opengl', when='@5.3.0:+qt+opengl2') depends_on('qt~opengl', when='@5.3.0:+qt~opengl2') depends_on('qt@:4', when='@:5.2.0+qt') depends_on('mesa+swrender', when='+osmesa') depends_on('libxt', when='+qt') conflicts('+qt', when='+osmesa') depends_on('bzip2') depends_on('freetype') # depends_on('hdf5+mpi', when='+mpi') # depends_on('hdf5~mpi', when='~mpi') depends_on('hdf5+hl+mpi', when='+hdf5+mpi') depends_on('hdf5+hl~mpi', when='+hdf5~mpi') depends_on('jpeg') depends_on('libpng') depends_on('libtiff') depends_on('libxml2') # depends_on('netcdf') # depends_on('netcdf-cxx') # depends_on('protobuf') # version mismatches? # depends_on('sqlite') # external version not supported depends_on('zlib') depends_on('cmake@3.3:', type='build') patch('stl-reader-pv440.patch', when='@4.4.0') # Broken gcc-detection - improved in 5.1.0, redundant later patch('gcc-compiler-pv501.patch', when='@:5.0.1') # Broken installation (ui_pqExportStateWizard.h) - fixed in 5.2.0 patch('ui_pqExportStateWizard.patch', when='@:5.1.2') def url_for_version(self, version): """Handle ParaView version-based custom URLs.""" if version < Version('5.1.0'): return self._urlfmt.format(version.up_to(2), version, '-source') else: return self._urlfmt.format(version.up_to(2), version, '') def setup_dependent_environment(self, spack_env, run_env, dependent_spec): if os.path.isdir(self.prefix.lib64): lib_dir = self.prefix.lib64 else: lib_dir = self.prefix.lib paraview_version = 'paraview-%s' % self.spec.version.up_to(2) spack_env.set('PARAVIEW_VTK_DIR', join_path(lib_dir, 'cmake', paraview_version)) def setup_environment(self, spack_env, run_env): if os.path.isdir(self.prefix.lib64): lib_dir = self.prefix.lib64 else: lib_dir = self.prefix.lib paraview_version = 'paraview-%s' % self.spec.version.up_to(2) run_env.prepend_path('LIBRARY_PATH', join_path(lib_dir, paraview_version)) run_env.prepend_path('LD_LIBRARY_PATH', join_path(lib_dir, paraview_version)) run_env.set('PARAVIEW_VTK_DIR', join_path(lib_dir, 'cmake', paraview_version)) if '+python' in self.spec: run_env.prepend_path('PYTHONPATH', join_path(lib_dir, paraview_version)) run_env.prepend_path('PYTHONPATH', join_path(lib_dir, paraview_version, 'site-packages')) run_env.prepend_path('PYTHONPATH', join_path(lib_dir, paraview_version, 'site-packages', 'vtk')) def cmake_args(self): """Populate cmake arguments for ParaView.""" spec = self.spec def variant_bool(feature, on='ON', off='OFF'): """Ternary for spec variant to ON/OFF string""" if feature in spec: return on return off def nvariant_bool(feature): """Negated ternary for spec variant to OFF/ON string""" return variant_bool(feature, on='OFF', off='ON') rendering = variant_bool('+opengl2', 'OpenGL2', 'OpenGL') includes = variant_bool('+plugins') cmake_args = [ '-DPARAVIEW_BUILD_QT_GUI:BOOL=%s' % variant_bool('+qt'), '-DVTK_OPENGL_HAS_OSMESA:BOOL=%s' % variant_bool('+osmesa'), '-DVTK_USE_X:BOOL=%s' % nvariant_bool('+osmesa'), '-DVTK_RENDERING_BACKEND:STRING=%s' % rendering, '-DPARAVIEW_INSTALL_DEVELOPMENT_FILES:BOOL=%s' % includes, '-DBUILD_TESTING:BOOL=OFF', '-DBUILD_EXAMPLES:BOOL=%s' % variant_bool('+examples'), '-DVTK_USE_SYSTEM_FREETYPE:BOOL=ON', '-DVTK_USE_SYSTEM_HDF5:BOOL=%s' % variant_bool('+hdf5'), '-DVTK_USE_SYSTEM_JPEG:BOOL=ON', '-DVTK_USE_SYSTEM_LIBXML2:BOOL=ON', '-DVTK_USE_SYSTEM_NETCDF:BOOL=OFF', '-DVTK_USE_SYSTEM_TIFF:BOOL=ON', '-DVTK_USE_SYSTEM_ZLIB:BOOL=ON', ] # The assumed qt version changed to QT5 (as of paraview 5.2.1), # so explicitly specify which QT major version is actually being used if '+qt' in spec: cmake_args.extend([ '-DPARAVIEW_QT_VERSION=%s' % spec['qt'].version[0], ]) if '+python' in spec: cmake_args.extend([ '-DPARAVIEW_ENABLE_PYTHON:BOOL=ON', '-DPYTHON_EXECUTABLE:FILEPATH=%s' % spec['python'].command.path ]) if '+mpi' in spec: cmake_args.extend([ '-DPARAVIEW_USE_MPI:BOOL=ON', '-DMPIEXEC:FILEPATH=%s/bin/mpiexec' % spec['mpi'].prefix, '-DMPI_CXX_COMPILER:PATH=%s' % spec['mpi'].mpicxx, '-DMPI_C_COMPILER:PATH=%s' % spec['mpi'].mpicc, '-DMPI_Fortran_COMPILER:PATH=%s' % spec['mpi'].mpifc ]) if 'darwin' in spec.architecture: cmake_args.extend([ '-DVTK_USE_X:BOOL=OFF', '-DPARAVIEW_DO_UNIX_STYLE_INSTALLS:BOOL=ON', ]) # Hide git from Paraview so it will not use `git describe` # to find its own version number if spec.satisfies('@5.4.0:5.4.1'): cmake_args.extend([ '-DGIT_EXECUTABLE=FALSE' ]) return cmake_args
krafczyk/spack
var/spack/repos/builtin/packages/paraview/package.py
Python
lgpl-2.1
8,421
[ "NetCDF", "ParaView", "VTK" ]
b30c372fefd470a86119021a0285cd39a89fe65849b08def0f1e0073b3d7cb05
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- from qiime2.plugin import (Plugin, Int, Float, Range, Metadata, Str, Bool, Choices, MetadataColumn, Categorical, List, Citations, TypeMatch) import q2_feature_table from q2_types.feature_table import ( FeatureTable, Frequency, RelativeFrequency, PresenceAbsence, Composition) from q2_types.feature_data import ( FeatureData, Sequence, Taxonomy, AlignedSequence) from .examples import (feature_table_merge_example, feature_table_merge_three_tables_example) citations = Citations.load('citations.bib', package='q2_feature_table') plugin = Plugin( name='feature-table', version=q2_feature_table.__version__, website='https://github.com/qiime2/q2-feature-table', package='q2_feature_table', short_description=('Plugin for working with sample by feature tables.'), description=('This is a QIIME 2 plugin supporting operations on sample ' 'by feature tables, such as filtering, merging, and ' 'transforming tables.') ) plugin.methods.register_function( function=q2_feature_table.rarefy, inputs={'table': FeatureTable[Frequency]}, parameters={'sampling_depth': Int % Range(1, None), 'with_replacement': Bool}, outputs=[('rarefied_table', FeatureTable[Frequency])], input_descriptions={'table': 'The feature table to be rarefied.'}, parameter_descriptions={ 'sampling_depth': ('The total frequency that each sample should be ' 'rarefied to. Samples where the sum of frequencies ' 'is less than the sampling depth will be not be ' 'included in the resulting table unless ' 'subsampling is performed with replacement.'), 'with_replacement': ('Rarefy with replacement by sampling from the ' 'multinomial distribution instead of rarefying ' 'without replacement.') }, output_descriptions={ 'rarefied_table': 'The resulting rarefied feature table.' }, name='Rarefy table', description=("Subsample frequencies from all samples so that the sum of " "frequencies in each sample is equal to sampling-depth."), citations=[citations['Weiss2017']] ) plugin.methods.register_function( function=q2_feature_table.subsample, inputs={'table': FeatureTable[Frequency]}, parameters={'subsampling_depth': Int % Range(1, None), 'axis': Str % Choices(['sample', 'feature'])}, outputs=[('sampled_table', FeatureTable[Frequency])], input_descriptions={'table': 'The feature table to be sampled.'}, parameter_descriptions={ 'subsampling_depth': ('The total number of samples or features to be ' 'randomly sampled. Samples or features that are ' 'reduced to a zero sum will not be included in ' 'the resulting table.'), 'axis': ('The axis to sample over. If "sample" then samples will be ' 'randomly selected to be retained. If "feature" then ' 'a random set of features will be selected to be retained.') }, output_descriptions={ 'sampled_table': 'The resulting subsampled feature table.' }, name='Subsample table', description=("Randomly pick samples or features, without replacement, " "from the table.") ) plugin.methods.register_function( function=q2_feature_table.presence_absence, inputs={'table': FeatureTable[Frequency | RelativeFrequency]}, parameters={}, outputs=[('presence_absence_table', FeatureTable[PresenceAbsence])], input_descriptions={ 'table': ('The feature table to be converted into presence/absence ' 'abundances.') }, parameter_descriptions={}, output_descriptions={ 'presence_absence_table': ('The resulting presence/absence feature ' 'table.') }, name="Convert to presence/absence", description="Convert frequencies to binary values indicating presence or " "absence of a feature in a sample." ) plugin.methods.register_function( function=q2_feature_table.relative_frequency, inputs={'table': FeatureTable[Frequency]}, parameters={}, outputs=[ ('relative_frequency_table', FeatureTable[RelativeFrequency])], input_descriptions={ 'table': 'The feature table to be converted into relative frequencies.' }, parameter_descriptions={}, output_descriptions={ 'relative_frequency_table': ('The resulting relative frequency ' 'feature table.') }, name="Convert to relative frequencies", description="Convert frequencies to relative frequencies by dividing each " "frequency in a sample by the sum of frequencies in that " "sample." ) plugin.methods.register_function( function=q2_feature_table.transpose, inputs={'table': FeatureTable[Frequency]}, parameters={}, outputs=[('transposed_feature_table', FeatureTable[Frequency])], input_descriptions={ 'table': 'The feature table to be transposed.' }, parameter_descriptions={}, output_descriptions={ 'transposed_feature_table': ('The resulting transposed feature table.') }, name='Transpose a feature table.', description='Transpose the rows and columns ' '(typically samples and features) of a feature table.' ) plugin.methods.register_function( function=q2_feature_table.group, inputs={'table': FeatureTable[Frequency]}, parameters={ 'mode': Str % Choices({'sum', 'median-ceiling', 'mean-ceiling'}), 'metadata': MetadataColumn[Categorical], 'axis': Str % Choices({'sample', 'feature'}) }, outputs=[ ('grouped_table', FeatureTable[Frequency]) ], input_descriptions={ 'table': 'The table to group samples or features on.' }, parameter_descriptions={ 'mode': 'How to combine samples or features within a group. `sum` ' 'will sum the frequencies across all samples or features ' 'within a group; `mean-ceiling` will take the ceiling of the ' 'mean of these frequencies; `median-ceiling` will take the ' 'ceiling of the median of these frequencies.', 'metadata': 'A column defining the groups. Each unique value will ' 'become a new ID for the table on the given `axis`.', 'axis': 'Along which axis to group. Each ID in the given axis must ' 'exist in `metadata`.' }, output_descriptions={ 'grouped_table': 'A table that has been grouped along the given ' '`axis`. IDs on that axis are replaced by values in ' 'the `metadata` column.' }, name="Group samples or features by a metadata column", description="Group samples or features in a feature table using metadata " "to define the mapping of IDs to a group." ) plugin.methods.register_function( function=q2_feature_table.merge, inputs={'tables': List[FeatureTable[Frequency]]}, parameters={ 'overlap_method': Str % Choices(q2_feature_table.overlap_methods()), }, outputs=[ ('merged_table', FeatureTable[Frequency])], input_descriptions={ 'tables': 'The collection of feature tables to be merged.', }, parameter_descriptions={ 'overlap_method': 'Method for handling overlapping ids.', }, output_descriptions={ 'merged_table': ('The resulting merged feature table.'), }, name="Combine multiple tables", description="Combines feature tables using the `overlap_method` provided.", examples={'basic': feature_table_merge_example, 'three_tables': feature_table_merge_three_tables_example}, ) plugin.methods.register_function( function=q2_feature_table.merge_seqs, inputs={'data': List[FeatureData[Sequence]]}, parameters={}, outputs=[ ('merged_data', FeatureData[Sequence])], input_descriptions={ 'data': 'The collection of feature sequences to be merged.', }, parameter_descriptions={}, output_descriptions={ 'merged_data': ('The resulting collection of feature sequences ' 'containing all feature sequences provided.') }, name="Combine collections of feature sequences", description="Combines feature data objects which may or may not " "contain data for the same features. If different feature " "data is present for the same feature id in the inputs, " "the data from the first will be propagated to the result." ) plugin.methods.register_function( function=q2_feature_table.merge_taxa, inputs={'data': List[FeatureData[Taxonomy]]}, parameters={}, outputs=[ ('merged_data', FeatureData[Taxonomy])], input_descriptions={ 'data': 'The collection of feature taxonomies to be merged.', }, parameter_descriptions={}, output_descriptions={ 'merged_data': ('The resulting collection of feature taxonomies ' 'containing all feature taxonomies provided.') }, name="Combine collections of feature taxonomies", description="Combines a pair of feature data objects which may or may not " "contain data for the same features. If different feature " "data is present for the same feature id in the inputs, " "the data from the first will be propagated to the result." ) T1 = TypeMatch([Frequency, RelativeFrequency, PresenceAbsence, Composition]) plugin.methods.register_function( function=q2_feature_table.rename_ids, inputs={ 'table': FeatureTable[T1], }, parameters={ 'metadata': MetadataColumn[Categorical], 'strict': Bool, 'axis': Str % Choices({'sample', 'feature'}) }, outputs=[ ('renamed_table', FeatureTable[T1]) ], input_descriptions={ 'table': 'The table to be renamed', }, parameter_descriptions={ 'metadata': 'A metadata column defining the new ids. Each original id ' 'must map to a new unique id. If strict mode is used, ' 'then every id in the original table must have a new id.', 'strict': 'Whether the naming needs to be strict (each id in ' 'the table must have a new id). Otherwise, only the ' 'ids described in `metadata` will be renamed and ' 'the others will keep their original id names.', 'axis': 'Along which axis to rename the ids.', }, output_descriptions={ 'renamed_table': 'A table which has new ids, where the ids are ' 'replaced by values in the `metadata` column.', }, name='Renames sample or feature ids in a table', description='Renames the sample or feature ids in a feature table using ' 'metadata to define the new ids.', ) # TODO: constrain min/max frequency when optional is handled by typemap plugin.methods.register_function( function=q2_feature_table.filter_samples, inputs={'table': FeatureTable[T1]}, parameters={'min_frequency': Int, 'max_frequency': Int, 'min_features': Int, 'max_features': Int, 'metadata': Metadata, 'where': Str, 'exclude_ids': Bool}, outputs=[('filtered_table', FeatureTable[T1])], input_descriptions={ 'table': 'The feature table from which samples should be filtered.' }, parameter_descriptions={ 'min_frequency': ('The minimum total frequency that a sample must ' 'have to be retained.'), 'max_frequency': ('The maximum total frequency that a sample can ' 'have to be retained. If no value is provided ' 'this will default to infinity (i.e., no maximum ' 'frequency filter will be applied).'), 'min_features': ('The minimum number of features that a sample must ' 'have to be retained.'), 'max_features': ('The maximum number of features that a sample can ' 'have to be retained. If no value is provided ' 'this will default to infinity (i.e., no maximum ' 'feature filter will be applied).'), 'metadata': 'Sample metadata used with `where` parameter when ' 'selecting samples to retain, or with `exclude_ids` ' 'when selecting samples to discard.', 'where': 'SQLite WHERE clause specifying sample metadata criteria ' 'that must be met to be included in the filtered feature ' 'table. If not provided, all samples in `metadata` that are ' 'also in the feature table will be retained.', 'exclude_ids': 'If true, the samples selected by `metadata` or ' '`where` parameters will be excluded from the filtered ' 'table instead of being retained.' }, output_descriptions={ 'filtered_table': 'The resulting feature table filtered by sample.' }, name="Filter samples from table", description="Filter samples from table based on frequency and/or " "metadata. Any features with a frequency of zero after sample " "filtering will also be removed. See the filtering tutorial " "on https://docs.qiime2.org for additional details." ) plugin.methods.register_function( function=q2_feature_table.filter_features_conditionally, inputs={'table': FeatureTable[T1]}, parameters={'prevalence': Float % Range(0, 1), 'abundance': Float % Range(0, 1) }, outputs=[('filtered_table', FeatureTable[T1])], input_descriptions={ 'table': 'The feature table from which features should be filtered.' }, parameter_descriptions={ 'abundance': ('The minimum relative abundance for a feature to be ' 'retained.'), 'prevalence': ('The minimum portion of samples that a feature ' 'must have a relative abundance of at least ' '`abundance` to be retained.') }, output_descriptions={ 'filtered_table': 'The resulting feature table filtered by feature.' }, name="Filter features from a table based on abundance and prevalence", description=("Filter features based on the relative abundance in a " "certain portion of samples (i.e., features must have a " "relative abundance of at least `abundance` in at least " "`prevalence` number of samples). Any samples with a " "frequency of zero after feature filtering will also be " "removed.") ) plugin.methods.register_function( function=q2_feature_table.filter_features, inputs={'table': FeatureTable[Frequency]}, parameters={'min_frequency': Int, 'max_frequency': Int, 'min_samples': Int, 'max_samples': Int, 'metadata': Metadata, 'where': Str, 'exclude_ids': Bool}, outputs=[('filtered_table', FeatureTable[Frequency])], input_descriptions={ 'table': 'The feature table from which features should be filtered.' }, parameter_descriptions={ 'min_frequency': ('The minimum total frequency that a feature must ' 'have to be retained.'), 'max_frequency': ('The maximum total frequency that a feature can ' 'have to be retained. If no value is provided ' 'this will default to infinity (i.e., no maximum ' 'frequency filter will be applied).'), 'min_samples': ('The minimum number of samples that a feature must ' 'be observed in to be retained.'), 'max_samples': ('The maximum number of samples that a feature can ' 'be observed in to be retained. If no value is ' 'provided this will default to infinity (i.e., no ' 'maximum sample filter will be applied).'), 'metadata': 'Feature metadata used with `where` parameter when ' 'selecting features to retain, or with `exclude_ids` ' 'when selecting features to discard.', 'where': 'SQLite WHERE clause specifying feature metadata criteria ' 'that must be met to be included in the filtered feature ' 'table. If not provided, all features in `metadata` that are ' 'also in the feature table will be retained.', 'exclude_ids': 'If true, the features selected by `metadata` or ' '`where` parameters will be excluded from the filtered ' 'table instead of being retained.' }, output_descriptions={ 'filtered_table': 'The resulting feature table filtered by feature.' }, name="Filter features from table", description="Filter features from table based on frequency and/or " "metadata. Any samples with a frequency of zero after feature " "filtering will also be removed. See the filtering tutorial " "on https://docs.qiime2.org for additional details." ) T2 = TypeMatch([Sequence, AlignedSequence]) plugin.methods.register_function( function=q2_feature_table.filter_seqs, inputs={ 'data': FeatureData[T2], 'table': FeatureTable[Frequency], }, parameters={ 'metadata': Metadata, 'where': Str, 'exclude_ids': Bool }, outputs=[('filtered_data', FeatureData[T2])], input_descriptions={ 'data': 'The sequences from which features should be filtered.', 'table': 'Table containing feature ids used for id-based filtering.' }, parameter_descriptions={ 'metadata': 'Feature metadata used for id-based filtering, with ' '`where` parameter when selecting features to retain, or ' 'with `exclude_ids` when selecting features to discard.', 'where': 'SQLite WHERE clause specifying feature metadata criteria ' 'that must be met to be included in the filtered feature ' 'table. If not provided, all features in `metadata` that are ' 'also in the sequences will be retained.', 'exclude_ids': 'If true, the features selected by the `metadata` ' '(with or without the `where` parameter) or `table` ' 'parameter will be excluded from the filtered ' 'sequences instead of being retained.' }, output_descriptions={ 'filtered_data': 'The resulting filtered sequences.' }, name="Filter features from sequences", description="Filter features from sequences based on a feature table or " "metadata. See the filtering tutorial on " "https://docs.qiime2.org for additional details. This method " "can filter based on ids in a table or a metadata file, but " "not both (i.e., the table and metadata options are mutually " "exclusive)." ) plugin.visualizers.register_function( function=q2_feature_table.summarize, inputs={'table': FeatureTable[Frequency | RelativeFrequency | PresenceAbsence]}, parameters={'sample_metadata': Metadata}, input_descriptions={'table': 'The feature table to be summarized.'}, parameter_descriptions={'sample_metadata': 'The sample metadata.'}, name="Summarize table", description="Generate visual and tabular summaries of a feature table." ) plugin.visualizers.register_function( function=q2_feature_table.tabulate_seqs, inputs={'data': FeatureData[Sequence | AlignedSequence]}, parameters={}, input_descriptions={'data': 'The feature sequences to be tabulated.'}, parameter_descriptions={}, name='View sequence associated with each feature', description="Generate tabular view of feature identifier to sequence " "mapping, including links to BLAST each sequence against " "the NCBI nt database.", citations=[citations['NCBI'], citations['NCBI-BLAST']] ) plugin.visualizers.register_function( function=q2_feature_table.core_features, inputs={ 'table': FeatureTable[Frequency] }, parameters={ 'min_fraction': Float % Range(0.0, 1.0, inclusive_start=False), 'max_fraction': Float % Range(0.0, 1.0, inclusive_end=True), 'steps': Int % Range(2, None) }, name='Identify core features in table', description=('Identify "core" features, which are features observed in a ' 'user-defined fraction of the samples. Since the core ' 'features are a function of the fraction of samples that the ' 'feature must be observed in to be considered core, this is ' 'computed over a range of fractions defined by the ' '`min_fraction`, `max_fraction`, and `steps` parameters.'), input_descriptions={ 'table': 'The feature table to use in core features calculations.' }, parameter_descriptions={ 'min_fraction': 'The minimum fraction of samples that a feature must ' 'be observed in for that feature to be considered a ' 'core feature.', 'max_fraction': 'The maximum fraction of samples that a feature must ' 'be observed in for that feature to be considered a ' 'core feature.', 'steps': 'The number of steps to take between `min_fraction` and ' '`max_fraction` for core features calculations. This ' 'parameter has no effect if `min_fraction` and ' '`max_fraction` are the same value.' } ) plugin.visualizers.register_function( function=q2_feature_table.heatmap, inputs={ 'table': FeatureTable[Frequency] }, parameters={ 'sample_metadata': MetadataColumn[Categorical], 'feature_metadata': MetadataColumn[Categorical], 'normalize': Bool, 'title': Str, 'metric': Str % Choices(q2_feature_table.heatmap_choices['metric']), 'method': Str % Choices(q2_feature_table.heatmap_choices['method']), 'cluster': Str % Choices(q2_feature_table.heatmap_choices['cluster']), 'color_scheme': Str % Choices( q2_feature_table.heatmap_choices['color_scheme']), }, name='Generate a heatmap representation of a feature table', description='Generate a heatmap representation of a feature table with ' 'optional clustering on both the sample and feature axes.\n\n' 'Tip: To generate a heatmap containing taxonomic annotations, ' 'use `qiime taxa collapse` to collapse the feature table at ' 'the desired taxonomic level.', input_descriptions={ 'table': 'The feature table to visualize.' }, parameter_descriptions={ 'sample_metadata': 'Annotate the sample IDs with these sample ' 'metadata values. When metadata is present and ' '`cluster`=\'feature\', samples will be sorted by ' 'the metadata values.', 'feature_metadata': 'Annotate the feature IDs with these feature ' 'metadata values. When metadata is present and ' '`cluster`=\'sample\', features will be sorted by ' 'the metadata values.', 'normalize': 'Normalize the feature table by adding a psuedocount ' 'of 1 and then taking the log10 of the table.', 'title': 'Optional custom plot title.', 'metric': 'Metrics exposed by seaborn (see http://seaborn.pydata.org/' 'generated/seaborn.clustermap.html#seaborn.clustermap for ' 'more detail).', 'method': 'Clustering methods exposed by seaborn (see http://seaborn.' 'pydata.org/generated/seaborn.clustermap.html#seaborn.clust' 'ermap for more detail).', 'cluster': 'Specify which axes to cluster.', 'color_scheme': 'The matplotlib colorscheme to generate the heatmap ' 'with.', }, citations=[citations['Hunter2007Matplotlib']] )
qiime2-plugins/feature-table
q2_feature_table/plugin_setup.py
Python
bsd-3-clause
25,499
[ "BLAST" ]
1408326bc87cd997079b5d2a686c932c3f2266886207fde72cd3719735bb6d48
"""PURPLE: Purity and ploidy estimates for somatic tumor/normal samples https://github.com/hartwigmedical/hmftools/tree/master/purity-ploidy-estimator """ import csv import os import re import shutil import subprocess import toolz as tz from bcbio import broad, utils from bcbio.log import logger from bcbio.distributed.transaction import file_transaction from bcbio.pipeline import config_utils from bcbio.pipeline import datadict as dd from bcbio.provenance import do from bcbio.structural import titancna from bcbio.variation import vcfutils def run(items): paired = vcfutils.get_paired(items) if not paired or not paired.normal_name: logger.info("Skipping PURPLE; need tumor/normal somatic calls in batch: %s" % " ".join([dd.get_sample_name(d) for d in items])) return items work_dir = _sv_workdir(paired.tumor_data) from bcbio import heterogeneity vrn_files = heterogeneity.get_variants(paired.tumor_data, include_germline=False) het_file = _amber_het_file("pon", vrn_files, work_dir, paired) depth_file = _run_cobalt(paired, work_dir) purple_out = _run_purple(paired, het_file, depth_file, vrn_files, work_dir) out = [] if paired.normal_data: out.append(paired.normal_data) if "sv" not in paired.tumor_data: paired.tumor_data["sv"] = [] paired.tumor_data["sv"].append(purple_out) out.append(paired.tumor_data) return out def _get_jvm_opts(out_file, data): """Retrieve Java options, adjusting memory for available cores. """ resources = config_utils.get_resources("purple", data["config"]) jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3500m"]) jvm_opts = config_utils.adjust_opts(jvm_opts, {"algorithm": {"memory_adjust": {"direction": "increase", "maximum": "30000M", "magnitude": dd.get_cores(data)}}}) jvm_opts += broad.get_default_jvm_opts(os.path.dirname(out_file)) return jvm_opts def _run_purple(paired, het_file, depth_file, vrn_files, work_dir): """Run PURPLE with pre-calculated AMBER and COBALT compatible inputs. """ purple_dir = utils.safe_makedir(os.path.join(work_dir, "purple")) out_file = os.path.join(purple_dir, "%s.purple.cnv" % dd.get_sample_name(paired.tumor_data)) if not utils.file_exists(out_file): with file_transaction(paired.tumor_data, out_file) as tx_out_file: cmd = ["PURPLE"] + _get_jvm_opts(tx_out_file, paired.tumor_data) + \ ["-amber", os.path.dirname(het_file), "-baf", het_file, "-cobalt", os.path.dirname(depth_file), "-gc_profile", dd.get_variation_resources(paired.tumor_data)["gc_profile"], "-output_dir", os.path.dirname(tx_out_file), "-ref_genome", "hg38" if dd.get_genome_build(paired.tumor_data) == "hg38" else "hg19", "-run_dir", work_dir, "-threads", dd.get_num_cores(paired.tumor_data), "-tumor_sample", dd.get_sample_name(paired.tumor_data), "-ref_sample", dd.get_sample_name(paired.normal_data)] if vrn_files: cmd += ["-somatic_vcf", vrn_files[0]["vrn_file"]] # Avoid X11 display errors when writing plots cmd = "unset DISPLAY && %s" % " ".join([str(x) for x in cmd]) do.run(cmd, "PURPLE: purity and ploidy estimation") for f in os.listdir(os.path.dirname(tx_out_file)): if f != os.path.basename(tx_out_file): shutil.move(os.path.join(os.path.dirname(tx_out_file), f), os.path.join(purple_dir, f)) out_file_export = os.path.join(purple_dir, "%s-purple-cnv.tsv" % (dd.get_sample_name(paired.tumor_data))) if not utils.file_exists(out_file_export): utils.symlink_plus(out_file, out_file_export) out = {"variantcaller": "purple", "call_file": out_file_export, "vrn_file": titancna.to_vcf(out_file_export, "PURPLE", _get_header, _export_to_vcf, paired.tumor_data), "plot": {}, "metrics": {}} for name, ext in [("copy_number", "copyNumber"), ("minor_allele", "minor_allele"), ("variant", "variant")]: plot_file = os.path.join(purple_dir, "plot", "%s.%s.png" % (dd.get_sample_name(paired.tumor_data), ext)) if os.path.exists(plot_file): out["plot"][name] = plot_file purity_file = os.path.join(purple_dir, "%s.purple.purity" % dd.get_sample_name(paired.tumor_data)) with open(purity_file) as in_handle: header = in_handle.readline().replace("#", "").split("\t") vals = in_handle.readline().split("\t") for h, v in zip(header, vals): try: v = float(v) except ValueError: pass out["metrics"][h] = v return out def _normalize_baf(baf): """Provide normalized BAF in the same manner as Amber, relative to het. https://github.com/hartwigmedical/hmftools/blob/637e3db1a1a995f4daefe2d0a1511a5bdadbeb05/hmf-common/src7/main/java/com/hartwig/hmftools/common/amber/AmberBAF.java#L16 """ if baf is None: baf = 0.0 return 0.5 + abs(baf - 0.5) def _counts_to_amber(t_vals, n_vals): """Converts a line of CollectAllelicCounts into AMBER line. """ t_depth = int(t_vals["REF_COUNT"]) + int(t_vals["ALT_COUNT"]) n_depth = int(n_vals["REF_COUNT"]) + int(n_vals["ALT_COUNT"]) if n_depth > 0 and t_depth > 0: t_baf = float(t_vals["ALT_COUNT"]) / float(t_depth) n_baf = float(n_vals["ALT_COUNT"]) / float(n_depth) return [t_vals["CONTIG"], t_vals["POSITION"], t_baf, _normalize_baf(t_baf), t_depth, n_baf, _normalize_baf(n_baf), n_depth] def _count_files_to_amber(tumor_counts, normal_counts, work_dir, data): """Converts tumor and normal counts from GATK CollectAllelicCounts into Amber format. """ amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(data)) if not utils.file_uptodate(out_file, tumor_counts): with file_transaction(data, out_file) as tx_out_file: with open(tumor_counts) as tumor_handle: with open(normal_counts) as normal_handle: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, delimiter="\t") writer.writerow(["Chromosome", "Position", "TumorBAF", "TumorModifiedBAF", "TumorDepth", "NormalBAF", "NormalModifiedBAF", "NormalDepth"]) header = None for t, n in zip(tumor_handle, normal_handle): if header is None and t.startswith("CONTIG"): header = t.strip().split() elif header is not None: t_vals = dict(zip(header, t.strip().split())) n_vals = dict(zip(header, n.strip().split())) amber_line = _counts_to_amber(t_vals, n_vals) if amber_line: writer.writerow(amber_line) return out_file class AmberWriter: def __init__(self, out_handle): self.writer = csv.writer(out_handle, delimiter="\t") def write_header(self): self.writer.writerow(["Chromosome", "Position", "TumorBAF", "TumorModifiedBAF", "TumorDepth", "NormalBAF", "NormalModifiedBAF", "NormalDepth"]) def write_row(self, rec, stats): if stats["normal"]["freq"] is not None and stats["normal"]["depth"] is not None: self.writer.writerow([rec.chrom, rec.pos, stats["tumor"]["freq"], _normalize_baf(stats["tumor"]["freq"]), stats["tumor"]["depth"], stats["normal"]["freq"], _normalize_baf(stats["normal"]["freq"]), stats["normal"]["depth"]]) def _amber_het_file(method, vrn_files, work_dir, paired): """Create file of BAFs in normal heterozygous positions compatible with AMBER. Two available methods: - pon -- Use panel of normals with likely heterozygous sites. - variants -- Use pre-existing variant calls, filtered to likely heterozygotes. https://github.com/hartwigmedical/hmftools/tree/master/amber https://github.com/hartwigmedical/hmftools/blob/637e3db1a1a995f4daefe2d0a1511a5bdadbeb05/hmf-common/src/test/resources/amber/new.amber.baf """ assert vrn_files, "Did not find compatible variant calling files for PURPLE inputs" from bcbio.heterogeneity import bubbletree if method == "variants": amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(paired.tumor_data)) prep_file = bubbletree.prep_vrn_file(vrn_files[0]["vrn_file"], vrn_files[0]["variantcaller"], work_dir, paired, AmberWriter) utils.symlink_plus(prep_file, out_file) pcf_file = out_file + ".pcf" if not utils.file_exists(pcf_file): with file_transaction(paired.tumor_data, pcf_file) as tx_out_file: r_file = os.path.join(os.path.dirname(tx_out_file), "bafSegmentation.R") with open(r_file, "w") as out_handle: out_handle.write(_amber_seg_script) cmd = "%s && %s --vanilla %s %s %s" % (utils.get_R_exports(), utils.Rscript_cmd(), r_file, out_file, pcf_file) do.run(cmd, "PURPLE: AMBER baf segmentation") else: assert method == "pon" out_file = _run_amber(paired, work_dir) return out_file def _run_amber(paired, work_dir, lenient=False): """AMBER: calculate allele frequencies at likely heterozygous sites. lenient flag allows amber runs on small test sets. """ amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(paired.tumor_data)) if not utils.file_exists(out_file) or not utils.file_exists(out_file + ".pcf"): with file_transaction(paired.tumor_data, out_file) as tx_out_file: key = "germline_het_pon" het_bed = tz.get_in(["genome_resources", "variation", key], paired.tumor_data) cmd = ["AMBER"] + _get_jvm_opts(tx_out_file, paired.tumor_data) + \ ["-threads", dd.get_num_cores(paired.tumor_data), "-tumor", dd.get_sample_name(paired.tumor_data), "-tumor_bam", dd.get_align_bam(paired.tumor_data), "-reference", dd.get_sample_name(paired.normal_data), "-reference_bam", dd.get_align_bam(paired.normal_data), "-ref_genome", dd.get_ref_file(paired.tumor_data), "-bed", het_bed, "-output_dir", os.path.dirname(tx_out_file)] if lenient: cmd += ["-max_het_af_percent", "1.0"] try: do.run(cmd, "PURPLE: AMBER baf generation") except subprocess.CalledProcessError as msg: if not lenient and _amber_allowed_errors(str(msg)): return _run_amber(paired, work_dir, True) for f in os.listdir(os.path.dirname(tx_out_file)): if f != os.path.basename(tx_out_file): shutil.move(os.path.join(os.path.dirname(tx_out_file), f), os.path.join(amber_dir, f)) return out_file def _amber_allowed_errors(msg): allowed = ["R execution failed. Unable to complete segmentation."] return any([len(re.findall(m, msg)) > 0 for m in allowed]) # BAF segmentation with copynumber from AMBER # https://github.com/hartwigmedical/hmftools/blob/master/amber/src/main/resources/r/bafSegmentation.R _amber_seg_script = """ # Parse the arguments args <- commandArgs(trailing=T) bafFile <- args[1] pcfFile <- args[2] library(copynumber) baf <- read.table(bafFile, header=TRUE) chromosomeLevels = levels(baf$Chromosome) chromosomePrefix = "" if (any(grepl("chr", chromosomeLevels, ignore.case = T))) { chromosomePrefix = substr(chromosomeLevels[1], 1, 3) } baf <- baf[,c("Chromosome","Position","TumorModifiedBAF")] baf$Chromosome <- gsub(chromosomePrefix, "", baf$Chromosome, ignore.case = T) baf.seg<-pcf(baf,verbose=FALSE,gamma=100,kmin=1) baf.seg$chrom = paste0(chromosomePrefix, baf.seg$chrom) write.table(baf.seg, file = pcfFile, row.names = F, sep = "\t", quote = F) """ def _run_cobalt(paired, work_dir): """Run Cobalt for counting read depth across genomic windows. PURPLE requires even 1000bp windows so use integrated counting solution directly rather than converting from CNVkit calculations. If this approach is useful should be moved upstream to be available to other tools as an input comparison. https://github.com/hartwigmedical/hmftools/tree/master/count-bam-lines """ cobalt_dir = utils.safe_makedir(os.path.join(work_dir, "cobalt")) out_file = os.path.join(cobalt_dir, "%s.cobalt" % dd.get_sample_name(paired.tumor_data)) if not utils.file_exists(out_file): with file_transaction(paired.tumor_data, out_file) as tx_out_file: cmd = ["COBALT"] + _get_jvm_opts(tx_out_file, paired.tumor_data) + \ ["-reference", paired.normal_name, "-reference_bam", paired.normal_bam, "-tumor", paired.tumor_name, "-tumor_bam", paired.tumor_bam, "-threads", dd.get_num_cores(paired.tumor_data), "-output_dir", os.path.dirname(tx_out_file), "-gc_profile", dd.get_variation_resources(paired.tumor_data)["gc_profile"]] cmd = "%s && %s" % (utils.get_R_exports(), " ".join([str(x) for x in cmd])) do.run(cmd, "PURPLE: COBALT read depth normalization") for f in os.listdir(os.path.dirname(tx_out_file)): if f != os.path.basename(tx_out_file): shutil.move(os.path.join(os.path.dirname(tx_out_file), f), os.path.join(cobalt_dir, f)) return out_file def _cobalt_ratio_file(paired, work_dir): """Convert CNVkit binning counts into cobalt ratio output. This contains read counts plus normalization for GC, from section 7.2 "Determine read depth ratios for tumor and reference genomes" https://www.biorxiv.org/content/biorxiv/early/2018/09/20/415133.full.pdf Since CNVkit cnr files already have GC bias correction, we re-center the existing log2 ratios to be around 1, rather than zero, which matches the cobalt expectations. XXX This doesn't appear to be a worthwhile direction since PURPLE requires 1000bp even binning. We'll leave this here as a starting point for future work but work on using cobalt directly. """ cobalt_dir = utils.safe_makedir(os.path.join(work_dir, "cobalt")) out_file = os.path.join(cobalt_dir, "%s.cobalt" % dd.get_sample_name(paired.tumor_data)) if not utils.file_exists(out_file): cnr_file = tz.get_in(["depth", "bins", "normalized"], paired.tumor_data) with file_transaction(paired.tumor_data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, delimiter="\t") writer.writerow(["Chromosome", "Position", "ReferenceReadCount", "TumorReadCount", "ReferenceGCRatio", "TumorGCRatio", "ReferenceGCDiploidRatio"]) raise NotImplementedError return out_file def _sv_workdir(data): return utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", dd.get_sample_name(data), "purple")) # ## VCF output def _get_header(in_handle): return in_handle.readline().replace("#", "").strip().split(), in_handle def _export_to_vcf(cur): """Convert PURPLE custom output into VCF. """ if float(cur["copyNumber"]) > 2.0: svtype = "DUP" elif float(cur["copyNumber"]) < 2.0: svtype = "DEL" else: svtype = None if svtype: info = ["END=%s" % cur["end"], "SVLEN=%s" % (int(cur["end"]) - int(cur["start"])), "SVTYPE=%s" % svtype, "CN=%s" % cur["copyNumber"], "PROBES=%s" % cur["depthWindowCount"]] return [cur["chromosome"], cur["start"], ".", "N", "<%s>" % svtype, ".", ".", ";".join(info), "GT", "0/1"]
a113n/bcbio-nextgen
bcbio/structural/purple.py
Python
mit
16,992
[ "Amber" ]
6e833837bc37de0eccd4b7543a7f1ee15f8051791a490ef011160277f813e309
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Main simulation script for setting up the model producing the data shown in figure 4, 5 and 6 in: Multimodal modeling of neural network activity: computing LFP, ECoG, EEG and MEG signals with LFPy2.0 Espen Hagen, Solveig Næss, Torbjørn V Ness, Gaute T Einevoll bioRxiv 281717; doi: https://doi.org/10.1101/281717 This example file is not suited for execution on laptops or desktop computers. In the corresponding parameter file example_parallel_network_parameters.py there is an option to set TESTING = True which will set the number of neurons in each network population to one, which facilitates testing for missing files or data. Otherwise, the full number of neurons in each population will be created. Various biophysically detailed neuron models required for these simulations can be obtained from The Neocortical Microcircuit Collaboration Portal (https://bbp.epfl.ch/nmc-portal/welcome) providing the cell models used in a reconstruction of a rat somatosensory cortex column described in: Markram H, Muller E, Ramaswamy S†, Reimann MW, Abdellah M, Sanchez CA, Ailamaki A, Alonso-Nanclares L, Antille N, Arsever S et al. (2015). Reconstruction and Simulation of Neocortical Microcircuitry. Cell 163:2, 456 - 492. doi: 10.1016/j.cell.2015.09.029 A tar file with all single-cell models zipped can be downloaded and unpacked by issuing: $ wget https://bbp.epfl.ch/nmc-portal/assets/documents/static/Download/\ hoc_combos_syn.1_0_10.allzips.tar $ tar -xvf hoc_combos_syn.1_0_10.allzips.tar $ cd hoc_combos_syn.1_0_10.allzips $ unzip 'L4_PC_*.zip' $ unzip 'L4_LBC_*.zip' $ unzip 'L5_TTPC1_*.zip' $ unzip 'L5_MC_*.zip' $ cd - .json files with anatomy and physiology data of the microcircuit are also needed: $ wget https://bbp.epfl.ch/nmc-portal/assets/documents/static/Download/\ pathways_anatomy_factsheets_simplified.json $ wget https://bbp.epfl.ch/nmc-portal/assets/documents/static/Download/\ pathways_physiology_factsheets_simplified.json Some preparatory steps has to be made in order to compile NMODL language files used by the neuron models: Set working dir >>> import os >>> import sys >>> import neuron >>> from glob import glob >>> CWD = os.getcwd() >>> NMODL = 'hoc_combos_syn.1_0_10.allmods' Load some required neuron-interface files >>> neuron.h.load_file("stdrun.hoc") >>> neuron.h.load_file("import3d.hoc") Load only some layer 5 pyramidal cell types Define a list of the neuron models (defined in the parameter file) >>> neurons = [os.path.join('hoc_combos_syn.1_0_10.allzips', 'L4_PC_cADpyr230_1'), os.path.join('hoc_combos_syn.1_0_10.allzips', 'L4_LBC_dNAC222_1'), os.path.join('hoc_combos_syn.1_0_10.allzips', 'L5_TTPC1_cADpyr232_1'), os.path.join('hoc_combos_syn.1_0_10.allzips', 'L5_MC_bAC217_1')] Attempt to set up a folder with all unique mechanism mod files, compile, and load them all. One synapse mechanism file is faulty and must be patched. >>> if not os.path.isdir(NMODL): >>> os.mkdir(NMODL) >>> for NRN in neurons: >>> for nmodl in glob(os.path.join(NRN, 'mechanisms', '*.mod')): >>> while not os.path.isfile(os.path.join(NMODL, >>> os.path.split(nmodl)[-1])): >>> if "win32" in sys.platform: >>> os.system("copy {} {}".format(nmodl, NMODL)) >>> else: >>> os.system('cp {} {}'.format(nmodl, >>> os.path.join(NMODL, >>> '.'))) >>> os.chdir(NMODL) >>> diff = """319c319 < urand = scop_random(1) --- > value = scop_random(1) """ >>> f = open('ProbGABAAB_EMS.patch', 'w') >>> f.writelines(diff) >>> f.close() >>> os.system('patch ProbGABAAB_EMS.mod ProbGABAAB_EMS.patch') >>> if "win32" in sys.platform: >>> warn("no autompile of NMODL (.mod) files on Windows. " >>> + "Run mknrndll from NEURON bash in the folder " >>> + "%s and rerun example script" % NMODL) >>> else: >>> os.system('nrnivmodl') >>> os.chdir(CWD) An example job script set up using the SLURM workload management software (https://slurm.schedmd.com/) on a compute cluster is provided in the file example_parallel_network.job. This job script asks for exclusive access to 24 nodes with 24 physical CPU cores each. Adjust accordingly for other clusters. The job can be submitted issuing: $ sbatch example_parallel_network.job Execution example: $ mpirun -np 1152 python example_parallel_network.py Output is stored in the folder ./example_parallel_network_output, which is set in the parameter file. Adjust accordingly to use the work area on your cluster. Some pdf figures are saved as example_parallel_network*.pdf, showing somatic responses of different cells on some MPI processes The script uses some plotting routines from the file example_parallel_network_plotting.py If the simulation finished successfully, the figures 4-6 from the manuscript can be generated by issuing: $ python figure_4.py $ python figure_5.py $ python figure_6.py Copyright (C) 2018 Computational Neuroscience Group, NMBU. 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. ''' from mpi4py import MPI import LFPy from time import time import os import h5py from distutils.version import LooseVersion import numpy as np from matplotlib.gridspec import GridSpec from matplotlib.collections import PolyCollection from matplotlib.ticker import MaxNLocator import matplotlib.pyplot as plt from scipy.signal import decimate import neuron import matplotlib matplotlib.use('agg') if LooseVersion(h5py.version.hdf5_version) < LooseVersion('1.8.16'): raise ImportError('h5py uses HDF5 v{}: v1.8.16 or newer required'.format( h5py.version.hdf5_version)) # set up MPI environment COMM = MPI.COMM_WORLD SIZE = COMM.Get_size() RANK = COMM.Get_rank() # set default plotting parameters fontsize = 8 plt.rcParams.update({ 'axes.xmargin': 0.0, 'axes.ymargin': 0.0, 'axes.labelsize': fontsize, 'axes.titlesize': fontsize, 'axes.titleweight': fontsize, 'figure.titlesize': fontsize, 'font.size': fontsize, 'legend.fontsize': fontsize, }) # tic toc tic = time() # avoid same sequence of random numbers from numpy and neuron on each RANK, # e.g., in order to draw unique cell locations and random synapse activation # times GLOBALSEED = 1234 np.random.seed(GLOBALSEED + RANK) ########################################################################## # Main simulation procedure ########################################################################## if __name__ == '__main__': # Remove cells from previous script executions neuron.h('forall delete_section()') ########################################################################## # Simulation control and parameters ########################################################################## # import LFPy.NetworkCell and Network classes from LFPy import NetworkCell, Network # tic-toc if RANK == 0: initialization_time = time() - tic print('Initialization in {} seconds'.format(initialization_time)) tic = time() # import main parameters dictionary for simulation from example_parallel_network_parameters import PSET # set up file destination if RANK == 0: # create directory for output: if not os.path.isdir(PSET.OUTPUTPATH): os.mkdir(PSET.OUTPUTPATH) # remove old simulation output if directory exist else: for fname in os.listdir(PSET.OUTPUTPATH): os.unlink(os.path.join(PSET.OUTPUTPATH, fname)) COMM.Barrier() # Modify release probabilities of excitatory synapses in order to # stabilize circuit. # This change is incorporated in https://github.com/LFPy/LFPy/pull/320 # which modifies slightly the way multapse counts are generated # (and hence affected the network state compared to the old behaviour) for i, pre in enumerate(PSET.populationParameters['m_type']): for j, post in enumerate(PSET.populationParameters['m_type']): if (pre in ['L4_PC', 'L5_TTPC1']) & (pre == post): PSET.connParams['synparams'][i][j]['Use'] = \ PSET.connParams['synparams'][i][j]['Use'] * 0.8 if RANK == 0: parameters_time = time() - tic print('Parameters in {} seconds'.format(parameters_time)) tic = time() ########################################################################## # Create population, provide noisy input to each cell, connect network ########################################################################## # create network object instance network = Network(dt=PSET.dt, tstop=PSET.tstop, v_init=PSET.v_init, celsius=PSET.celsius, OUTPUTPATH=PSET.OUTPUTPATH) # create populations iteratively for name, pop_args, rotation_args, POP_SIZE in zip( PSET.populationParameters['me_type'], PSET.populationParameters['pop_args'], PSET.populationParameters['rotation_args'], (PSET.populationParameters['POP_SIZE'] * PSET.POPSCALING).astype(int)): network.create_population(CWD=PSET.CWD, CELLPATH=PSET.CELLPATH, Cell=NetworkCell, POP_SIZE=POP_SIZE, name=name, cell_args=PSET.cellParameters[name], pop_args=pop_args, rotation_args=rotation_args) # tic-toc if RANK == 0: create_population_time = time() - tic print('Populations initialized in {} seconds'.format( create_population_time)) tic = time() # Sync MPI threads as populations may take a different amount of # time across RANKs. All neurons must have been created before connections # are made COMM.Barrier() # # # Attach current stimulus to the soma of the cell with gid 0. # if False: # for name in PSET.populationParameters['me_type']: # for cell in network.populations[name].cells: # if cell.gid == 0: # LFPy.StimIntElectrode(cell, # amp = 0.4, # **PSET.PointProcParams) # create for each cell in each population some external input with Poisson # statistics using NEURON's NetStim device (controlled using LFPy.Synapse) for m_type, me_type, section, rho, f, synparams, weightfun, weightargs \ in zip(PSET.populationParameters['m_type'], PSET.populationParameters['me_type'], PSET.populationParameters['extrinsic_input_section'], PSET.populationParameters['extrinsic_input_density'], PSET.populationParameters['extrinsic_input_frequency'], PSET.connParamsExtrinsic['synparams'], PSET.connParamsExtrinsic['weightfuns'], PSET.connParamsExtrinsic['weightargs']): for cell in network.populations[me_type].cells: idx = cell.get_rand_idx_area_norm( section=section, nidx=int(cell.area[cell.get_idx(section)].sum() * rho)) for i in idx: syn = LFPy.Synapse(cell=cell, idx=i, syntype=PSET.connParamsExtrinsic['syntype'], weight=weightfun(**weightargs), **synparams) syn.set_spike_times_w_netstim(interval=1000. / f, seed=np.random.rand() * 2**32 - 1 ) # connect pre and post-synaptic populations with some connectivity and # weight of connections and other connection parameters: total_conncount = 0 total_syncount = 0 for i, pre in enumerate(PSET.populationParameters['me_type']): for j, post in enumerate(PSET.populationParameters['me_type']): # boolean connectivity matrix between pre- and post-synaptic # neurons in each population (postsynaptic on this RANK) connectivity = network.get_connectivity_rand( pre=pre, post=post, connprob=PSET.connParams['connprob'][i][j]) # connect network (conncount, syncount) = network.connect( pre=pre, post=post, connectivity=connectivity, syntype=PSET.connParams['syntypes'][i][j], synparams=PSET.connParams['synparams'][i][j], weightfun=PSET.connParams['weightfuns'][i][j], weightargs=PSET.connParams['weightargs'][i][j], delayfun=PSET.connParams['delayfuns'][i][j], delayargs=PSET.connParams['delayargs'][i][j], mindelay=PSET.connParams['mindelay'], multapsefun=PSET.connParams['multapsefuns'][i][j], multapseargs=PSET.connParams['multapseargs'][i][j], syn_pos_args=PSET.connParams['syn_pos_args'][i][j], save_connections=PSET.save_connections, ) total_conncount += conncount total_syncount += syncount # tic-toc if RANK == 0: create_connections_time = time() - tic print('Network build finished with ' '{} connections and {} synapses in {} seconds'.format( total_conncount, total_syncount, create_connections_time)) tic = time() ########################################################################## # Set up extracellular electrodes and devices ########################################################################## probes = [] if PSET.COMPUTE_LFP: electrode = LFPy.RecExtElectrode(cell=None, **PSET.electrodeParams) probes.append(electrode) if PSET.COMPUTE_ECOG: ecog_electrode = LFPy.RecMEAElectrode(cell=None, **PSET.ecogParameters) probes.append(ecog_electrode) if PSET.COMPUTE_P: current_dipole_moment = LFPy.CurrentDipoleMoment(cell=None) probes.append(current_dipole_moment) ########################################################################## # Recording of additional variables ########################################################################## if RANK == 0: network.t = neuron.h.Vector() network.t.record(neuron.h._ref_t) else: network.t = None ########################################################################## # run simulation, gather results across all RANKs ########################################################################## # Assert that connect routines has finished across RANKS before starting # main simulation procedure COMM.Barrier() if RANK == 0: print('running simulation....') SPIKES = network.simulate(probes=probes, rec_pop_contributions=PSET.rec_pop_contributions, **PSET.NetworkSimulateArgs) if RANK == 0: run_simulation_time = time() - tic print('Simulations finished in {} seconds'.format(run_simulation_time)) tic = time() ########################################################################## # save simulated output to file to allow for offline plotting ########################################################################## if RANK == 0: f = h5py.File(os.path.join(PSET.OUTPUTPATH, 'example_parallel_network_output.h5'), 'w') if PSET.COMPUTE_P: # save current dipole moment f['CURRENT_DIPOLE_MOMENT'] = current_dipole_moment.data if PSET.COMPUTE_LFP: # save all extracellular traces f['SUMMED_OUTPUT'] = electrode.data if PSET.COMPUTE_ECOG: # save extracellular potential on top of cortex f['SUMMED_ECOG'] = ecog_electrode.data # all spikes grp = f.create_group('SPIKES') # variable length datatype for spike time arrays dtype = h5py.special_dtype(vlen=np.dtype('float')) for i, name in enumerate(PSET.populationParameters['me_type']): subgrp = grp.create_group(name) if len(SPIKES['gids'][i]) > 0: subgrp['gids'] = np.array(SPIKES['gids'][i]).flatten() dset = subgrp.create_dataset('times', (len(SPIKES['gids'][i]),), dtype=dtype) for j, spt in enumerate(SPIKES['times'][i]): dset[j] = spt else: subgrp['gids'] = [] subgrp['times'] = [] f.close() COMM.Barrier() # clean up namespace del electrode, ecog_electrode, current_dipole_moment, probes # tic toc if RANK == 0: saving_data_time = time() - tic print('Wrote output files in {} seconds'.format(saving_data_time)) tic = time() # create logfile recording time in seconds for different simulation steps # (initialization, parameters, simulation etc.) if RANK == 0: logfile = open(os.path.join(PSET.OUTPUTPATH, 'log.txt'), 'w') logfile.write('initialization {}\n'.format(initialization_time)) logfile.write('parameters {}\n'.format(parameters_time)) logfile.write('population {}\n'.format(create_population_time)) logfile.write('connections {}\n'.format(create_connections_time)) logfile.write('simulation {}\n'.format(run_simulation_time)) logfile.write('save {}\n'.format(saving_data_time)) logfile.close() if __name__ == '__main__': ########################################################################## # Plot simulated output (relies on Network class instance) ########################################################################## T = (PSET.TRANSIENT, PSET.tstop) colors = [plt.get_cmap('Set1', PSET.populationParameters.size)(i) for i in range(PSET.populationParameters.size)] # don't want thousands of figure files: PLOTRANKS = np.arange(0, SIZE, 16) if SIZE >= 48 else np.arange(SIZE) if RANK in PLOTRANKS: fig = plt.figure(figsize=(20, 10)) fig.subplots_adjust(left=0.2) nrows = np.sum([len(population.gids) for population in network.populations.values()]) ncols = 1 gs = GridSpec(nrows=nrows, ncols=ncols) fig.suptitle('RANK {}'.format(RANK)) counter = 0 # somatic traces tvec = np.arange(PSET.tstop / PSET.dt + 1) * PSET.dt tinds = tvec >= PSET.TRANSIENT for i, name in enumerate(PSET.populationParameters['me_type']): population = network.populations[name] for j, cell in enumerate(population.cells): ax = fig.add_subplot(gs[counter, 0]) if counter == 0: ax.set_title('somatic voltages') ax.plot(tvec[tinds][::PSET.decimate_q], decimate(cell.somav[tinds], q=PSET.decimate_q), color=colors[i], lw=1.5, label=name) ax.set_ylabel('gid {}'.format(population.gids[j]), rotation='horizontal', labelpad=30) ax.axis(ax.axis('tight')) ax.set_ylim(-90, -20) ax.legend(loc='best') ax.yaxis.set_major_locator(MaxNLocator(nbins=3)) counter += 1 if counter == nrows: ax.set_xlabel('time (ms)') else: ax.set_xticklabels([]) # save figure output fig.savefig(os.path.join(PSET.OUTPUTPATH, 'example_parallel_network_RANK_{}.pdf'.format( RANK)), bbox_inches='tight') plt.close(fig) # make an illustration of the different populations on each RANK. if RANK in PLOTRANKS: # don't want thousands of figure files # figure out which populations has at least one cell on this RANK local_me_types = [] for i, name in enumerate(PSET.populationParameters['me_type']): if len(network.populations[name].gids) >= 1: local_me_types += [name] fig, axes = plt.subplots(1, len(local_me_types) + 1, figsize=((len(local_me_types) + 1) * 5, 10), sharey=True, sharex=True) ax = axes[0] # plot electrode contact points ax.plot(PSET.electrodeParams['x'], PSET.electrodeParams['z'], 'ko', markersize=5) # plot cell geometries for i, name in enumerate(PSET.populationParameters['me_type']): population = network.populations[name] zips = [] for cell in population.cells: for x, z in cell.get_idx_polygons(projection=('x', 'z')): zips.append(list(zip(x, z))) polycol = PolyCollection(zips, edgecolors=colors[i], linewidths=0.01, facecolors=colors[i], label=name, ) ax.add_collection(polycol) ax.set_xlim(-400, 400) axis = ax.axis() ax.hlines(np.r_[0., -PSET.layer_data['thickness'].cumsum()], axis[0], axis[1], 'k', lw=0.5) ax.set_xticks([-400, 0, 400]) ax.set_xlabel(r'x ($\mu$m)') ax.set_ylabel(r'z ($\mu$m)') ax.set_title('network populations') # for i, (name, population) in enumerate(network.populations.items()): j = 1 # counter for i, name in enumerate(PSET.populationParameters['me_type']): if name in local_me_types: population = network.populations[name] ax = axes[j] # plot electrode contact points ax.plot(PSET.electrodeParams['x'], PSET.electrodeParams['z'], 'ko', markersize=5) # plot cell geometries and synapse locations zips = [] synpos_e = [] synpos_i = [] for cell in population.cells: for x, z in cell.get_idx_polygons(projection=('x', 'z')): zips.append(list(zip(x, z))) for idx, syn in zip(cell.synidx, cell.netconsynapses): if hasattr(syn, 'e') and syn.e > -50: synpos_e += [[cell.x[idx].mean(), cell.z[idx].mean()]] else: synpos_i += [[cell.x[idx].mean(), cell.z[idx].mean()]] polycol = PolyCollection(zips, edgecolors=colors[i], linewidths=0.01, facecolors=colors[i], label=name, ) ax.add_collection(polycol) synpos_e = np.array(synpos_e) synpos_i = np.array(synpos_i) if synpos_e.size > 0: ax.plot(synpos_e[:, 0], synpos_e[:, 1], 'r.', markersize=3, zorder=1) if synpos_i.size > 0: ax.plot(synpos_i[:, 0], synpos_i[:, 1], 'b.', markersize=1.5, zorder=2) ax.set_xlim(-400, 400) axis = ax.axis() ax.hlines(np.r_[0., -PSET.layer_data['thickness'].cumsum()], axis[0], axis[1], 'k', lw=0.5) ax.set_xticks([-400, 0, 400]) ax.set_xlabel(r'x ($\mu$m)') ax.set_title(name) j += 1 # counter # save figure output fig.savefig(os.path.join( PSET.OUTPUTPATH, 'example_parallel_network_populations_RANK_{}.pdf'.format(RANK)), bbox_inches='tight') plt.close(fig) ########################################################################## # customary cleanup of object references - the psection() function may not # write correct information if NEURON still has object references in memory # even if Python references has been deleted. It will also allow the script # to be run in successive fashion. ########################################################################## network.pc.gid_clear() # allows assigning new gids to threads for population in network.populations.values(): for cell in population.cells: cell = None population.cells = None population = None network = None neuron.h('forall delete_section()')
LFPy/LFPy
examples/bioRxiv281717/example_parallel_network.py
Python
gpl-3.0
25,962
[ "NEURON" ]
c438cecf064da3ee5cdbbfdfb9e76082c793b7bc30dda6ff2c24b3565f22dfdc
########################################################### # Import ########################################################### # Import import os import sys from Bio import motifs from pysam import Samfile from pysam import Fastafile from MOODS import search ########################################################### # Input ########################################################### # Input bedFileName = sys.argv[1] pfmFileNameList = sys.argv[2].split(",") genomeFileName = sys.argv[3] footprintBamFileName = sys.argv[4] dnaseBamFileName = sys.argv[5] outputFileName = sys.argv[6] # Parameters tcHalfWindowVec = [50] maxReadPile = 1000 ########################################################### # Functions / Classes ########################################################### # Motif class class Motif: def __init__(self, input_file_name): input_file = open(input_file_name, "r") self.pfm = motifs.read(input_file, "pfm") self.pwm = self.pfm.counts.normalize(0.0001) input_file.close() self.len = len(self.pfm) background = {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25} self.pssm = self.pwm.log_odds(background) self.pssm_list = [self.pssm[e] for e in ["A", "C", "G", "T"]] self.max = self.pssm.max self.min = self.pssm.min # Function calculate tag count def tag_count(chrName, start, end, bamFile, tcHalfWindow=None): total = 0 if(tcHalfWindow): mid = (start + end) / 2 p1exttc = max(mid - tcHalfWindow, 0) p2exttc = mid + tcHalfWindow else: p1exttc = start p2exttc = end for read in bamFile.fetch(reference=chrName, start=p1exttc, end=p2exttc): total += 1 if(total >= maxReadPile): break return total # Function to calculate overlap def overlap(t1, t2): return max(0, min(t1[1], t2[1]) - max(t1[0], t2[0])) # Function to write output def writeOutput(ll, regionTagCountVec, resVec, outFile): finalResVec = [] for vec in resVec: for e in vec: finalResVec.append(e) outFile.write("\t".join([ll[0], ll[1], ll[2]] + [str(e) for e in regionTagCountVec] + [str(e) for e in finalResVec]) + "\n") ########################################################### # Execution ########################################################### # Fetching motifs & evaluating global minimum motifList = [] for pfmFileName in pfmFileNameList: motifList.append(Motif(pfmFileName)) globalMin = min([e.min for e in motifList]) # Opening BAM files for DNase-seq and footprints (footprint bed files were converted to BAM for efficiency) dnaseBam = Samfile(dnaseBamFileName, "rb") fpBam = Samfile(footprintBamFileName, "rb") # Making header naming metricForEachMotif = ["BITSCORE", "BITSCORE_FOOTPRINT", "PROTECTION", "RELATIVE_MOTIF_POSITION", "OVERLAP_FOOTPRINT"] pfmFileNameListShort = [e.split("/")[-1].split(".")[0] for e in pfmFileNameList] header = "TC" counterPos = 1 counterNeg = 1 for e in pfmFileNameListShort: myvec = [] if("POS." in e): factorname = "\tDENOVO_POS_" + str(counterPos) counterPos += 1 elif("NEG." in e): factorname = "\tDENOVO_NEG_" + str(counterNeg) counterNeg += 1 else: factorname = "\tHOCOMOCO" for k in metricForEachMotif: myvec.append(factorname + "_" + k) header += "".join(myvec) # Iterating on main bed file bedFile = open(bedFileName, "r") outFile = open(outputFileName, "w") outFile.write(header + "\n") genomeFile = Fastafile(genomeFileName) for line in bedFile: # Fetching line ll = line.strip().split("\t") chrName = ll[0] p1 = int(ll[1]) p2 = int(ll[2]) # Starting result structures regionTagCount = 0 resVec = [] for m in motifList: vec = [] # For each motif print: # 1. Bitscore. # 2. Bitscore Footprint. # 3. Protection. # 4. Relative motif position. # 5. Amount of overlap between FP and motif. vec.append(globalMin) vec.append(-99) vec.append(-99) vec.append(-99) vec.append(-99) resVec.append(vec) # Evaluating Overall TC regionTagCountVec = [-99] try: for i in range(0, len(tcHalfWindowVec)): tcHalfWindow = tcHalfWindowVec[i] regionTagCountVec[i] = tag_count(chrName, p1, p2, dnaseBam, tcHalfWindow) except Exception: print "Exception TC raised in " + line writeOutput(ll, regionTagCountVec, resVec, outFile) continue # Fetching sequence try: sequence = str(genomeFile.fetch(chrName, p1, p2)) except Exception: print "Exception SEQUENCE raised in " + line writeOutput(ll, regionTagCountVec, resVec, outFile) continue # Performing motif matching for i in range(0, len(motifList)): m = motifList[i] for res in search(sequence, [m.pssm_list], [m.min], absolute_threshold=True, both_strands=True): for (position, score) in res: if(score > resVec[i][0]): resVec[i][0] = score resVec[i][3] = abs(position) # Fetching absolute position of best motif match mp1 = p1 + position mp2 = p1 + m.len # Evaluating PS p1_ext = mp1 - m.len p2_ext = mp2 + m.len if(p1_ext < 0): continue nl = tag_count(chrName, p1_ext, mp1, dnaseBam) nc = tag_count(chrName, mp1, mp2, dnaseBam) nr = tag_count(chrName, mp2, p2_ext, dnaseBam) resVec[i][2] = round(((nr + nl) / 2.0) - nc, 6) # Fetching footprints try: footprints = fpBam.fetch(reference=chrName, start=p1, end=p2) for fp in footprints: sequence = str(genomeFile.fetch(chrName, fp.pos - 5, fp.aend + 5)) for i in range(0, len(motifList)): m = motifList[i] flag = False for res in search(sequence, [m.pssm_list], [m.min], absolute_threshold=True, both_strands=True): for (position, score) in res: if(score > resVec[i][1]): resVec[i][1] = score flag = True if(flag): # Fetching absolute position of best motif match mp1 = p1 + position mp2 = p1 + m.len # Evaluating overlap resVec[i][4] = overlap([mp1, mp2], [fp.pos, fp.aend]) except Exception: print "Exception FOOTPRINTS raised in " + line writeOutput(ll, regionTagCountVec, resVec, outFile) continue # Writing results writeOutput(ll, regionTagCountVec, resVec, outFile) # Termination bedFile.close() outFile.close() genomeFile.close() dnaseBam.close() fpBam.close()
CostaLab/dream-challenge
fullMpbsFootprintTc.py
Python
gpl-3.0
6,914
[ "pysam" ]
a2e537b6248986428b13a4027f66f611be2a113fc0f83bc7315724b6a1af78e8
from sympy import (meijerg, I, S, integrate, Integral, oo, gamma, cosh, sinc, hyperexpand, exp, simplify, sqrt, pi, erf, erfc, sin, cos, exp_polar, polygamma, hyper, log, expand_func) from sympy.integrals.meijerint import (_rewrite_single, _rewrite1, meijerint_indefinite, _inflate_g, _create_lookup_table, meijerint_definite, meijerint_inversion) from sympy.utilities import default_sort_key from sympy.utilities.pytest import slow from sympy.utilities.randtest import (verify_numerically, random_complex_number as randcplx) from sympy.core.compatibility import range from sympy.abc import x, y, a, b, c, d, s, t, z def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) assert e is not None assert isinstance(e[0][0][2], meijerg) assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,)) def tn(expr): assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None t(x, 1, x) t(x**2, 1, x**2) t(x**2 + y*x**2, y + 1, x**2) tn(x**2 + x) tn(x**y) def u(expr, x): from sympy import Add, exp, exp_polar r = _rewrite_single(expr, x) e = Add(*[res[0]*res[2] for res in r[0]]).replace( exp_polar, exp) # XXX Hack? assert verify_numerically(e, expr, x) u(exp(-x)*sin(x), x) # The following has stopped working because hyperexpand changed slightly. # It is probably not worth fixing #u(exp(-x)*sin(x)*cos(x), x) # This one cannot be done numerically, since it comes out as a g-function # of argument 4*pi # NOTE This also tests a bug in inverse mellin transform (which used to # turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of # exp_polar). #u(exp(x)*sin(x), x) assert _rewrite_single(exp(x)*sin(x), x) == \ ([(-sqrt(2)/(2*sqrt(pi)), 0, meijerg(((-S(1)/2, 0, S(1)/4, S(1)/2, S(3)/4), (1,)), ((), (-S(1)/2, 0)), 64*exp_polar(-4*I*pi)/x**4))], True) def test_rewrite1(): assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \ (5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True) def test_meijerint_indefinite_numerically(): def t(fac, arg): g = meijerg([a], [b], [c], [d], arg)*fac subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx()} integral = meijerint_indefinite(g, x) assert integral is not None assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x) t(1, x) t(2, x) t(1, 2*x) t(1, x**2) t(5, x**S('3/2')) t(x**3, x) t(3*x**S('3/2'), 4*x**S('7/3')) def test_meijerint_definite(): v, b = meijerint_definite(x, x, 0, 0) assert v.is_zero and b is True v, b = meijerint_definite(x, x, oo, oo) assert v.is_zero and b is True def test_inflate(): subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx(), y: randcplx()/10} def t(a, b, arg, n): from sympy import Mul m1 = meijerg(a, b, arg) m2 = Mul(*_inflate_g(m1, n)) # NOTE: (the random number)**9 must still be on the principal sheet. # Thus make b&d small to create random numbers of small imaginary part. return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1) assert t([[a], [b]], [[c], [d]], x, 3) assert t([[a, y], [b]], [[c], [d]], x, 3) assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3) def test_recursive(): from sympy import symbols a, b, c = symbols('a b c', positive=True) r = exp(-(x - a)**2)*exp(-(x - b)**2) e = integrate(r, (x, 0, oo), meijerg=True) assert simplify(e.expand()) == ( sqrt(2)*sqrt(pi)*( (erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True) assert simplify(e) == ( sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2 + (2*a + 2*b + c)**2/8)/4) assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 + erf(a + b + c)) assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \ sqrt(pi)/2*(1 - erf(a + b + c)) @slow def test_meijerint(): from sympy import symbols, expand, arg s, t, mu = symbols('s t mu', real=True) assert integrate(meijerg([], [], [0], [], s*t) *meijerg([], [], [mu/2], [-mu/2], t**2/4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma))) assert c == True i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1/(mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) # Note: causes a NaN in _check_antecedents assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2), x, -oo, oo) == (1, True) assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S(1)/2, True) # Test a bug def res(n): return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True) ) == sqrt(2)*sin(a + pi/4)/2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy import And, re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \ (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1)) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S(1)/2)/4).expand() # Test hyperexpand bug. from sympy import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S(1)/2, alpha/2 + 1)), ((0, 0, S(1)/2), (-S(1)/2,)), alpha**S(2)/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S(1)/2)*((-1)**s + 1)*gamma(s/2 + S(1)/2)/2 def test_bessel(): from sympy import besselj, besseli assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo), meijerg=True, conds='none')) == \ 2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b)) assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo), meijerg=True, conds='none')) == 1/(2*a) # TODO more orthogonality integrals assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S(1)/2)), (x, 1, oo), meijerg=True, conds='none') *2/((z/2)**y*sqrt(pi)*gamma(S(1)/2 - y))) == \ besselj(y, z) # Werner Rosenheinrich # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x) assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x) # TODO can do higher powers, but come out as high order ... should they be # reduced to order 0, 1? assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x) assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \ -(besselj(0, x)**2 + besselj(1, x)**2)/2 # TODO more besseli when tables are extended or recursive mellin works assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \ -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \ + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \ -besselj(0, x)**2/2 assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \ x**2*besselj(1, x)**2/2 assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \ (x*besselj(0, x)**2 + x*besselj(1, x)**2 - besselj(0, x)*besselj(1, x)) # TODO how does besselj(0, a*x)*besselj(0, b*x) work? # TODO how does besselj(0, x)**2*besselj(1, x)**2 work? # TODO sin(x)*besselj(0, x) etc come out a mess # TODO can x*log(x)*besselj(0, x) be done? # TODO how does besselj(1, x)*besselj(0, x+a) work? # TODO more indefinite integrals when struve functions etc are implemented # test a substitution assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \ -besselj(0, x**2)/2 def test_inversion(): from sympy import piecewise_fold, besselj, sqrt, sin, cos, Heaviside def inv(f): return piecewise_fold(meijerint_inversion(f, s, t)) assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t) assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t) assert inv(exp(-s)/s) == Heaviside(t - 1) assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t) # Test some antcedents checking. assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None assert inv(exp(s**2)) is None assert meijerint_inversion(exp(-s**2), s, t) is None @slow def test_lookup_table(): from random import uniform, randrange from sympy import Add from sympy.integrals.meijerint import z as z_dummy table = {} _create_lookup_table(table) for _, l in sorted(table.items()): for formula, terms, cond, hint in sorted(l, key=default_sort_key): subs = {} for a in list(formula.free_symbols) + [z_dummy]: if hasattr(a, 'properties') and a.properties: # these Wilds match positive integers subs[a] = randrange(1, 10) else: subs[a] = uniform(1.5, 2.0) if not isinstance(terms, list): terms = terms(subs) # First test that hyperexpand can do this. expanded = [hyperexpand(g) for (_, g) in terms] assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded) # Now test that the meijer g-function is indeed as advertised. expanded = Add(*[f*x for (f, x) in terms]) a, b = formula.n(subs=subs), expanded.n(subs=subs) r = min(abs(a), abs(b)) if r < 1: assert abs(a - b).n() <= 1e-10 else: assert (abs(a - b)/r).n() <= 1e-10 def test_branch_bug(): from sympy import powdenest, lowergamma # TODO gammasimp cannot prove that the factor is unity assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x), polar=True) == 2*erf(x**3)*gamma(S(2)/3)/3/gamma(S(5)/3) assert integrate(erf(x**3), x, meijerg=True) == \ 2*x*erf(x**3)*gamma(S(2)/3)/(3*gamma(S(5)/3)) \ - 2*gamma(S(2)/3)*lowergamma(S(2)/3, x**6)/(3*sqrt(pi)*gamma(S(5)/3)) def test_linear_subs(): from sympy import besselj assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x) assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x) @slow def test_probability(): # various integrals from probability theory from sympy.abc import x, y from sympy import symbols, Symbol, Abs, expand_mul, gammasimp, powsimp, sin mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, finite=True, positive=True) rate = Symbol('lambda', real=True, positive=True, finite=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \ mu1 assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**2 + sigma1**2 assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**3 + 3*mu1*sigma1**2 assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1 assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2 assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2 assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2 assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ -1 + mu1 + mu2 i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) assert not i.has(Abs) assert simplify(i) == mu1**2 + sigma1**2 assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ sigma2**2 + mu2**2 assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1 assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 1/rate assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 2/rate**2 def E(expr): res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) assert expand_mul(res1) == expand_mul(res2) return res1 assert E(1) == 1 assert E(x*y) == mu1/rate assert E(x*y**2) == mu1**2/rate + sigma1**2/rate ans = sigma1**2 + 1/rate**2 assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans assert simplify(E((x + y)**2) - E(x + y)**2) == ans # Beta' distribution alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) assert integrate(betadist, (x, 0, oo), meijerg=True) == 1 i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate') assert (gammasimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta) j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate') assert j[1] == (1 < beta - 1) assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \ /(beta - 2)/(beta - 1)**2 # Beta distribution # NOTE: this is evaluated using antiderivatives. It also tests that # meijerint_indefinite returns the simplest possible answer. a, b = symbols('a b', positive=True) betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b)) assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1 assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \ a/(a + b) assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \ a*(a + 1)/(a + b)/(a + b + 1) assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \ gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y) # Chi distribution k = Symbol('k', integer=True, positive=True) chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \ sqrt(2)*gamma((k + 1)/2)/gamma(k/2) assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k # Chi^2 distribution chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \ k*(k + 2) assert gammasimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)) == 2*sqrt(2)/sqrt(k) # Dagum distribution a, b, p = symbols('a b p', positive=True) # XXX (x/b)**a does not work dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1) assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1 # XXX conditions are a mess arg = x*dagum assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/( (a*p + 1)*gamma(p)) assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/( (a*p + 2)*gamma(p)) # F-distribution d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1 # TODO conditions are a mess assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none') ) == d2/(d2 - 2) assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none') ) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2) # TODO gamma, rayleigh # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(-S(3)/2)*exp(-lamda*(x - mu)**2/x/2/mu**2) mysimp = lambda expr: simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2 # Levi c = Symbol('c', positive=True) assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'), (x, mu, oo)) == 1 # higher moments oo # log-logistic distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \ (1 + x**beta/alpha**beta)**2 assert simplify(integrate(distn, (x, 0, oo))) == 1 # NOTE the conditions are a mess, but correctly state beta > 1 assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \ pi*alpha/beta/sin(pi/beta) # (similar comment for conditions applies) assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \ pi*alpha**y*y/beta/sin(pi*y/beta) # weibull k = Symbol('k', positive=True) n = Symbol('n', positive=True) distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k) assert simplify(integrate(distn, (x, 0, oo))) == 1 assert simplify(integrate(x**n*distn, (x, 0, oo))) == \ lamda**n*gamma(1 + n/k) # rice distribution from sympy import besseli nu, sigma = symbols('nu sigma', positive=True) rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2) assert integrate(rice, (x, 0, oo), meijerg=True) == 1 # can someone verify higher moments? # Laplace distribution mu = Symbol('mu', real=True) b = Symbol('b', positive=True) laplace = exp(-abs(x - mu)/b)/2/b assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1 assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \ 2*b**2 + mu**2 # TODO are there other distributions supported on (-oo, oo) that we can do? # misc tests k = Symbol('k', positive=True) assert gammasimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k), (x, 0, oo)))) == polygamma(0, k) def test_expint(): """ Test various exponential integrals. """ from sympy import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi, sin, cos, sinh, cosh, Ei) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewrite(expint).expand(func=True))) == expint(y, z) assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(1, z) assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(2, z).rewrite(Ei).rewrite(expint) assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(3, z).rewrite(Ei).rewrite(expint).expand() t = Symbol('t', positive=True) assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t) assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \ Si(t) - pi/2 assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z) assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z) assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \ I*pi - expint(1, x) assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \ == expint(1, x) - exp(-x)/x - I*pi u = Symbol('u', polar=True) assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Ci(u) assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Chi(u) assert integrate(expint(1, x), x, meijerg=True ).rewrite(expint).expand() == x*expint(1, x) - exp(-x) assert integrate(expint(2, x), x, meijerg=True ).rewrite(expint).expand() == \ -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2 assert simplify(unpolarify(integrate(expint(y, x), x, meijerg=True).rewrite(expint).expand(func=True))) == \ -expint(y + 1, x) assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x) assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u) assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x) assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u) assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4 assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2 def test_messy(): from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise, acoth, E1, besselj, acosh, asin, And, re, fourier_transform, sqrt) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 4*abs(pi**2*s**2) > 1), (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True)) def test_issue_6122(): assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \ -I*sqrt(pi)*exp(I*pi/4) def test_issue_6252(): expr = 1/x/(a + b*x)**(S(1)/3) anti = integrate(expr, x, meijerg=True) assert not expr.has(hyper) # XXX the expression is a mess, but actually upon differentiation and # putting in numerical values seems to work... def test_issue_6348(): assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \ == pi*exp(-1) def test_fresnel(): from sympy import fresnels, fresnelc assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x) assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x) def test_issue_6860(): assert meijerint_indefinite(x**x**x, x) is None def test_issue_7337(): f = meijerint_indefinite(x*sqrt(2*x + 3), x).together() assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5 assert f._eval_interval(x, S(-1), S(1)) == S(2)/5 def test_issue_8368(): assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == ( (-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1) def test_issue_10211(): from sympy.abc import h, w assert integrate((1/sqrt(((y-x)**2 + h**2))**3), (x,0,w), (y,0,w)) == \ 2*sqrt(1 + w**2/h**2)/h - 2/h def test_issue_11806(): from sympy import symbols y, L = symbols('y L', positive=True) assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \ 2*L/(y**2*sqrt(L**2 + y**2)) def test_issue_10681(): from sympy import RR from sympy.abc import R, r f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True) g = (1.0/3)*R**1.0*r**3*hyper((-0.5, S(3)/2), (S(5)/2,), r**2*exp_polar(2*I*pi)/R**2) assert RR.almosteq((f/g).n(), 1.0, 1e-12) def test_issue_13536(): from sympy import Symbol a = Symbol('a', real=True, positive=True) assert integrate(1/x**2, (x, oo, a)) == -1/a
wxgeo/geophar
wxgeometrie/sympy/integrals/tests/test_meijerint.py
Python
gpl-2.0
28,567
[ "Gaussian" ]
cffddec116ae3cd1682fa2a8ddd39022143f8bf7439e7d8b9856e91584a7827b
# -*- coding: utf-8 -*- """ Models used to implement SAML SSO support in third_party_auth (inlcuding Shibboleth support) """ from __future__ import absolute_import import json import logging import re from config_models.models import ConfigurationModel, cache from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from provider.oauth2.models import Client from provider.utils import long_token from six import text_type from social_core.backends.base import BaseAuth from social_core.backends.oauth import OAuthAuth from social_core.backends.saml import SAMLAuth from social_core.exceptions import SocialAuthBaseException from social_core.utils import module_member from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.theming.helpers import get_current_request from appsembler import third_party_auth_utils from .lti import LTI_PARAMS_KEY, LTIAuthBackend from .saml import STANDARD_SAML_PROVIDER_KEY, get_saml_idp_choices, get_saml_idp_class log = logging.getLogger(__name__) REGISTRATION_FORM_FIELD_BLACKLIST = [ 'name', 'username' ] # A dictionary of {name: class} entries for each python-social-auth backend available. # Because this setting can specify arbitrary code to load and execute, it is set via # normal Django settings only and cannot be changed at runtime: def _load_backend_classes(base_class=BaseAuth): """ Load the list of python-social-auth backend classes from Django settings """ for class_path in settings.AUTHENTICATION_BACKENDS: auth_class = module_member(class_path) if issubclass(auth_class, base_class): yield auth_class _PSA_BACKENDS = {backend_class.name: backend_class for backend_class in _load_backend_classes()} _PSA_OAUTH2_BACKENDS = [backend_class.name for backend_class in _load_backend_classes(OAuthAuth)] _PSA_SAML_BACKENDS = [backend_class.name for backend_class in _load_backend_classes(SAMLAuth)] _LTI_BACKENDS = [backend_class.name for backend_class in _load_backend_classes(LTIAuthBackend)] def clean_json(value, of_type): """ Simple helper method to parse and clean JSON """ if not value.strip(): return json.dumps(of_type()) try: value_python = json.loads(value) except ValueError as err: raise ValidationError("Invalid JSON: {}".format(text_type(err))) if not isinstance(value_python, of_type): raise ValidationError("Expected a JSON {}".format(of_type)) return json.dumps(value_python, indent=4) def clean_username(username=''): """ Simple helper method to ensure a username is compatible with our system requirements. """ return re.sub(r'[^-\w]+', '_', username)[:30] class AuthNotConfigured(SocialAuthBaseException): """ Exception when SAMLProviderData or other required info is missing """ def __init__(self, provider_name): super(AuthNotConfigured, self).__init__() self.provider_name = provider_name def __str__(self): return _('Authentication with {} is currently unavailable.').format( self.provider_name ) class ProviderConfig(ConfigurationModel): """ Abstract Base Class for configuring a third_party_auth provider """ KEY_FIELDS = ('slug',) icon_class = models.CharField( max_length=50, blank=True, default='fa-sign-in', help_text=( 'The Font Awesome (or custom) icon class to use on the login button for this provider. ' 'Examples: fa-google-plus, fa-facebook, fa-linkedin, fa-sign-in, fa-university' ), ) # We use a FileField instead of an ImageField here because ImageField # doesn't support SVG. This means we don't get any image validation, but # that should be fine because only trusted users should be uploading these # anyway. icon_image = models.FileField( blank=True, help_text=( 'If there is no Font Awesome icon available for this provider, upload a custom image. ' 'SVG images are recommended as they can scale to any size.' ), ) name = models.CharField(max_length=50, blank=False, help_text="Name of this provider (shown to users)") slug = models.SlugField( max_length=30, db_index=True, default='default', help_text=( 'A short string uniquely identifying this provider. ' 'Cannot contain spaces and should be a usable as a CSS class. Examples: "ubc", "mit-staging"' )) secondary = models.BooleanField( default=False, help_text=_( 'Secondary providers are displayed less prominently, ' 'in a separate list of "Institution" login providers.' ), ) site = models.ForeignKey( Site, default=settings.SITE_ID, related_name='%(class)ss', help_text=_( 'The Site that this provider configuration belongs to.' ), on_delete=models.CASCADE, ) skip_hinted_login_dialog = models.BooleanField( default=False, help_text=_( "If this option is enabled, users that visit a \"TPA hinted\" URL for this provider " "(e.g. a URL ending with `?tpa_hint=[provider_name]`) will be forwarded directly to " "the login URL of the provider instead of being first prompted with a login dialog." ), ) skip_registration_form = models.BooleanField( default=False, help_text=_( "If this option is enabled, users will not be asked to confirm their details " "(name, email, etc.) during the registration process. Only select this option " "for trusted providers that are known to provide accurate user information." ), ) skip_email_verification = models.BooleanField( default=False, help_text=_( "If this option is selected, users will not be required to confirm their " "email, and their account will be activated immediately upon registration." ), ) send_welcome_email = models.BooleanField( default=False, help_text=_( "If this option is selected, users will be sent a welcome email upon registration." ), ) visible = models.BooleanField( default=False, help_text=_( "If this option is not selected, users will not be presented with the provider " "as an option to authenticate with on the login screen, but manual " "authentication using the correct link is still possible." ), ) max_session_length = models.PositiveIntegerField( null=True, blank=True, default=None, verbose_name='Max session length (seconds)', help_text=_( "If this option is set, then users logging in using this SSO provider will have " "their session length limited to no longer than this value. If set to 0 (zero), " "the session will expire upon the user closing their browser. If left blank, the " "Django platform session default length will be used." ) ) send_to_registration_first = models.BooleanField( default=False, help_text=_( "If this option is selected, users will be directed to the registration page " "immediately after authenticating with the third party instead of the login page." ), ) sync_learner_profile_data = models.BooleanField( default=False, help_text=_( "Synchronize user profile data received from the identity provider with the edX user " "account on each SSO login. The user will be notified if the email address associated " "with their account is changed as a part of this synchronization." ) ) enable_sso_id_verification = models.BooleanField( default=False, help_text="Use the presence of a profile from a trusted third party as proof of identity verification.", ) prefix = None # used for provider_id. Set to a string value in subclass backend_name = None # Set to a field or fixed value in subclass accepts_logins = True # Whether to display a sign-in button when the provider is enabled # "enabled" field is inherited from ConfigurationModel class Meta(object): app_label = "third_party_auth" abstract = True def clean(self): """ Ensure that either `icon_class` or `icon_image` is set """ super(ProviderConfig, self).clean() if bool(self.icon_class) == bool(self.icon_image): raise ValidationError('Either an icon class or an icon image must be given (but not both)') @property def provider_id(self): """ Unique string key identifying this provider. Must be URL and css class friendly. """ assert self.prefix is not None return "-".join((self.prefix, ) + tuple(getattr(self, field) for field in self.KEY_FIELDS)) @property def backend_class(self): """ Get the python-social-auth backend class used for this provider """ return _PSA_BACKENDS[self.backend_name] @property def full_class_name(self): """ Get the fully qualified class name of this provider. """ return '{}.{}'.format(self.__module__, self.__class__.__name__) def get_url_params(self): """ Get a dict of GET parameters to append to login links for this provider """ return {} def is_active_for_pipeline(self, pipeline): """ Is this provider being used for the specified pipeline? """ return self.backend_name == pipeline['backend'] def match_social_auth(self, social_auth): """ Is this provider being used for this UserSocialAuth entry? """ return self.backend_name == social_auth.provider def get_remote_id_from_social_auth(self, social_auth): """ Given a UserSocialAuth object, return the remote ID used by this provider. """ # This is generally the same thing as the UID, expect when one backend is used for multiple providers assert self.match_social_auth(social_auth) return social_auth.uid def get_social_auth_uid(self, remote_id): """ Return the uid in social auth. This is default implementation. Subclass may override with a different one. """ return remote_id @classmethod def get_register_form_data(cls, pipeline_kwargs): """Gets dict of data to display on the register form. common.djangoapps.student.views.register_user uses this to populate the new account creation form with values supplied by the user's chosen provider, preventing duplicate data entry. Args: pipeline_kwargs: dict of string -> object. Keyword arguments accumulated by the pipeline thus far. Returns: Dict of string -> string. Keys are names of form fields; values are values for that field. Where there is no value, the empty string must be used. """ registration_form_data = {} # Details about the user sent back from the provider. details = pipeline_kwargs.get('details').copy() # Set the registration form to use the `fullname` detail for the `name` field. registration_form_data['name'] = third_party_auth_utils.get_fullname( details=details, default_fullname=details.get('fullname', '') ) # Get the username separately to take advantage of the de-duping logic # built into the pipeline. The provider cannot de-dupe because it can't # check the state of taken usernames in our system. Note that there is # technically a data race between the creation of this value and the # creation of the user object, so it is still possible for users to get # an error on submit. registration_form_data['username'] = third_party_auth_utils.clean_username(pipeline_kwargs.get('username')) # Any other values that are present in the details dict should be copied # into the registration form details. This may include details that do # not map to a value that exists in the registration form. However, # because the fields that are actually rendered are not based on this # list, only those values that map to a valid registration form field # will actually be sent to the form as default values. for blacklisted_field in REGISTRATION_FORM_FIELD_BLACKLIST: details.pop(blacklisted_field, None) registration_form_data.update(details) return registration_form_data def get_authentication_backend(self): """Gets associated Django settings.AUTHENTICATION_BACKEND string.""" return '{}.{}'.format(self.backend_class.__module__, self.backend_class.__name__) @property def display_for_login(self): """ Determines whether the provider ought to be shown as an option with which to authenticate on the login screen, registration screen, and elsewhere. """ return bool(self.enabled_for_current_site and self.accepts_logins and self.visible) @property def enabled_for_current_site(self): """ Determines if the provider is able to be used with the current site. """ return self.enabled and self.site == Site.objects.get_current(get_current_request()) class OAuth2ProviderConfig(ProviderConfig): """ Configuration Entry for an OAuth2 based provider. Also works for OAuth1 providers. """ prefix = 'oa2' backend_name = models.CharField( max_length=50, blank=False, db_index=True, help_text=( "Which python-social-auth OAuth2 provider backend to use. " "The list of backend choices is determined by the THIRD_PARTY_AUTH_BACKENDS setting." # To be precise, it's set by AUTHENTICATION_BACKENDS - which aws.py sets from THIRD_PARTY_AUTH_BACKENDS ) ) key = models.TextField(blank=True, verbose_name="Client ID") secret = models.TextField( blank=True, verbose_name="Client Secret", help_text=( 'For increased security, you can avoid storing this in your database by leaving ' ' this field blank and setting ' 'SOCIAL_AUTH_OAUTH_SECRETS = {"(backend name)": "secret", ...} ' 'in your instance\'s Django settings (or lms.auth.json)' ) ) other_settings = models.TextField(blank=True, help_text="Optional JSON object with advanced settings, if any.") class Meta(object): app_label = "third_party_auth" verbose_name = "Provider Configuration (OAuth)" verbose_name_plural = verbose_name def clean(self): """ Standardize and validate fields """ super(OAuth2ProviderConfig, self).clean() self.other_settings = clean_json(self.other_settings, dict) def get_setting(self, name): """ Get the value of a setting, or raise KeyError """ if name == "KEY": return self.key if name == "SECRET": if self.secret: return self.secret # To allow instances to avoid storing secrets in the DB, the secret can also be set via Django: return getattr(settings, 'SOCIAL_AUTH_OAUTH_SECRETS', {}).get(self.backend_name, '') if self.other_settings: other_settings = json.loads(self.other_settings) assert isinstance(other_settings, dict), "other_settings should be a JSON object (dictionary)" return other_settings[name] raise KeyError class SAMLConfiguration(ConfigurationModel): """ General configuration required for this edX instance to act as a SAML Service Provider and allow users to authenticate via third party SAML Identity Providers (IdPs) """ KEY_FIELDS = ('site_id', 'slug') site = models.ForeignKey( Site, default=settings.SITE_ID, related_name='%(class)ss', help_text=_( 'The Site that this SAML configuration belongs to.' ), on_delete=models.CASCADE, ) slug = models.SlugField( max_length=30, default='default', help_text=( 'A short string uniquely identifying this configuration. ' 'Cannot contain spaces. Examples: "ubc", "mit-staging"' ), ) private_key = models.TextField( help_text=( 'To generate a key pair as two files, run ' '"openssl req -new -x509 -days 3652 -nodes -out saml.crt -keyout saml.key". ' 'Paste the contents of saml.key here. ' 'For increased security, you can avoid storing this in your database by leaving ' 'this field blank and setting it via the SOCIAL_AUTH_SAML_SP_PRIVATE_KEY setting ' 'in your instance\'s Django settings (or lms.auth.json).' ), blank=True, ) public_key = models.TextField( help_text=( 'Public key certificate. ' 'For increased security, you can avoid storing this in your database by leaving ' 'this field blank and setting it via the SOCIAL_AUTH_SAML_SP_PUBLIC_CERT setting ' 'in your instance\'s Django settings (or lms.auth.json).' ), blank=True, ) entity_id = models.CharField(max_length=255, default="http://saml.example.com", verbose_name="Entity ID") org_info_str = models.TextField( verbose_name="Organization Info", default='{"en-US": {"url": "http://www.example.com", "displayname": "Example Inc.", "name": "example"}}', help_text="JSON dictionary of 'url', 'displayname', and 'name' for each language", ) other_config_str = models.TextField( default='{\n"SECURITY_CONFIG": {"metadataCacheDuration": 604800, "signMetadata": false}\n}', help_text=( "JSON object defining advanced settings that are passed on to python-saml. " "Valid keys that can be set here include: SECURITY_CONFIG and SP_EXTRA" ), ) slo_redirect_url = models.CharField( max_length=255, default='/logout', verbose_name="SLO post redirect URL", help_text="The url to redirect the user after process the SLO response", blank=True ) class Meta(object): app_label = "third_party_auth" verbose_name = "SAML Configuration" verbose_name_plural = verbose_name def __str__(self): """ Return human-readable string representation. """ return "SAMLConfiguration {site}: {slug} on {date:%Y-%m-%d %H:%M:%S}".format( site=self.site.name, slug=self.slug, date=self.change_date, ) def clean(self): """ Standardize and validate fields """ super(SAMLConfiguration, self).clean() self.org_info_str = clean_json(self.org_info_str, dict) self.other_config_str = clean_json(self.other_config_str, dict) self.private_key = ( self.private_key .replace("-----BEGIN RSA PRIVATE KEY-----", "") .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END RSA PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .strip() ) self.public_key = ( self.public_key .replace("-----BEGIN CERTIFICATE-----", "") .replace("-----END CERTIFICATE-----", "") .strip() ) def get_setting(self, name): """ Get the value of a setting, or raise KeyError """ default_saml_contact = { # Default contact information to put into the SAML metadata that gets generated by python-saml. "givenName": _("{platform_name} Support").format( platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) ), "emailAddress": configuration_helpers.get_value('TECH_SUPPORT_EMAIL', settings.TECH_SUPPORT_EMAIL), } if name == "ORG_INFO": return json.loads(self.org_info_str) if name == "SP_ENTITY_ID": return self.entity_id if name == "SP_PUBLIC_CERT": if self.public_key: return self.public_key # To allow instances to avoid storing keys in the DB, the key pair can also be set via Django: if self.slug == 'default': return getattr(settings, 'SOCIAL_AUTH_SAML_SP_PUBLIC_CERT', '') else: public_certs = getattr(settings, 'SOCIAL_AUTH_SAML_SP_PUBLIC_CERT_DICT', {}) return public_certs.get(self.slug, '') if name == "SP_PRIVATE_KEY": if self.private_key: return self.private_key # To allow instances to avoid storing keys in the DB, the private key can also be set via Django: if self.slug == 'default': return getattr(settings, 'SOCIAL_AUTH_SAML_SP_PRIVATE_KEY', '') else: private_keys = getattr(settings, 'SOCIAL_AUTH_SAML_SP_PRIVATE_KEY_DICT', {}) return private_keys.get(self.slug, '') if name == "LOGOUT_REDIRECT_URL": return self.slo_redirect_url if name == "SP_SAML_RESTRICT_MODE": return getattr(settings, 'SP_SAML_RESTRICT_MODE', True) other_config = { # These defaults can be overriden by self.other_config_str "GET_ALL_EXTRA_DATA": True, # Save all attribute values the IdP sends into the UserSocialAuth table "TECHNICAL_CONTACT": default_saml_contact, "SUPPORT_CONTACT": default_saml_contact, } other_config.update(json.loads(self.other_config_str)) return other_config[name] # SECURITY_CONFIG, SP_EXTRA, or similar extra settings def active_saml_configurations_filter(): """ Returns a mapping to be used for the SAMLProviderConfig to limit the SAMLConfiguration choices to the current set. """ query_set = SAMLConfiguration.objects.current_set() return {'id__in': query_set.values_list('id', flat=True)} class SAMLProviderConfig(ProviderConfig): """ Configuration Entry for a SAML/Shibboleth provider. """ prefix = 'saml' backend_name = models.CharField( max_length=50, default='tpa-saml', blank=False, help_text="Which python-social-auth provider backend to use. 'tpa-saml' is the standard edX SAML backend.") entity_id = models.CharField( max_length=255, verbose_name="Entity ID", help_text="Example: https://idp.testshib.org/idp/shibboleth") metadata_source = models.CharField( max_length=255, help_text=( "URL to this provider's XML metadata. Should be an HTTPS URL. " "Example: https://www.testshib.org/metadata/testshib-providers.xml" )) attr_user_permanent_id = models.CharField( max_length=128, blank=True, verbose_name="User ID Attribute", help_text="URN of the SAML attribute that we can use as a unique, persistent user ID. Leave blank for default.") attr_full_name = models.CharField( max_length=128, blank=True, verbose_name="Full Name Attribute", help_text="URN of SAML attribute containing the user's full name. Leave blank for default.") attr_first_name = models.CharField( max_length=128, blank=True, verbose_name="First Name Attribute", help_text="URN of SAML attribute containing the user's first name. Leave blank for default.") attr_last_name = models.CharField( max_length=128, blank=True, verbose_name="Last Name Attribute", help_text="URN of SAML attribute containing the user's last name. Leave blank for default.") attr_username = models.CharField( max_length=128, blank=True, verbose_name="Username Hint Attribute", help_text="URN of SAML attribute to use as a suggested username for this user. Leave blank for default.") attr_email = models.CharField( max_length=128, blank=True, verbose_name="Email Attribute", help_text="URN of SAML attribute containing the user's email address[es]. Leave blank for default.") automatic_refresh_enabled = models.BooleanField( default=True, verbose_name="Enable automatic metadata refresh", help_text="When checked, the SAML provider's metadata will be included " "in the automatic refresh job, if configured." ) identity_provider_type = models.CharField( max_length=128, blank=False, verbose_name="Identity Provider Type", default=STANDARD_SAML_PROVIDER_KEY, choices=get_saml_idp_choices(), help_text=( "Some SAML providers require special behavior. For example, SAP SuccessFactors SAML providers require an " "additional API call to retrieve user metadata not provided in the SAML response. Select the provider type " "which best matches your use case. If in doubt, choose the Standard SAML Provider type." ) ) debug_mode = models.BooleanField( default=False, verbose_name="Debug Mode", help_text=( "In debug mode, all SAML XML requests and responses will be logged. " "This is helpful for testing/setup but should always be disabled before users start using this provider." ), ) other_settings = models.TextField( verbose_name="Advanced settings", blank=True, help_text=( 'For advanced use cases, enter a JSON object with addtional configuration. ' 'The tpa-saml backend supports {"requiredEntitlements": ["urn:..."]}, ' 'which can be used to require the presence of a specific eduPersonEntitlement, ' 'and {"extra_field_definitions": [{"name": "...", "urn": "..."},...]}, which can be ' 'used to define registration form fields and the URNs that can be used to retrieve ' 'the relevant values from the SAML response. Custom provider types, as selected ' 'in the "Identity Provider Type" field, may make use of the information stored ' 'in this field for additional configuration.' )) archived = models.BooleanField(default=False) saml_configuration = models.ForeignKey( SAMLConfiguration, on_delete=models.SET_NULL, limit_choices_to=active_saml_configurations_filter, null=True, blank=True, ) def clean(self): """ Standardize and validate fields """ super(SAMLProviderConfig, self).clean() self.other_settings = clean_json(self.other_settings, dict) class Meta(object): app_label = "third_party_auth" verbose_name = "Provider Configuration (SAML IdP)" verbose_name_plural = "Provider Configuration (SAML IdPs)" def get_url_params(self): """ Get a dict of GET parameters to append to login links for this provider """ return {'idp': self.slug} def is_active_for_pipeline(self, pipeline): """ Is this provider being used for the specified pipeline? """ return self.backend_name == pipeline['backend'] and self.slug == pipeline['kwargs']['response']['idp_name'] def match_social_auth(self, social_auth): """ Is this provider being used for this UserSocialAuth entry? """ prefix = self.slug + ":" return self.backend_name == social_auth.provider and social_auth.uid.startswith(prefix) def get_remote_id_from_social_auth(self, social_auth): """ Given a UserSocialAuth object, return the remote ID used by this provider. """ assert self.match_social_auth(social_auth) # Remove the prefix from the UID return social_auth.uid[len(self.slug) + 1:] def get_social_auth_uid(self, remote_id): """ Get social auth uid from remote id by prepending idp_slug to the remote id """ return '{}:{}'.format(self.slug, remote_id) def get_config(self): """ Return a SAMLIdentityProvider instance for use by SAMLAuthBackend. Essentially this just returns the values of this object and its associated 'SAMLProviderData' entry. """ if self.other_settings: conf = json.loads(self.other_settings) else: conf = {} attrs = ( 'attr_user_permanent_id', 'attr_full_name', 'attr_first_name', 'attr_last_name', 'attr_username', 'attr_email', 'entity_id') for field in attrs: val = getattr(self, field) if val: conf[field] = val # Now get the data fetched automatically from the metadata.xml: data = SAMLProviderData.current(self.entity_id) if not data or not data.is_valid(): log.error( 'No SAMLProviderData found for provider "%s" with entity id "%s" and IdP slug "%s". ' 'Run "manage.py saml pull" to fix or debug.', self.name, self.entity_id, self.slug ) raise AuthNotConfigured(provider_name=self.name) conf['x509cert'] = data.public_key conf['url'] = data.sso_url conf['slo_url'] = data.slo_url # Add SAMLConfiguration appropriate for this IdP conf['saml_sp_configuration'] = ( self.saml_configuration or SAMLConfiguration.current(self.site.id, 'default') ) idp_class = get_saml_idp_class(self.identity_provider_type) return idp_class(self.slug, **conf) class SAMLProviderData(models.Model): """ Data about a SAML IdP that is fetched automatically by 'manage.py saml pull' This data is only required during the actual authentication process. """ cache_timeout = 600 fetched_at = models.DateTimeField(db_index=True, null=False) expires_at = models.DateTimeField(db_index=True, null=True) entity_id = models.CharField(max_length=255, db_index=True) # This is the key for lookups in this table sso_url = models.URLField(verbose_name="SSO URL") slo_url = models.URLField(verbose_name="SLO URL", null=True) public_key = models.TextField() class Meta(object): app_label = "third_party_auth" verbose_name = "SAML Provider Data" verbose_name_plural = verbose_name ordering = ('-fetched_at', ) def is_valid(self): """ Is this data valid? """ if self.expires_at and timezone.now() > self.expires_at: return False return bool(self.entity_id and self.sso_url and self.public_key) is_valid.boolean = True @classmethod def cache_key_name(cls, entity_id): """ Return the name of the key to use to cache the current data """ return 'configuration/{}/current/{}'.format(cls.__name__, entity_id) @classmethod def current(cls, entity_id): """ Return the active data entry, if any, otherwise None """ cached = cache.get(cls.cache_key_name(entity_id)) if cached is not None: return cached try: current = cls.objects.filter(entity_id=entity_id).order_by('-fetched_at')[0] except IndexError: current = None cache.set(cls.cache_key_name(entity_id), current, cls.cache_timeout) return current class LTIProviderConfig(ProviderConfig): """ Configuration required for this edX instance to act as a LTI Tool Provider and allow users to authenticate and be enrolled in a course via third party LTI Tool Consumers. """ prefix = 'lti' backend_name = 'lti' # This provider is not visible to users icon_class = None icon_image = None secondary = False # LTI login cannot be initiated by the tool provider accepts_logins = False KEY_FIELDS = ('lti_consumer_key', ) lti_consumer_key = models.CharField( max_length=255, help_text=( 'The name that the LTI Tool Consumer will use to identify itself' ) ) lti_hostname = models.CharField( default='localhost', max_length=255, help_text=( 'The domain that will be acting as the LTI consumer.' ), db_index=True ) lti_consumer_secret = models.CharField( default=long_token, max_length=255, help_text=( 'The shared secret that the LTI Tool Consumer will use to ' 'authenticate requests. Only this edX instance and this ' 'tool consumer instance should know this value. ' 'For increased security, you can avoid storing this in ' 'your database by leaving this field blank and setting ' 'SOCIAL_AUTH_LTI_CONSUMER_SECRETS = {"consumer key": "secret", ...} ' 'in your instance\'s Django setttigs (or lms.auth.json)' ), blank=True, ) lti_max_timestamp_age = models.IntegerField( default=10, help_text=( 'The maximum age of oauth_timestamp values, in seconds.' ) ) def match_social_auth(self, social_auth): """ Is this provider being used for this UserSocialAuth entry? """ prefix = self.lti_consumer_key + ":" return self.backend_name == social_auth.provider and social_auth.uid.startswith(prefix) def get_remote_id_from_social_auth(self, social_auth): """ Given a UserSocialAuth object, return the remote ID used by this provider. """ assert self.match_social_auth(social_auth) # Remove the prefix from the UID return social_auth.uid[len(self.lti_consumer_key) + 1:] def is_active_for_pipeline(self, pipeline): """ Is this provider being used for the specified pipeline? """ try: return ( self.backend_name == pipeline['backend'] and self.lti_consumer_key == pipeline['kwargs']['response'][LTI_PARAMS_KEY]['oauth_consumer_key'] ) except KeyError: return False def get_lti_consumer_secret(self): """ If the LTI consumer secret is not stored in the database, check Django settings instead """ if self.lti_consumer_secret: return self.lti_consumer_secret return getattr(settings, 'SOCIAL_AUTH_LTI_CONSUMER_SECRETS', {}).get(self.lti_consumer_key, '') class Meta(object): app_label = "third_party_auth" verbose_name = "Provider Configuration (LTI)" verbose_name_plural = verbose_name class ProviderApiPermissions(models.Model): """ This model links OAuth2 client with provider Id. It gives permission for a OAuth2 client to access the information under certain IdPs. """ client = models.ForeignKey(Client, on_delete=models.CASCADE) provider_id = models.CharField( max_length=255, help_text=( 'Uniquely identify a provider. This is different from backend_name.' ) ) class Meta(object): app_label = "third_party_auth" verbose_name = "Provider API Permission" verbose_name_plural = verbose_name + 's'
gymnasium/edx-platform
common/djangoapps/third_party_auth/models.py
Python
agpl-3.0
35,551
[ "VisIt" ]
907624d0519f2642256aa31b2b12cb987e520df2a1cc1de64de67cf3f8897322
""" Maximally localized Wannier Functions Find the set of maximally localized Wannier functions using the spread functional of Marzari and Vanderbilt (PRB 56, 1997 page 12847). """ from time import time from math import sqrt, pi from pickle import dump, load import numpy as np from ase.parallel import paropen from ase.dft.kpoints import get_monkhorst_pack_size_and_offset from ase.transport.tools import dagger, normalize dag = dagger def gram_schmidt(U): """Orthonormalize columns of U according to the Gram-Schmidt procedure.""" for i, col in enumerate(U.T): for col2 in U.T[:i]: col -= col2 * np.dot(col2.conj(), col) col /= np.linalg.norm(col) def gram_schmidt_single(U, n): """Orthogonalize columns of U to column n""" N = len(U.T) v_n = U.T[n] indices = range(N) del indices[indices.index(n)] for i in indices: v_i = U.T[i] v_i -= v_n * np.dot(v_n.conj(), v_i) def lowdin(U, S=None): """Orthonormalize columns of U according to the Lowdin procedure. If the overlap matrix is know, it can be specified in S. """ if S is None: S = np.dot(dag(U), U) eig, rot = np.linalg.eigh(S) rot = np.dot(rot / np.sqrt(eig), dag(rot)) U[:] = np.dot(U, rot) def neighbor_k_search(k_c, G_c, kpt_kc, tol=1e-4): # search for k1 (in kpt_kc) and k0 (in alldir), such that # k1 - k - G + k0 = 0 alldir_dc = np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1], [1,1,0],[1,0,1],[0,1,1]], int) for k0_c in alldir_dc: for k1, k1_c in enumerate(kpt_kc): if np.linalg.norm(k1_c - k_c - G_c + k0_c) < tol: return k1, k0_c print 'Wannier: Did not find matching kpoint for kpt=', k_c print 'Probably non-uniform k-point grid' raise NotImplementedError def calculate_weights(cell_cc): """ Weights are used for non-cubic cells, see PRB **61**, 10040""" alldirs_dc = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]], dtype=int) g = np.dot(cell_cc, cell_cc.T) # NOTE: Only first 3 of following 6 weights are presently used: w = np.zeros(6) w[0] = g[0, 0] - g[0, 1] - g[0, 2] w[1] = g[1, 1] - g[0, 1] - g[1, 2] w[2] = g[2, 2] - g[0, 2] - g[1, 2] w[3] = g[0, 1] w[4] = g[0, 2] w[5] = g[1, 2] # Make sure that first 3 Gdir vectors are included - # these are used to calculate Wanniercenters. Gdir_dc = alldirs_dc[:3] weight_d = w[:3] for d in range(3, 6): if abs(w[d]) > 1e-5: Gdir_dc = np.concatenate((Gdir_dc, alldirs_dc[d:d + 1])) weight_d = np.concatenate((weight_d, w[d:d + 1])) weight_d /= max(abs(weight_d)) return weight_d, Gdir_dc def random_orthogonal_matrix(dim, seed=None, real=False): """Generate a random orthogonal matrix""" if seed is not None: np.random.seed(seed) H = np.random.rand(dim, dim) np.add(dag(H), H, H) np.multiply(.5, H, H) if real: gram_schmidt(H) return H else: val, vec = np.linalg.eig(H) return np.dot(vec * np.exp(1.j * val), dag(vec)) def steepest_descent(func, step=.005, tolerance=1e-6, **kwargs): fvalueold = 0. fvalue = fvalueold + 10 count=0 while abs((fvalue - fvalueold) / fvalue) > tolerance: fvalueold = fvalue dF = func.get_gradients() func.step(dF * step, **kwargs) fvalue = func.get_functional_value() count += 1 print 'SteepestDescent: iter=%s, value=%s' % (count, fvalue) def md_min(func, step=.25, tolerance=1e-6, verbose=False, **kwargs): if verbose: print 'Localize with step =', step, 'and tolerance =', tolerance t = -time() fvalueold = 0. fvalue = fvalueold + 10 count = 0 V = np.zeros(func.get_gradients().shape, dtype=complex) while abs((fvalue - fvalueold) / fvalue) > tolerance: fvalueold = fvalue dF = func.get_gradients() V *= (dF * V.conj()).real > 0 V += step * dF func.step(V, **kwargs) fvalue = func.get_functional_value() if fvalue < fvalueold: step *= 0.5 count += 1 if verbose: print 'MDmin: iter=%s, step=%s, value=%s' % (count, step, fvalue) if verbose: t += time() print '%d iterations in %0.2f seconds (%0.2f ms/iter), endstep = %s' %( count, t, t * 1000. / count, step) def rotation_from_projection2(proj_nw, fixed): V_ni = proj_nw Nb, Nw = proj_nw.shape M = fixed L = Nw - M print 'M=%i, L=%i, Nb=%i, Nw=%i' % (M, L, Nb, Nw) U_ww = np.zeros((Nw, Nw), dtype=proj_nw.dtype) c_ul = np.zeros((Nb-M, L), dtype=proj_nw.dtype) for V_n in V_ni.T: V_n /= np.linalg.norm(V_n) # Find EDF P_ui = V_ni[M:].copy() la = np.linalg for l in range(L): norm_list = np.array([la.norm(v) for v in P_ui.T]) perm_list = np.argsort(-norm_list) P_ui = P_ui[:, perm_list].copy() # largest norm to the left P_ui[:, 0] /= la.norm(P_ui[:, 0]) # normalize c_ul[:, l] = P_ui[:, 0] # save normalized EDF gram_schmidt_single(P_ui, 0) # ortho remain. to this EDF P_ui = P_ui[:, 1:].copy() # remove this EDF U_ww[:M] = V_ni[:M, :] U_ww[M:] = np.dot(c_ul.T.conj(), V_ni[M:]) gram_schmidt(U_ww) return U_ww, c_ul def rotation_from_projection(proj_nw, fixed, ortho=True): """Determine rotation and coefficient matrices from projections proj_nw = <psi_n|p_w> psi_n: eigenstates p_w: localized function Nb (n) = Number of bands Nw (w) = Number of wannier functions M (f) = Number of fixed states L (l) = Number of extra degrees of freedom U (u) = Number of non-fixed states """ Nb, Nw = proj_nw.shape M = fixed L = Nw - M U_ww = np.empty((Nw, Nw), dtype=proj_nw.dtype) U_ww[:M] = proj_nw[:M] if L > 0: proj_uw = proj_nw[M:] eig_w, C_ww = np.linalg.eigh(np.dot(dag(proj_uw), proj_uw)) C_ul = np.dot(proj_uw, C_ww[:, np.argsort(-eig_w.real)[:L]]) #eig_u, C_uu = np.linalg.eigh(np.dot(proj_uw, dag(proj_uw))) #C_ul = C_uu[:, np.argsort(-eig_u.real)[:L]] U_ww[M:] = np.dot(dag(C_ul), proj_uw) else: C_ul = np.empty((Nb - M, 0)) normalize(C_ul) if ortho: lowdin(U_ww) else: normalize(U_ww) return U_ww, C_ul class Wannier: """Maximally localized Wannier Functions Find the set of maximally localized Wannier functions using the spread functional of Marzari and Vanderbilt (PRB 56, 1997 page 12847). """ def __init__(self, nwannier, calc, file=None, nbands=None, fixedenergy=None, fixedstates=None, spin=0, initialwannier='random', seed=None, verbose=False): """ Required arguments: ``nwannier``: The number of Wannier functions you wish to construct. This must be at least half the number of electrons in the system and at most equal to the number of bands in the calculation. ``calc``: A converged DFT calculator class. If ``file`` arg. is not provided, the calculator *must* provide the method ``get_wannier_localization_matrix``, and contain the wavefunctions (save files with only the density is not enough). If the localization matrix is read from file, this is not needed, unless ``get_function`` or ``write_cube`` is called. Optional arguments: ``nbands``: Bands to include in localization. The number of bands considered by Wannier can be smaller than the number of bands in the calculator. This is useful if the highest bands of the DFT calculation are not well converged. ``spin``: The spin channel to be considered. The Wannier code treats each spin channel independently. ``fixedenergy`` / ``fixedstates``: Fixed part of Heilbert space. Determine the fixed part of Hilbert space by either a maximal energy *or* a number of bands (possibly a list for multiple k-points). Default is None meaning that the number of fixed states is equated to ``nwannier``. ``file``: Read localization and rotation matrices from this file. ``initialwannier``: Initial guess for Wannier rotation matrix. Can be 'bloch' to start from the Bloch states, 'random' to be randomized, or a list passed to calc.get_initial_wannier. ``seed``: Seed for random ``initialwannier``. ``verbose``: True / False level of verbosity. """ # Bloch phase sign convention sign = -1 classname = calc.__class__.__name__ if classname in ['Dacapo', 'Jacapo']: print 'Using ' + classname sign = +1 self.nwannier = nwannier self.calc = calc self.spin = spin self.verbose = verbose self.kpt_kc = calc.get_bz_k_points() assert len(calc.get_ibz_k_points()) == len(self.kpt_kc) self.kptgrid = get_monkhorst_pack_size_and_offset(self.kpt_kc)[0] self.kpt_kc *= sign self.Nk = len(self.kpt_kc) self.unitcell_cc = calc.get_atoms().get_cell() self.largeunitcell_cc = (self.unitcell_cc.T * self.kptgrid).T self.weight_d, self.Gdir_dc = calculate_weights(self.largeunitcell_cc) self.Ndir = len(self.weight_d) # Number of directions if nbands is not None: self.nbands = nbands else: self.nbands = calc.get_number_of_bands() if fixedenergy is None: if fixedstates is None: self.fixedstates_k = np.array([nwannier] * self.Nk, int) else: if type(fixedstates) is int: fixedstates = [fixedstates] * self.Nk self.fixedstates_k = np.array(fixedstates, int) else: # Setting number of fixed states and EDF from specified energy. # All states below this energy (relative to Fermi level) are fixed. fixedenergy += calc.get_fermi_level() print fixedenergy self.fixedstates_k = np.array( [calc.get_eigenvalues(k, spin).searchsorted(fixedenergy) for k in range(self.Nk)], int) self.edf_k = self.nwannier - self.fixedstates_k if verbose: print 'Wannier: Fixed states : %s' % self.fixedstates_k print 'Wannier: Extra degrees of freedom: %s' % self.edf_k # Set the list of neighboring k-points k1, and the "wrapping" k0, # such that k1 - k - G + k0 = 0 # # Example: kpoints = (-0.375,-0.125,0.125,0.375), dir=0 # G = [0.25,0,0] # k=0.375, k1= -0.375 : -0.375-0.375-0.25 => k0=[1,0,0] # # For a gamma point calculation k1 = k = 0, k0 = [1,0,0] for dir=0 if self.Nk == 1: self.kklst_dk = np.zeros((self.Ndir, 1), int) k0_dkc = self.Gdir_dc.reshape(-1, 1, 3) else: self.kklst_dk = np.empty((self.Ndir, self.Nk), int) k0_dkc = np.empty((self.Ndir, self.Nk, 3), int) # Distance between kpoints kdist_c = np.empty(3) for c in range(3): # make a sorted list of the kpoint values in this direction slist = np.argsort(self.kpt_kc[:, c], kind='mergesort') skpoints_kc = np.take(self.kpt_kc, slist, axis=0) kdist_c[c] = max([skpoints_kc[n + 1, c] - skpoints_kc[n, c] for n in range(self.Nk - 1)]) for d, Gdir_c in enumerate(self.Gdir_dc): for k, k_c in enumerate(self.kpt_kc): # setup dist vector to next kpoint G_c = np.where(Gdir_c > 0, kdist_c, 0) if max(G_c) < 1e-4: self.kklst_dk[d, k] = k k0_dkc[d, k] = Gdir_c else: self.kklst_dk[d, k], k0_dkc[d, k] = \ neighbor_k_search(k_c, G_c, self.kpt_kc) # Set the inverse list of neighboring k-points self.invkklst_dk = np.empty((self.Ndir, self.Nk), int) for d in range(self.Ndir): for k1 in range(self.Nk): self.invkklst_dk[d, k1] = self.kklst_dk[d].tolist().index(k1) Nw = self.nwannier Nb = self.nbands self.Z_dkww = np.empty((self.Ndir, self.Nk, Nw, Nw), complex) self.V_knw = np.zeros((self.Nk, Nb, Nw), complex) if file is None: self.Z_dknn = np.empty((self.Ndir, self.Nk, Nb, Nb), complex) for d, dirG in enumerate(self.Gdir_dc): for k in range(self.Nk): k1 = self.kklst_dk[d, k] k0_c = k0_dkc[d, k] self.Z_dknn[d, k] = calc.get_wannier_localization_matrix( nbands=Nb, dirG=dirG, kpoint=k, nextkpoint=k1, G_I=k0_c, spin=self.spin) self.initialize(file=file, initialwannier=initialwannier, seed=seed) def initialize(self, file=None, initialwannier='random', seed=None): """Re-initialize current rotation matrix. Keywords are identical to those of the constructor. """ Nw = self.nwannier Nb = self.nbands if file is not None: self.Z_dknn, self.U_kww, self.C_kul = load(paropen(file)) elif initialwannier == 'bloch': # Set U and C to pick the lowest Bloch states self.U_kww = np.zeros((self.Nk, Nw, Nw), complex) self.C_kul = [] for U, M, L in zip(self.U_kww, self.fixedstates_k, self.edf_k): U[:] = np.identity(Nw, complex) if L > 0: self.C_kul.append( np.identity(Nb - M, complex)[:, :L]) else: self.C_kul.append([]) elif initialwannier == 'random': # Set U and C to random (orthogonal) matrices self.U_kww = np.zeros((self.Nk, Nw, Nw), complex) self.C_kul = [] for U, M, L in zip(self.U_kww, self.fixedstates_k, self.edf_k): U[:] = random_orthogonal_matrix(Nw, seed, real=False) if L > 0: self.C_kul.append(random_orthogonal_matrix( Nb - M, seed=seed, real=False)[:, :L]) else: self.C_kul.append(np.array([])) else: # Use initial guess to determine U and C self.C_kul, self.U_kww = self.calc.initial_wannier( initialwannier, self.kptgrid, self.fixedstates_k, self.edf_k, self.spin, self.nbands) self.update() def save(self, file): """Save information on localization and rotation matrices to file.""" dump((self.Z_dknn, self.U_kww, self.C_kul), paropen(file, 'w')) def update(self): # Update large rotation matrix V (from rotation U and coeff C) for k, M in enumerate(self.fixedstates_k): self.V_knw[k, :M] = self.U_kww[k, :M] if M < self.nwannier: self.V_knw[k, M:] = np.dot(self.C_kul[k], self.U_kww[k, M:]) # else: self.V_knw[k, M:] = 0.0 # Calculate the Zk matrix from the large rotation matrix: # Zk = V^d[k] Zbloch V[k1] for d in range(self.Ndir): for k in range(self.Nk): k1 = self.kklst_dk[d, k] self.Z_dkww[d, k] = np.dot(dag(self.V_knw[k]), np.dot( self.Z_dknn[d, k], self.V_knw[k1])) # Update the new Z matrix self.Z_dww = self.Z_dkww.sum(axis=1) / self.Nk def get_centers(self, scaled=False): """Calculate the Wannier centers :: pos = L / 2pi * phase(diag(Z)) """ coord_wc = np.angle(self.Z_dww[:3].diagonal(0, 1, 2)).T / (2 * pi) % 1 if not scaled: coord_wc = np.dot(coord_wc, self.largeunitcell_cc) return coord_wc def get_radii(self): """Calculate the spread of the Wannier functions. :: -- / L \ 2 2 radius**2 = - > | --- | ln |Z| --d \ 2pi / """ r2 = -np.dot(self.largeunitcell_cc.diagonal()**2 / (2 * pi)**2, np.log(abs(self.Z_dww[:3].diagonal(0, 1, 2))**2)) return np.sqrt(r2) def get_spectral_weight(self, w): return abs(self.V_knw[:, :, w])**2 / self.Nk def get_pdos(self, w, energies, width): """Projected density of states (PDOS). Returns the (PDOS) for Wannier function ``w``. The calculation is performed over the energy grid specified in energies. The PDOS is produced as a sum of Gaussians centered at the points of the energy grid and with the specified width. """ spec_kn = self.get_spectral_weight(w) dos = np.zeros(len(energies)) for k, spec_n in enumerate(spec_kn): eig_n = self.calc.get_eigenvalues(k=kpt, s=self.spin) for weight, eig in zip(spec_n, eig): # Add gaussian centered at the eigenvalue x = ((energies - center) / width)**2 dos += weight * np.exp(-x.clip(0., 40.)) / (sqrt(pi) * width) return dos def max_spread(self, directions=[0, 1, 2]): """Returns the index of the most delocalized Wannier function together with the value of the spread functional""" d = np.zeros(self.nwannier) for dir in directions: d[dir] = np.abs(self.Z_dww[dir].diagonal())**2 *self.weight_d[dir] index = np.argsort(d)[0] print 'Index:', index print 'Spread:', d[index] def translate(self, w, R): """Translate the w'th Wannier function The distance vector R = [n1, n2, n3], is in units of the basis vectors of the small cell. """ for kpt_c, U_ww in zip(self.kpt_kc, self.U_kww): U_ww[:, w] *= np.exp(2.j * pi * np.dot(np.array(R), kpt_c)) self.update() def translate_to_cell(self, w, cell): """Translate the w'th Wannier function to specified cell""" scaled_c = np.angle(self.Z_dww[:3, w, w]) * self.kptgrid / (2 * pi) trans = np.array(cell) - np.floor(scaled_c) self.translate(w, trans) def translate_all_to_cell(self, cell=[0, 0, 0]): """Translate all Wannier functions to specified cell. Move all Wannier orbitals to a specific unit cell. There exists an arbitrariness in the positions of the Wannier orbitals relative to the unit cell. This method can move all orbitals to the unit cell specified by ``cell``. For a `\Gamma`-point calculation, this has no effect. For a **k**-point calculation the periodicity of the orbitals are given by the large unit cell defined by repeating the original unitcell by the number of **k**-points in each direction. In this case it is usefull to move the orbitals away from the boundaries of the large cell before plotting them. For a bulk calculation with, say 10x10x10 **k** points, one could move the orbitals to the cell [2,2,2]. In this way the pbc boundary conditions will not be noticed. """ scaled_wc = np.angle(self.Z_dww[:3].diagonal(0, 1, 2)).T * \ self.kptgrid / (2 * pi) trans_wc = np.array(cell)[None] - np.floor(scaled_wc) for kpt_c, U_ww in zip(self.kpt_kc, self.U_kww): U_ww *= np.exp(2.j * pi * np.dot(trans_wc, kpt_c)) self.update() def distances(self, R): Nw = self.nwannier cen = self.get_centers() r1 = cen.repeat(Nw, axis=0).reshape(Nw, Nw, 3) r2 = cen.copy() for i in range(3): r2 += self.unitcell_cc[i] * R[i] r2 = np.swapaxes(r2.repeat(Nw, axis=0).reshape(Nw, Nw, 3), 0, 1) return np.sqrt(np.sum((r1 - r2)**2, axis=-1)) def get_hopping(self, R): """Returns the matrix H(R)_nm=<0,n|H|R,m>. :: 1 _ -ik.R H(R) = <0,n|H|R,m> = --- >_ e H(k) Nk k where R is the cell-distance (in units of the basis vectors of the small cell) and n,m are indices of the Wannier functions. """ H_ww = np.zeros([self.nwannier, self.nwannier], complex) for k, kpt_c in enumerate(self.kpt_kc): phase = np.exp(-2.j * pi * np.dot(np.array(R), kpt_c)) H_ww += self.get_hamiltonian(k) * phase return H_ww / self.Nk def get_hamiltonian(self, k=0): """Get Hamiltonian at existing k-vector of index k :: dag H(k) = V diag(eps ) V k k k """ eps_n = self.calc.get_eigenvalues(kpt=k, spin=self.spin)[:self.nbands] return np.dot(dag(self.V_knw[k]) * eps_n, self.V_knw[k]) def get_hamiltonian_kpoint(self, kpt_c): """Get Hamiltonian at some new arbitrary k-vector :: _ ik.R H(k) = >_ e H(R) R Warning: This method moves all Wannier functions to cell (0, 0, 0) """ if self.verbose: print 'Translating all Wannier functions to cell (0, 0, 0)' self.translate_all_to_cell() max = (self.kptgrid - 1) / 2 N1, N2, N3 = max Hk = np.zeros([self.nwannier, self.nwannier], complex) for n1 in xrange(-N1, N1 + 1): for n2 in xrange(-N2, N2 + 1): for n3 in xrange(-N3, N3 + 1): R = np.array([n1, n2, n3], float) hop_ww = self.get_hopping(R) phase = np.exp(+2.j * pi * np.dot(R, kpt_c)) Hk += hop_ww * phase return Hk def get_function(self, index, repeat=None): """Get Wannier function on grid. Returns an array with the funcion values of the indicated Wannier function on a grid with the size of the *repeated* unit cell. For a calculation using **k**-points the relevant unit cell for eg. visualization of the Wannier orbitals is not the original unit cell, but rather a larger unit cell defined by repeating the original unit cell by the number of **k**-points in each direction. Note that for a `\Gamma`-point calculation the large unit cell coinsides with the original unit cell. The large unitcell also defines the periodicity of the Wannier orbitals. ``index`` can be either a single WF or a coordinate vector in terms of the WFs. """ # Default size of plotting cell is the one corresponding to k-points. if repeat is None: repeat = self.kptgrid N1, N2, N3 = repeat dim = self.calc.get_number_of_grid_points() largedim = dim * [N1, N2, N3] wanniergrid = np.zeros(largedim, dtype=complex) for k, kpt_c in enumerate(self.kpt_kc): # The coordinate vector of wannier functions if type(index) == int: vec_n = self.V_knw[k, :, index] else: vec_n = np.dot(self.V_knw[k], index) wan_G = np.zeros(dim, complex) for n, coeff in enumerate(vec_n): wan_G += coeff * self.calc.get_pseudo_wave_function( n, k, self.spin, pad=True) # Distribute the small wavefunction over large cell: for n1 in xrange(N1): for n2 in xrange(N2): for n3 in xrange(N3): # sign? e = np.exp(-2.j * pi * np.dot([n1, n2, n3], kpt_c)) wanniergrid[n1 * dim[0]:(n1 + 1) * dim[0], n2 * dim[1]:(n2 + 1) * dim[1], n3 * dim[2]:(n3 + 1) * dim[2]] += e * wan_G # Normalization wanniergrid /= np.sqrt(self.Nk) return wanniergrid def write_cube(self, index, fname, repeat=None, real=True): """Dump specified Wannier function to a cube file""" from ase.io.cube import write_cube # Default size of plotting cell is the one corresponding to k-points. if repeat is None: repeat = self.kptgrid atoms = self.calc.get_atoms() * repeat func = self.get_function(index, repeat) # Handle separation of complex wave into real parts if real: if self.Nk == 1: func *= np.exp(-1.j * np.angle(func.max())) if 0: assert max(abs(func.imag).flat) < 1e-4 func = func.real else: func = abs(func) else: phase_fname = fname.split('.') phase_fname.insert(1, 'phase') phase_fname = '.'.join(phase_fname) write_cube(phase_fname, atoms, data=np.angle(func)) func = abs(func) write_cube(fname, atoms, data=func) def localize(self, step=0.25, tolerance=1e-08, updaterot=True, updatecoeff=True): """Optimize rotation to give maximal localization""" md_min(self, step, tolerance, verbose=self.verbose, updaterot=updaterot, updatecoeff=updatecoeff) def get_functional_value(self): """Calculate the value of the spread functional. :: Tr[|ZI|^2]=sum(I)sum(n) w_i|Z_(i)_nn|^2, where w_i are weights.""" a_d = np.sum(np.abs(self.Z_dww.diagonal(0, 1, 2))**2, axis=1) return np.dot(a_d, self.weight_d).real def get_gradients(self): # Determine gradient of the spread functional. # # The gradient for a rotation A_kij is:: # # dU = dRho/dA_{k,i,j} = sum(I) sum(k') # + Z_jj Z_kk',ij^* - Z_ii Z_k'k,ij^* # - Z_ii^* Z_kk',ji + Z_jj^* Z_k'k,ji # # The gradient for a change of coefficients is:: # # dRho/da^*_{k,i,j} = sum(I) [[(Z_0)_{k} V_{k'} diag(Z^*) + # (Z_0_{k''})^d V_{k''} diag(Z)] * # U_k^d]_{N+i,N+j} # # where diag(Z) is a square,diagonal matrix with Z_nn in the diagonal, # k' = k + dk and k = k'' + dk. # # The extra degrees of freedom chould be kept orthonormal to the fixed # space, thus we introduce lagrange multipliers, and minimize instead:: # # Rho_L=Rho- sum_{k,n,m} lambda_{k,nm} <c_{kn}|c_{km}> # # for this reason the coefficient gradients should be multiplied # by (1 - c c^d). Nb = self.nbands Nw = self.nwannier dU = [] dC = [] for k in xrange(self.Nk): M = self.fixedstates_k[k] L = self.edf_k[k] U_ww = self.U_kww[k] C_ul = self.C_kul[k] Utemp_ww = np.zeros((Nw, Nw), complex) Ctemp_nw = np.zeros((Nb, Nw), complex) for d, weight in enumerate(self.weight_d): if abs(weight) < 1.0e-6: continue Z_knn = self.Z_dknn[d] diagZ_w = self.Z_dww[d].diagonal() Zii_ww = np.repeat(diagZ_w, Nw).reshape(Nw, Nw) k1 = self.kklst_dk[d, k] k2 = self.invkklst_dk[d, k] V_knw = self.V_knw Z_kww = self.Z_dkww[d] if L > 0: Ctemp_nw += weight * np.dot( np.dot(Z_knn[k], V_knw[k1]) * diagZ_w.conj() + np.dot(dag(Z_knn[k2]), V_knw[k2]) * diagZ_w, dag(U_ww)) temp = Zii_ww.T * Z_kww[k].conj() - Zii_ww * Z_kww[k2].conj() Utemp_ww += weight * (temp - dag(temp)) dU.append(Utemp_ww.ravel()) if L > 0: # Ctemp now has same dimension as V, the gradient is in the # lower-right (Nb-M) x L block Ctemp_ul = Ctemp_nw[M:, M:] G_ul = Ctemp_ul - np.dot(np.dot(C_ul, dag(C_ul)), Ctemp_ul) dC.append(G_ul.ravel()) return np.concatenate(dU + dC) def step(self, dX, updaterot=True, updatecoeff=True): # dX is (A, dC) where U->Uexp(-A) and C->C+dC Nw = self.nwannier Nk = self.Nk M_k = self.fixedstates_k L_k = self.edf_k if updaterot: A_kww = dX[:Nk * Nw**2].reshape(Nk, Nw, Nw) for U, A in zip(self.U_kww, A_kww): H = -1.j * A.conj() epsilon, Z = np.linalg.eigh(H) # Z contains the eigenvectors as COLUMNS. # Since H = iA, dU = exp(-A) = exp(iH) = ZDZ^d dU = np.dot(Z * np.exp(1.j * epsilon), dag(Z)) if U.dtype == float: U[:] = np.dot(U, dU).real else: U[:] = np.dot(U, dU) if updatecoeff: start = 0 for C, unocc, L in zip(self.C_kul, self.nbands - M_k, L_k): if L == 0 or unocc == 0: continue Ncoeff = L * unocc deltaC = dX[Nk * Nw**2 + start: Nk * Nw**2 + start + Ncoeff] C += deltaC.reshape(unocc, L) gram_schmidt(C) start += Ncoeff self.update()
askhl/ase
ase/dft/wannier.py
Python
gpl-2.0
30,303
[ "ASE", "Gaussian" ]
45466ad893558132d478a19e55fe321639efdad085f1af55b6e566b89badd686
#!/usr/bin/python3 ''' --------------------------------------------------------------------------------------- CrossMap: lift over genomic coordinates between genome assemblies. Supports BED/BedGraph, GFF/GTF, BAM/SAM, BigWig/Wig, VCF format files. http://crossmap.sourceforge.net/ ------------------------------------------------------------------------------------------ ''' import os,sys import optparse import collections import subprocess import string from textwrap import wrap from time import strftime import pyBigWig import pysam from bx.intervals import * import numpy as np import datetime from cmmodule import ireader from cmmodule import BED from cmmodule import annoGene from cmmodule import sam_header from cmmodule import myutils from cmmodule import bgrMerge __author__ = "Liguo Wang, Hao Zhao" __contributor__="Liguo Wang, Hao Zhao" __copyright__ = "Copyleft" __credits__ = [] __license__ = "GPLv2" __version__="0.3.1" __maintainer__ = "Liguo Wang" __email__ = "wangliguo78@gmail.com" __status__ = "Production" def printlog (mesg_lst): ''' print progress into stderr ''' if len(mesg_lst)==1: msg = "@ " + strftime("%Y-%m-%d %H:%M:%S") + ": " + mesg_lst[0] else: msg = "@ " + strftime("%Y-%m-%d %H:%M:%S") + ": " + ' '.join(mesg_lst) print(msg, file=sys.stderr) def parse_header( line ): return dict( [ field.split( '=' ) for field in line.split()[1:] ] ) def revcomp_DNA(dna): ''' reverse complement of input DNA sequence. ''' complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A','N':'N','X':'X'} seq = dna.upper() return ''.join(complement[base] for base in reversed(seq)) def wiggleReader( f ): ''' Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack scores are ignored. ''' current_chrom = None current_pos = None current_step = None # always for wiggle data strand = '+' mode = "bed" for line in ireader.reader(f): if line.isspace() or line.startswith( "track" ) or line.startswith( "#" ) or line.startswith( "browser" ): continue elif line.startswith( "variableStep" ): header = parse_header( line ) current_chrom = header['chrom'] current_pos = None current_step = None if 'span' in header: current_span = int( header['span'] ) else: current_span = 1 mode = "variableStep" elif line.startswith( "fixedStep" ): header = parse_header( line ) current_chrom = header['chrom'] current_pos = int( header['start'] ) - 1 current_step = int( header['step'] ) if 'span' in header: current_span = int( header['span'] ) else: current_span = 1 mode = "fixedStep" elif mode == "bed": fields = line.split() if len( fields ) > 3: if len( fields ) > 5: yield fields[0], int( fields[1] ), int( fields[2] ), fields[5], float( fields[3] ) else: yield fields[0], int( fields[1] ), int( fields[2] ), strand, float( fields[3] ) elif mode == "variableStep": fields = line.split() pos = int( fields[0] ) - 1 yield current_chrom, pos, pos + current_span, strand, float( fields[1] ) elif mode == "fixedStep": yield current_chrom, current_pos, current_pos + current_span, strand, float( line.split()[0] ) current_pos += current_step else: raise "Unexpected input line: %s" % line.strip() def bigwigReader(infile, bin_size = 2000): ''' infile: bigwig format file chromsize: chrom_name: size. return: chrom, position (0-based), value ''' bw = pyBigWig.open(infile) chrom_sizes = bw.chroms() #print (chrom_sizes) for chr_name, chr_size in list(chrom_sizes.items()): for chrom, st, end in BED.tillingBed(chrName = chr_name,chrSize = chr_size,stepSize = bin_size): try: a = bw.stats(chrom,st,end) except: continue if bw.stats(chrom,st,end)[0] is None: continue sig_list = bw.values(chrom,st,end) sig_list = np.nan_to_num(sig_list) #change 'nan' into '0.' low_bound = st point_num = 1 score = sig_list[0] for value in (sig_list[1:]): if value == score: point_num += 1 else: yield(( chrom, low_bound, low_bound + point_num, score)) score = value low_bound = low_bound + point_num point_num = 1 def check_bed12(bedline): ''' check if bed12 format is correct or not ''' fields = bedline.strip().split() if len(fields) !=12: return False if fields[5] not in ['+','-','.']: return False try: chromStart = int(fields[1]) chromEnd = int(fields[2]) thickStart = int(fields[6]) thickEnd = int(fields[7]) blockCount = int(fields[9]) blockSizes = [int(i) for i in fields[10].rstrip(',').split(',')] blockStarts = [int(i) for i in fields[11].rstrip(',').split(',')] except: return False if chromStart > chromEnd or thickStart > thickEnd: return False if thickStart < chromStart or thickEnd > chromEnd: return False if len(blockSizes) != blockCount: return False if len(blockStarts) != blockCount: return False if blockCount <1: return False for i in blockSizes: if i < 0: return False for i in blockStarts: if i < 0: return False return True def intersectBed(xxx_todo_changeme, xxx_todo_changeme1): ''' return intersection of two bed regions ''' (chr1, st1, end1) = xxx_todo_changeme (chr2, st2, end2) = xxx_todo_changeme1 if int(st1) > int(end1) or int(st2) > int(end2): raise Exception ("Start cannot be larger than end") if chr1 != chr2: return None if int(st1) > int(end2) or int(end1) < int(st2): return None return (chr1, max(st1, st2), min(end1,end2)) def read_chain_file (chain_file, print_table=False): ''' input chain_file could be either plain text, compressed file (".gz", ".Z", ".z", ".bz", ".bz2", ".bzip2"), or a URL pointing to the chain file ("http://", "https://", "ftp://"). If url was used, chain file must be plain text ''' printlog(["Read chain_file: ", chain_file]), maps={} target_chromSize={} source_chromSize={} if print_table: blocks=[] for line in ireader.reader(chain_file): # Example: chain 4900 chrY 58368225 + 25985403 25985638 chr5 151006098 - 43257292 43257528 1 if not line.strip(): continue line=line.strip() if line.startswith(('#',' ')):continue fields = line.split() if fields[0] == 'chain' and len(fields) in [12, 13]: score = int(fields[1]) # Alignment score source_name = fields[2] # E.g. chrY source_size = int(fields[3]) # Full length of the chromosome source_strand = fields[4] # Must be + if source_strand != '+': raise Exception("Source strand in an .over.chain file must be +. (%s)" % line) source_start = int(fields[5]) # Start of source region source_end = int(fields[6]) # End of source region target_name = fields[7] # E.g. chr5 target_size = int(fields[8]) # Full length of the chromosome target_strand = fields[9] # + or - target_start = int(fields[10]) target_end = int(fields[11]) target_chromSize[target_name]= target_size source_chromSize[source_name] = source_size if target_strand not in ['+', '-']: raise Exception("Target strand must be - or +. (%s)" % line) #if target_strand == '+': # target_start = int(fields[10]) # target_end = int(fields[11]) #if target_strand == '-': # target_start = target_size - target_end # target_end = target_size - target_start chain_id = None if len(fields) == 12 else fields[12] if source_name not in maps: maps[source_name] = Intersecter() sfrom, tfrom = source_start, target_start # Now read the alignment chain from the file and store it as a list (source_from, source_to) -> (target_from, target_to) elif fields[0] != 'chain' and len(fields) == 3: size, sgap, tgap = int(fields[0]), int(fields[1]), int(fields[2]) if print_table: if target_strand == '+': blocks.append((source_name,sfrom, sfrom+size, source_strand, target_name, tfrom, tfrom+size, target_strand)) elif target_strand == '-': blocks.append((source_name,sfrom, sfrom+size, source_strand, target_name, target_size - (tfrom+size), target_size - tfrom, target_strand)) if target_strand == '+': maps[source_name].add_interval( Interval(sfrom, sfrom+size,(target_name,tfrom, tfrom+size,target_strand))) elif target_strand == '-': maps[source_name].add_interval( Interval(sfrom, sfrom+size,(target_name,target_size - (tfrom+size), target_size - tfrom, target_strand))) sfrom += size + sgap tfrom += size + tgap elif fields[0] != 'chain' and len(fields) == 1: size = int(fields[0]) if print_table: if target_strand == '+': blocks.append((source_name,sfrom, sfrom+size, source_strand, target_name, tfrom, tfrom+size, target_strand)) elif target_strand == '-': blocks.append((source_name,sfrom, sfrom+size, source_strand, target_name, target_size - (tfrom+size), target_size - tfrom, target_strand)) if target_strand == '+': maps[source_name].add_interval( Interval(sfrom, sfrom+size,(target_name,tfrom, tfrom+size,target_strand))) elif target_strand == '-': maps[source_name].add_interval( Interval(sfrom, sfrom+size,(target_name,target_size - (tfrom+size), target_size - tfrom, target_strand))) else: raise Exception("Invalid chain format. (%s)" % line) if (sfrom + size) != source_end or (tfrom + size) != target_end: raise Exception("Alignment blocks do not match specified block sizes. (%s)" % header) if print_table: for i in blocks: print('\t'.join([str(n) for n in i])) return (maps,target_chromSize, source_chromSize) def map_coordinates(mapping, q_chr, q_start, q_end, q_strand='+', print_match=False): ''' Map coordinates from source assembly to target assembly ''' matches=[] complement ={'+':'-','-':'+'} if q_chr not in mapping: return None else: targets = mapping[q_chr].find(q_start, q_end) if len(targets)==0: return None elif len(targets)==1: s_start = targets[0].start s_end = targets[0].end t_chrom = targets[0].value[0] t_start = targets[0].value[1] t_end = targets[0].value[2] t_strand = targets[0].value[3] (chr, real_start, real_end) = intersectBed((q_chr,q_start,q_end),(q_chr,s_start,s_end)) l_offset = abs(real_start - s_start) #r_offset = real_end - s_end size = abs(real_end - real_start) matches.append( (chr, real_start, real_end,q_strand)) if t_strand == '+': i_start = t_start + l_offset if q_strand == '+': matches.append( (t_chrom, i_start, i_start + size, t_strand)) else: matches.append( (t_chrom, i_start, i_start + size, complement[t_strand])) elif t_strand == '-': i_start = t_end - l_offset - size if q_strand == '+': matches.append( (t_chrom, i_start, i_start + size, t_strand)) else: matches.append( (t_chrom, i_start, i_start + size, complement[t_strand])) else: raise Exception("Unknown strand: %s. Can only be '+' or '-'." % q_strand) elif len(targets) > 1: for t in targets: s_start = t.start s_end = t.end t_chrom = t.value[0] t_start = t.value[1] t_end = t.value[2] t_strand = t.value[3] (chr, real_start, real_end) = intersectBed((q_chr,q_start,q_end),(q_chr,s_start,s_end)) l_offset = abs(real_start - s_start) #r_offset = abs(real_end - s_end) size = abs(real_end - real_start) matches.append( (chr, real_start, real_end,q_strand) ) if t_strand == '+': i_start = t_start + l_offset if q_strand == '+': matches.append( (t_chrom, i_start, i_start + size, t_strand)) else: matches.append( (t_chrom, i_start, i_start + size, complement[t_strand])) elif t_strand == '-': i_start = t_end - l_offset - size if q_strand == '+': matches.append( (t_chrom, i_start, i_start + size, t_strand)) else: matches.append( (t_chrom, i_start, i_start + size, complement[t_strand])) else: raise Exception("Unknown strand: %s. Can only be '+' or '-'." % q_strand) if print_match: print(matches) # input: 'chr1',246974830,247024835 # output: [('chr1', 246974830, 246974833, '+' ), ('chr1', 248908207, 248908210, '+' ), ('chr1', 247024833, 247024835, '+'), ('chr1', 249058210, 249058212,'+')] # [('chr1', 246974830, 246974833), ('chr1', 248908207, 248908210)] return matches def crossmap_vcf_file(mapping, infile,outfile, liftoverfile, refgenome): ''' Convert genome coordinates in VCF format. ''' #index refegenome file if it hasn't been done if not os.path.exists(refgenome + '.fai'): printlog(["Creating index for", refgenome]) pysam.faidx(refgenome) refFasta = pysam.Fastafile(refgenome) FILE_OUT = open(outfile ,'w') UNMAP = open(outfile + '.unmap','w') total = 0 fail = 0 withChr = False # check if the VCF data lines use 'chr1' or '1' for line in ireader.reader(infile): if not line.strip(): continue line=line.strip() #deal with meta-information lines. #meta-information lines needed in both mapped and unmapped files if line.startswith('##fileformat'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##INFO'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##FILTER'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##FORMAT'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##ALT'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##SAMPLE'): print(line, file=FILE_OUT) print(line, file=UNMAP) elif line.startswith('##PEDIGREE'): print(line, file=FILE_OUT) print(line, file=UNMAP) #meta-information lines needed in unmapped files elif line.startswith('##assembly'): print(line, file=UNMAP) elif line.startswith('##contig'): print(line, file=UNMAP) if 'ID=chr' in line: withChr = True #update contig information elif line.startswith('#CHROM'): printlog(["Updating contig field ... "]) target_gsize = dict(list(zip(refFasta.references, refFasta.lengths))) for chr_id in sorted(target_gsize): if chr_id.startswith('chr'): if withChr is True: print("##contig=<ID=%s,length=%d,assembly=%s>" % (chr_id, target_gsize[chr_id], os.path.basename(refgenome)), file=FILE_OUT) else: print("##contig=<ID=%s,length=%d,assembly=%s>" % (chr_id.replace('chr',''), target_gsize[chr_id], os.path.basename(refgenome)), file=FILE_OUT) else: if withChr is True: print("##contig=<ID=%s,length=%d,assembly=%s>" % ('chr' + chr_id, target_gsize[chr_id], os.path.basename(refgenome)), file=FILE_OUT) else: print("##contig=<ID=%s,length=%d,assembly=%s>" % (chr_id, target_gsize[chr_id], os.path.basename(refgenome)), file=FILE_OUT) print("##liftOverProgram=CrossMap(https://sourceforge.net/projects/crossmap/)", file=FILE_OUT) print("##liftOverFile=" + liftoverfile, file=FILE_OUT) print("##new_reference_genome=" + refgenome, file=FILE_OUT) print("##liftOverTime=" + datetime.date.today().strftime("%B%d,%Y"), file=FILE_OUT) print(line, file=FILE_OUT) print(line, file=UNMAP) else: if line.startswith('#'):continue fields = str.split(line,maxsplit=7) total += 1 if fields[0].startswith('chr'): chrom = fields[0] else: chrom = 'chr' + fields[0] start = int(fields[1])-1 # 0 based end = start + len(fields[3]) a = map_coordinates(mapping, chrom, start, end,'+') if a is None: print(line, file=UNMAP) fail += 1 continue if len(a) == 2: # update chrom target_chr = str(a[1][0]) #target_chr is from chain file, could be 'chr1' or '1' target_start = a[1][1] target_end = a[1][2] if withChr is False: fields[0] = target_chr.replace('chr','') else: fields[0] = target_chr # update start coordinate fields[1] = target_start + 1 if refFasta.references[0].startswith('chr'): if target_chr.startswith('chr'): fields[3] = refFasta.fetch(target_chr,target_start,target_end).upper() else: fields[3] = refFasta.fetch('chr'+target_chr,target_start,target_end).upper() else: if target_chr.startswith('chr'): fields[3] = refFasta.fetch(target_chr.replace('chr',''),target_start,target_end).upper() else: fields[3] = refFasta.fetch(target_chr,target_start,target_end).upper() if fields[3] != fields[4]: print('\t'.join(map(str, fields)), file=FILE_OUT) else: print(line, file=UNMAP) fail += 1 else: print(line, file=UNMAP) fail += 1 continue FILE_OUT.close() UNMAP.close() printlog (["Total entries:", str(total)]) printlog (["Failed to map:", str(fail)]) def crossmap_bed_file(mapping, inbed,outfile=None): ''' Convert genome coordinates (in bed format) between assemblies. BED format: http://genome.ucsc.edu/FAQ/FAQformat.html#format1 ''' # check if 'outfile' was set. If not set, print to screen, if set, print to file if outfile is not None: FILE_OUT = open(outfile,'w') UNMAP = open(outfile + '.unmap','w') else: pass for line in ireader.reader(inbed): if line.startswith('#'):continue if line.startswith('track'):continue if line.startswith('browser'):continue if not line.strip():continue line=line.strip() fields=line.split() strand = '+' # filter out line less than 3 columns if len(fields)<3: print("Less than 3 fields. skip " + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue try: int(fields[1]) except: print("Start corrdinate is not an integer. skip " + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue try: int(fields[2]) except: print("End corrdinate is not an integer. skip " + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue if int(fields[1]) > int(fields[2]): print("\"Start\" is larger than \"End\" corrdinate is not an integer. skip " + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue # deal with bed less than 12 columns if len(fields)<12: # try to reset strand try: for f in fields: if f in ['+','-']: strand = f except: pass a = map_coordinates(mapping, fields[0], int(fields[1]),int(fields[2]),strand) # example of a: [('chr1', 246974830, 246974833,'+'), ('chr1', 248908207, 248908210,'+')] try: if len(a) % 2 != 0: if outfile is None: print(line + '\tFail') else: print(line, file=UNMAP) continue if len(a) == 2: #reset fields fields[0] = a[1][0] fields[1] = a[1][1] fields[2] = a[1][2] for i in range(0,len(fields)): #update the strand information if fields[i] in ['+','-']: fields[i] = a[1][3] if outfile is None: print(line + '\t->\t' + '\t'.join([str(i) for i in fields])) else: print('\t'.join([str(i) for i in fields]), file=FILE_OUT) if len(a) >2 : count=0 for j in range(1,len(a),2): count += 1 fields[0] = a[j][0] fields[1] = a[j][1] fields[2] = a[j][2] for i in range(0,len(fields)): #update the strand information if fields[i] in ['+','-']: fields[i] = a[j][3] if outfile is None: print(line + '\t'+ '(split.' + str(count) + ':' + ':'.join([str(i) for i in a[j-1]]) + ')\t' + '\t'.join([str(i) for i in fields])) else: print('\t'.join([str(i) for i in fields]), file=FILE_OUT) except: if outfile is None: print(line + '\tFail') else: print(line, file=UNMAP) continue # deal with bed12 and bed12+8 (genePred format) if len(fields)==12 or len(fields)==20: strand = fields[5] if strand not in ['+','-']: raise Exception("Unknown strand: %s. Can only be '+' or '-'." % strand) fail_flag=False exons_old_pos = annoGene.getExonFromLine(line) #[[chr,st,end],[chr,st,end],...] #print exons_old_pos exons_new_pos = [] for e_chr, e_start, e_end in exons_old_pos: a = map_coordinates(mapping, e_chr, e_start, e_end, strand) if a is None: fail_flag =True break if len(a) == 2: exons_new_pos.append(a[1]) # a has two elements, first is query, 2nd is target. # [('chr1', 246974830, 246974833,'+'), ('chr1', 248908207, 248908210,'+')] else: fail_flag =True break if not fail_flag: # check if all exons were mapped to the same chromosome the same strand chr_id = set() exon_strand = set() for e_chr, e_start, e_end, e_strand in exons_new_pos: chr_id.add(e_chr) exon_strand.add(e_strand) if len(chr_id) != 1 or len(exon_strand) != 1: fail_flag = True if not fail_flag: # build new bed cds_start_offset = int(fields[6]) - int(fields[1]) cds_end_offset = int(fields[2]) - int(fields[7]) new_chrom = exons_new_pos[0][0] new_chrom_st = exons_new_pos[0][1] new_chrom_end = exons_new_pos[-1][2] new_name = fields[3] new_score = fields[4] new_strand = exons_new_pos[0][3] new_thickStart = new_chrom_st + cds_start_offset new_thickEnd = new_chrom_end - cds_end_offset new_ittemRgb = fields[8] new_blockCount = len(exons_new_pos) new_blockSizes = ','.join([str(o - n) for m,n,o,p in exons_new_pos]) new_blockStarts = ','.join([str(n - new_chrom_st) for m,n,o,p in exons_new_pos]) new_bedline = '\t'.join(str(i) for i in (new_chrom,new_chrom_st,new_chrom_end,new_name,new_score,new_strand,new_thickStart,new_thickEnd,new_ittemRgb,new_blockCount,new_blockSizes,new_blockStarts)) if check_bed12(new_bedline) is False: fail_flag = True else: if outfile is None: print(line + '\t->\t' + new_bedline) else: print(new_bedline, file=FILE_OUT) if fail_flag: if outfile is None: print(line + '\tFail') else: print(line, file=UNMAP) def crossmap_gff_file(mapping, ingff,outfile=None): ''' Convert genome coordinates (in GFF/GTF format) between assemblies. GFF (General Feature Format) lines have nine required fields that must be Tab-separated: 1. seqname - The name of the sequence. Must be a chromosome or scaffold. 2. source - The program that generated this feature. 3. feature - The name of this type of feature. Some examples of standard feature types are "CDS", "start_codon", "stop_codon", and "exon". 4. start - The starting position of the feature in the sequence. The first base is numbered 1. 5. end - The ending position of the feature (inclusive). 6. score - A score between 0 and 1000. If the track line useScore attribute is set to 1 for this annotation data set, the score value will determine the level of gray in which this feature is displayed (higher numbers = darker gray). If there is no score value, enter ".". 7. strand - Valid entries include '+', '-', or '.' (for don't know/don't care). 8. frame - If the feature is a coding exon, frame should be a number between 0-2 that represents the reading frame of the first base. If the feature is not a coding exon, the value should be '.'. 9. group - All lines with the same group are linked together into a single item. GFF format: http://genome.ucsc.edu/FAQ/FAQformat.html#format3 GTF (Gene Transfer Format) is a refinement to GFF that tightens the specification. The first eight GTF fields are the same as GFF. The group field has been expanded into a list of attributes. Each attribute consists of a type/value pair. Attributes must end in a semi-colon, and be separated from any following attribute by exactly one space. GTF format: http://genome.ucsc.edu/FAQ/FAQformat.html#format4 We do NOT check if features (exon, CDS, etc) belonging to the same gene originally were converted into the same chromosome/strand. ''' if outfile is not None: FILE_OUT = open(outfile,'w') UNMAP = open(outfile + '.unmap', 'w') for line in ireader.reader(ingff): if line.startswith('#'):continue if line.startswith('track'):continue if line.startswith('browser'):continue if line.startswith('visibility'):continue if not line.strip():continue line=line.strip() fields=line.split('\t') # check GFF file #if len(fields) != 9: # print >>sys.stderr, 'GFF file must has 9 columns. Skip ' + line # continue try: start = int(fields[3]) - 1 #0-based end = int(fields[4])/1 feature_size = end - start except: print('Cannot recognize \"start\" and \"end\" coordinates. Skip ' + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue if fields[6] not in ['+','-','.']: print('Cannot recognize \"strand\". Skip ' + line, file=sys.stderr) if outfile: print(line, file=UNMAP) continue strand = '-' if fields[6] == '-' else '+' chrom = fields[0] a = map_coordinates(mapping, chrom,start,end,strand) if a is None: if outfile is None: print(line + '\tfail (no match to target assembly)') else: print(line, file=UNMAP) continue if len(a) !=2: if outfile is None: print(line + '\tfail (multpile match to target assembly)') else: print(line, file=UNMAP) else: if (int(a[1][2]) - int(a[1][1])) != feature_size: # check if it is exact match if outfile is None: print(line + '\tfail (not exact match)') else: print(line, file=UNMAP) fields[0] = a[1][0] # chrom fields[3] = a[1][1] + 1 # start, 1-based fields[4] = a[1][2] fields[6] = a[1][3] if outfile is None: print(line + '\t->\t' + '\t'.join([str(i) for i in fields])) else: print('\t'.join([str(i) for i in fields]), file=FILE_OUT) def crossmap_bam_file(mapping, chainfile, infile, outfile_prefix, chrom_size, IS_size=200, IS_std=30, fold=3, addtag = True): ''' Convert genome coordinates (in BAM/SAM format) between assemblies. BAM/SAM format: http://samtools.sourceforge.net/ chrom_size is target chromosome size if addtag is set to True, will add tags to each alignmnet: Q = QC (QC failed) N = unmapped (originally unmapped or originally mapped but failed to liftover to new assembly) M = multiple mapped (alignment can be liftover to multiple places) U = unique mapped (alignment can be liftover to only 1 place) tags for pair-end sequencing include: QF: QC failed NN: both read1 and read2 unmapped NU: read1 unmapped, read2 unique mapped NM: read1 unmapped, multiple mapped UN: read1 uniquely mapped, read2 unmap UU: both read1 and read2 uniquely mapped UM: read1 uniquely mapped, read2 multiple mapped MN: read1 multiple mapped, read2 unmapped MU: read1 multiple mapped, read2 unique mapped MM: both read1 and read2 multiple mapped tags for single-end sequencing include: QF: QC failed SN: unmaped SM: multiple mapped SU: uniquely mapped ''' # determine the input file format (BAM or SAM) try: samfile = pysam.Samfile(infile,'rb') if len(samfile.header) == 0: print("BAM file has no header section. Exit!", file=sys.stderr) sys.exit(1) bam_format = True except: samfile = pysam.Samfile(infile,'r') if len(samfile.header) == 0: print("SAM file has no header section. Exit!", file=sys.stderr) sys.exit(1) bam_format = False # add comments into BAM/SAM header section if bam_format: comments=['Liftover from original BAM file: ' + infile] else: comments=['Liftover from original SAM file: ' + infile] comments.append('Liftover is based on the chain file: ' + chainfile) sam_ori_header = samfile.header (new_header, name_to_id) = sam_header.bam_header_generator(orig_header = sam_ori_header, chrom_size = chrom_size, prog_name="CrossMap",prog_ver = __version__, format_ver=1.0,sort_type = 'coordinate',co=comments) # write to file if outfile_prefix is not None: if bam_format: OUT_FILE = pysam.Samfile( outfile_prefix + '.bam', "wb", header = new_header ) #OUT_FILE_UNMAP = pysam.Samfile( outfile_prefix + '.unmap.bam', "wb", template=samfile ) printlog (["Liftover BAM file:", infile, '==>', outfile_prefix + '.bam']) else: OUT_FILE = pysam.Samfile( outfile_prefix + '.sam', "wh", header = new_header ) #OUT_FILE_UNMAP = pysam.Samfile( outfile_prefix + '.unmap.sam', "wh", template=samfile ) printlog (["Liftover SAM file:", infile, '==>', outfile_prefix + '.sam']) # write to screen else: if bam_format: OUT_FILE = pysam.Samfile( '-', "wb", header = new_header ) #OUT_FILE_UNMAP = pysam.Samfile( infile.replace('.bam','') + '.unmap.bam', "wb", template=samfile ) printlog (["Liftover BAM file:", infile]) else: OUT_FILE = pysam.Samfile( '-', "w", header = new_header ) #OUT_FILE_UNMAP = pysam.Samfile( infile.replace('.sam','') + '.unmap.sam', "wh", template=samfile ) printlog (["Liftover SAM file:", infile]) QF = 0 NN = 0 NU = 0 NM = 0 UN = 0 UU = 0 UM = 0 MN = 0 MU = 0 MM = 0 SN = 0 SM = 0 SU = 0 total_item = 0 try: while(1): total_item += 1 new_alignment = pysam.AlignedRead() # create AlignedRead object old_alignment = next(samfile) # qcfailed reads will be written to OUT_FILE_UNMAP for both SE and PE reads if old_alignment.is_qcfail: QF += 1 if addtag: old_alignment.set_tag(tag="QF", value=0) OUT_FILE.write(old_alignment) continue # new_alignment.qqual = old_alignment.qqual # quality string of read, exclude soft clipped part # new_alignment.qlen = old_alignment.qlen # length of the "aligned part of read" # new_alignment. aligned_pairs = old_alignment. aligned_pairs #read coordinates <=> ref coordinates # new_alignment_aend = old_alignment.aend # reference End position of the aligned part (of read) #new_alignment.qname = old_alignment.qname # 1st column. read name. #new_alignment.flag = old_alignment.flag # 2nd column. subject to change. flag value #new_alignment.tid = old_alignment.tid # 3rd column. samfile.getrname(tid) == chrom name #new_alignment.pos = old_alignment.pos # 4th column. reference Start position of the aligned part (of read) [0-based] #new_alignment.mapq = old_alignment.mapq # 5th column. mapping quality #new_alignment.cigar= old_alignment.cigar # 6th column. subject to change. #new_alignment.rnext = old_alignment.rnext # 7th column. tid of the reference (mate read mapped to) #new_alignment.pnext = old_alignment.pnext # 8th column. position of the reference (0 based, mate read mapped to) #new_alignment.tlen = old_alignment.tlen # 9th column. insert size #new_alignment.seq = old_alignment.seq # 10th column. read sequence. all bases. #new_alignment.qual = old_alignment.qual # 11th column. read sequence quality. all bases. #new_alignment.tags = old_alignment.tags # 12 - columns new_alignment.qname = old_alignment.qname # 1st column. read name. new_alignment.seq = old_alignment.seq # 10th column. read sequence. all bases. new_alignment.qual = old_alignment.qual # 11th column. read sequence quality. all bases. new_alignment.tags = old_alignment.tags # 12 - columns # by default pysam will change RG:Z to RG:A, which can cause downstream failures with GATK and freebayes # Thanks Wolfgang Resch <wresch@helix.nih.gov> identified this bug and provided solution. try: rg, rgt = old_alignment.get_tag("RG", with_value_type=True) except KeyError: pass else: new_alignment.set_tag("RG", str(rg), rgt) if old_alignment.is_paired: new_alignment.flag = 0x0001 #pair-end if old_alignment.is_read1: new_alignment.flag = new_alignment.flag | 0x40 elif old_alignment.is_read2: new_alignment.flag = new_alignment.flag | 0x80 #================================== # R1 is originally unmapped #================================== if old_alignment.is_unmapped: #This line will set the unmapped read flag for the first read in pair (in case it is unmapped). #Thanks Amir Keivan Mohtashami reporting this bug. new_alignment.flag = new_alignment.flag | 0x4 #------------------------------------ # both R1 and R2 unmapped #------------------------------------ if old_alignment.mate_is_unmapped: NN += 1 if addtag: old_alignment.set_tag(tag="NN", value=0) OUT_FILE.write(old_alignment) continue else: # originally, read-1 unmapped, read-2 is mapped try: read2_chr = samfile.getrname(old_alignment.rnext) read2_strand = '-' if old_alignment.mate_is_reverse else '+' read2_start = old_alignment.pnext read2_end = read2_start + 1 read2_maps = map_coordinates(mapping, read2_chr, read2_start, read2_end, read2_strand) # [('chr1', 246974830, 246974833, '+' ), ('chr1', 248908207, 248908210, '+' )] except: read2_maps = None #------------------------------------ # both R1 and R2 unmapped #------------------------------------ if read2_maps is None: NN += 1 if addtag: old_alignment.set_tag(tag="NN", value=0) OUT_FILE.write(old_alignment) continue #------------------------------------ # R1 unmapped, R2 unique #------------------------------------ elif len(read2_maps) == 2: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 3 new_alignment.tid = name_to_id[read2_maps[1][0]] #recommend to set the RNAME of unmapped read to its mate's # 4 new_alignment.pos = read2_maps[1][1] #recommend to set the POS of unmapped read to its mate's # 5 new_alignment.mapq = old_alignment.mapq # 6 new_alignment.cigar = old_alignment.cigar # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = 0 NU += 1 if addtag: new_alignment.set_tag(tag="NU", value=0) OUT_FILE.write(new_alignment) continue #------------------------------------ # R1 unmapped, R2 multiple #------------------------------------ else: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 2 new_alignment.flag = new_alignment.flag | 0x100 # 3 new_alignment.tid = name_to_id[read2_maps[1][0]] # 4 new_alignment.pos = read2_maps[1][1] # 5 new_alignment.mapq = old_alignment.mapq # 6 new_alignment.cigar = old_alignment.cigar # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = 0 NM += 1 if addtag: new_alignment.set_tag(tag="NM", value=0) OUT_FILE.write(new_alignment) continue #================================== # R1 is originally mapped #================================== else: try: read1_chr = samfile.getrname(old_alignment.tid) read1_strand = '-' if old_alignment.is_reverse else '+' read1_start = old_alignment.pos read1_end = old_alignment.aend read1_maps = map_coordinates(mapping, read1_chr, read1_start, read1_end, read1_strand) except: read1_maps = None if not old_alignment.mate_is_unmapped: try: read2_chr = samfile.getrname(old_alignment.rnext) read2_strand = '-' if old_alignment.mate_is_reverse else '+' read2_start = old_alignment.pnext read2_end = read2_start + 1 read2_maps = map_coordinates(mapping, read2_chr, read2_start, read2_end, read2_strand) # [('chr1', 246974830, 246974833, '+' ), ('chr1', 248908207, 248908210, '+' )] except: read2_maps = None #------------------------------------ # R1 unmapped (failed to liftover) #------------------------------------ if read1_maps is None: # 2 update flag (0x4: segment unmapped) new_alignment.flag = new_alignment.flag | 0x4 # 3 new_alignment.tid = -1 # 4 new_alignment.pos = 0 # 5 new_alignment.mapq = 255 # 6 new_alignment.cigar = old_alignment.cigar # 7 new_alignment.rnext = -1 # 8 new_alignment.pnext = 0 # 9 new_alignment.tlen = 0 # (1) read2 is unmapped before conversion if old_alignment.mate_is_unmapped: NN += 1 if addtag: new_alignment.set_tag(tag="NN", value=0) OUT_FILE.write(new_alignment) continue # (2) read2 is unmapped after conversion elif read2_maps is None: # 2 new_alignment.flag = new_alignment.flag | 0x8 NN += 1 if addtag: new_alignment.set_tag(tag="NN", value=0) OUT_FILE.write(new_alignment) continue # (3) read2 is unique mapped elif len(read2_maps) == 2: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 3 new_alignment.tid = name_to_id[read2_maps[1][0]] #recommend to set the RNAME of unmapped read to its mate's # 4 new_alignment.pos = read2_maps[1][1] #recommend to set the POS of unmapped read to its mate's # 5 new_alignment.mapq = old_alignment.mapq # 6 new_alignment.cigar = old_alignment.cigar # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = 0 NU += 1 if addtag: new_alignment.set_tag(tag="NU", value=0) OUT_FILE.write(new_alignment) continue # (4) read2 is multiple mapped else: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 2 new_alignment.flag = new_alignment.flag | 0x100 # 3 new_alignment.tid = name_to_id[read2_maps[1][0]] # 4 new_alignment.pos = read2_maps[1][1] # 5 new_alignment.mapq = 255 # mapq not available # 6 new_alignment.cigar = old_alignment.cigar # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = 0 NM += 1 if addtag:new_alignment.set_tag(tag="NM", value=0) OUT_FILE.write(new_alignment) continue #------------------------------------ # R1 uniquely mapped #------------------------------------ elif len(read1_maps) == 2: if read1_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x10 if read1_maps[0][3] != read1_maps[1][3]: # opposite strand # 6 new_alignment.cigar = old_alignment.cigar[::-1] #reverse cigar tuple # 10 new_alignment.seq = revcomp_DNA(old_alignment.seq) #reverse complement read sequence # 11 new_alignment.qual = old_alignment.qual[::-1] #reverse quality string elif read1_maps[0][3] == read1_maps[1][3]: # same strand # 6 new_alignment.cigar = old_alignment.cigar # 3 new_alignment.tid = name_to_id[read1_maps[1][0]] #chrom # 4 new_alignment.pos = read1_maps[1][1] #start # 5 new_alignment.mapq = old_alignment.mapq # (1) R2 unmapped before or after conversion if (old_alignment.mate_is_unmapped) or (read2_maps is None): # 2 new_alignment.flag = new_alignment.flag | 0x8 # 7 new_alignment.rnext = name_to_id[read1_maps[1][0]] # 8 new_alignment.pnext = read1_maps[1][1] # 9 new_alignment.tlen = 0 UN += 1 if addtag: new_alignment.set_tag(tag="UN", value=0) OUT_FILE.write(new_alignment) continue # (2) R2 is unique mapped elif len(read2_maps)==2: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] #chrom # 8 new_alignment.pnext = read2_maps[1][1] # 9 new_alignment.tlen = abs(new_alignment.pos - new_alignment.pnext) -1 - old_alignment.alen # 2 if (read2_maps[1][3] != read1_maps[1][3]) and (new_alignment.tlen <= IS_size + fold * IS_std) and (new_alignment.tlen >= IS_size - fold * IS_std): new_alignment.flag = new_alignment.flag | 0x2 UU += 1 if addtag: new_alignment.set_tag(tag="UU", value=0) OUT_FILE.write(new_alignment) continue # (3) R2 is multiple mapped else: # 2 (strand) if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 2 (secondary alignment) new_alignment.flag = new_alignment.flag | 0x100 # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] #chrom # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = abs(new_alignment.pos - new_alignment.pnext) -1 - old_alignment.alen UM += 1 if addtag: new_alignment.set_tag(tag="UM", value=0) OUT_FILE.write(new_alignment) continue #------------------------------------ # R1 multiple mapped #----------------------------------- elif len(read1_maps) > 2 and len(read1_maps) % 2 ==0: # 2 new_alignment.flag = new_alignment.flag | 0x100 # 2 if read1_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x10 if read1_maps[0][3] != read1_maps[1][3]: # 6 new_alignment.cigar = old_alignment.cigar[::-1] #reverse cigar tuple # 10 new_alignment.seq = revcomp_DNA(old_alignment.seq) #reverse complement read sequence # 11 new_alignment.qual = old_alignment.qual[::-1] #reverse quality string elif read1_maps[0][3] == read1_maps[1][3]: new_alignment.cigar = old_alignment.cigar # 3 new_alignment.tid = name_to_id[read1_maps[1][0]] #chrom # 4 new_alignment.pos = read1_maps[1][1] #start # 5 new_alignment.mapq = 255 # (1) R2 is unmapped if (old_alignment.mate_is_unmapped) or (read2_maps is None): # 2 new_alignment.flag = new_alignment.flag | 0x8 # 7 new_alignment.rnext = name_to_id[read1_maps[1][0]] # 8 new_alignment.pnext = read1_maps[1][1] # 9 new_alignment.tlen = 0 MN += 1 if addtag: new_alignment.set_tag(tag="MN", value=0) OUT_FILE.write(new_alignment) continue # (2) read2 is unique mapped elif len(read2_maps)==2: # 2 if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] #chrom # 8 new_alignment.pnext = read2_maps[1][1] # 9 new_alignment.tlen = abs(new_alignment.pos - new_alignment.pnext) -1 - old_alignment.alen MU += 1 if addtag: new_alignment.set_tag(tag="MU", value=0) OUT_FILE.write(new_alignment) continue # (3) R2 is multiple mapped else: # 2 (strand) if read2_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x20 # 2 (secondary alignment) new_alignment.flag = new_alignment.flag | 0x100 # 7 new_alignment.rnext = name_to_id[read2_maps[1][0]] #chrom # 8 new_alignment.pnext = read2_maps[1][1] #start # 9 new_alignment.tlen = abs(new_alignment.pos - new_alignment.pnext) -1 - old_alignment.alen MM += 1 if addtag: new_alignment.set_tag(tag="MM", value=0) OUT_FILE.write(new_alignment) continue else: #old_alignment.tid = name_to_id[samfile.getrname(old_alignment.tid)] OUT_FILE_UNMAP.write(old_alignment) failed += 1 # Singel end sequencing else: # (1) originally unmapped if old_alignment.is_unmapped: SN += 1 if addtag: old_alignment.set_tag(tag="SN",value=0) OUT_FILE.write(old_alignment) continue else: new_alignment.flag = 0x0 read_chr = samfile.getrname(old_alignment.tid) read_strand = '-' if old_alignment.is_reverse else '+' read_start = old_alignment.pos read_end = old_alignment.aend read_maps = map_coordinates(mapping, read_chr, read_start, read_end, read_strand) # (2) unmapped afte liftover if read_maps is None: # 1 new_alignment.qname = old_alignment.qname # 2 new_alignment.flag = new_alignment.flag | 0x4 # 3 new_alignment.tid = -1 # 4 new_alignment.pos = 0 # 5 new_alignment.mapq = 255 # 6 new_alignment.cigar= old_alignment.cigar # 7 new_alignment.rnext = -1 # 8 new_alignment.pnext = 0 # 9 new_alignment.tlen = 0 # 10 new_alignment.seq = old_alignment.seq # 11 new_alignment.qual = old_alignment.qual # 12 new_alignment.tags = old_alignment.tags SN += 1 if addtag: new_alignment.set_tag(tag="SN",value=0) OUT_FILE.write(new_alignment) continue # (3) unique mapped if len(read_maps)==2: # 1 new_alignment.qname = old_alignment.qname # 2 if read_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x10 if read_maps[0][3] != read_maps[1][3]: # 6 new_alignment.cigar = old_alignment.cigar[::-1] #reverse cigar tuple # 10 new_alignment.seq = revcomp_DNA(old_alignment.seq) #reverse complement read sequence # 11 new_alignment.qual = old_alignment.qual[::-1] #reverse quality string else: # 6 new_alignment.cigar = old_alignment.cigar # 10 new_alignment.seq = old_alignment.seq # 11 new_alignment.qual = old_alignment.qual # 3 new_alignment.tid = name_to_id[read_maps[1][0]] # 4 new_alignment.pos = read_maps[1][1] # 5 new_alignment.mapq = old_alignment.mapq # 7 new_alignment.rnext = -1 # 8 new_alignment.pnext = 0 # 9 new_alignment.tlen = 0 SU += 1 if addtag: new_alignment.set_tag(tag="SU",value=0) OUT_FILE.write(new_alignment) continue # (4) multiple mapped if len(read_maps) > 2 and len(read_maps) % 2 ==0: # 1 new_alignment.qname = old_alignment.qname new_alignment.flag = new_alignment.flag | 0x100 # 2 if read_maps[1][3] == '-': new_alignment.flag = new_alignment.flag | 0x10 if read_maps[0][3] != read_maps[1][3]: # 6 new_alignment.cigar = old_alignment.cigar[::-1] #reverse cigar tuple # 10 new_alignment.seq = revcomp_DNA(old_alignment.seq) #reverse complement read sequence # 11 new_alignment.qual = old_alignment.qual[::-1] #reverse quality string else: # 6 new_alignment.cigar = old_alignment.cigar # 10 new_alignment.seq = old_alignment.seq # 11 new_alignment.qual = old_alignment.qual # 3 new_alignment.tid = name_to_id[read_maps[1][0]] # 4 new_alignment.pos = read_maps[1][1] # 5 new_alignment.mapq = old_alignment.mapq # 7 new_alignment.rnext = -1 # 8 new_alignment.pnext = 0 # 9 new_alignment.tlen = 0 SM += 1 if addtag: new_alignment.set_tag(tag="SM",value=0) OUT_FILE.write(new_alignment) continue except StopIteration: printlog(["Done!"]) OUT_FILE.close() if outfile_prefix is not None: if bam_format: try: printlog (['Sort "%s" and save as "%s"' % (outfile_prefix + '.bam', outfile_prefix + '.sorted.bam')]) pysam.sort("-o", outfile_prefix + '.sorted.bam', outfile_prefix + '.bam') except: printlog(["Warning: ","output BAM file was NOT sorted"]) try: printlog (['Index "%s" ...' % (outfile_prefix + '.sorted.bam')]) pysam.index(outfile_prefix + '.sorted.bam',outfile_prefix + '.sorted.bam.bai') except: printlog(["Warning: ","output BAM file was NOT indexed."]) print("Total alignments:" + str(total_item-1)) print("\tQC failed: " + str(QF)) if max(NN,NU, NM, UN, UU, UM, MN, MU, MM) > 0: print("\tR1 unique, R2 unique (UU): " + str(UU)) print("\tR1 unique, R2 unmapp (UN): " + str(UN)) print("\tR1 unique, R2 multiple (UM): " + str(UM)) print("\tR1 multiple, R2 multiple (MM): " + str(MM)) print("\tR1 multiple, R2 unique (MU): " + str(MU)) print("\tR1 multiple, R2 unmapped (MN): " + str(MN)) print("\tR1 unmap, R2 unmap (NN): " + str(NN)) print("\tR1 unmap, R2 unique (NU): " + str(NU)) print("\tR1 unmap, R2 multiple (NM): " + str(NM)) if max(SN,SU,SM) > 0: print("\tUniquley mapped (SU): " + str(SU)) print("\tMultiple mapped (SM): " + str(SM)) print("\tUnmapped (SN): " + str(SN)) def crossmap_wig_file(mapping, in_file, out_prefix, taget_chrom_size, in_format, binSize=100000): ''' Convert genome coordinates (in wiggle/bigwig format) between assemblies. wiggle format: http://genome.ucsc.edu/goldenPath/help/wiggle.html bigwig format: http://genome.ucsc.edu/goldenPath/help/bigWig.html ''' OUT_FILE1 = open(out_prefix + '.bgr','w') # original bgr file OUT_FILE2 = open(out_prefix + '.sorted.bgr','w') # sorted bgr file OUT_FILE3 = pyBigWig.open(out_prefix + '.bw', "w") # bigwig file if in_format.upper() == "WIGGLE": printlog (["Liftover wiggle file:", in_file, '==>', out_prefix + '.bgr']) for chr, start, end, strand, score in wiggleReader (in_file): #print chr,start,end,score # map_coordinates(mapping, q_chr, q_start, q_end, q_strand = '+', print_match=False): maps = map_coordinates(mapping, chr, start, end, '+') if maps is None: continue if len(maps) == 2: print('\t'.join([str(i) for i in [maps[1][0],maps[1][1],maps[1][2], score]]), file=OUT_FILE1) else: continue maps[:]=[] OUT_FILE1.close() printlog (["Merging overlapped entries in bedGraph file ..."]) for (chr, start, end, score) in bgrMerge.merge(out_prefix + '.bgr'): print('\t'.join([str(i) for i in (chr, start, end, score )]), file=OUT_FILE2) OUT_FILE2.close() os.remove(out_prefix + '.bgr') #remove .bgr, keep .sorted.bgr # add header to bigwig file printlog (["Writing header to \"%s\" ..." % (out_prefix + '.bw') ]) target_chroms_sorted = [(k,taget_chrom_size[k]) for k in sorted(taget_chrom_size.keys())] OUT_FILE3.addHeader(target_chroms_sorted) printlog (["Writing entries to \"%s\" ..." % (out_prefix + '.bw') ]) # add entries to bigwig file for line in ireader.reader(out_prefix + '.sorted.bgr'): r_chr,r_st,r_end,r_value = line.split() OUT_FILE3.addEntries([r_chr], [int(r_st)], ends=[int(r_end)], values=[float(r_value)]) OUT_FILE3.close() elif in_format.upper() == "BIGWIG": printlog (["Liftover bigwig file:", in_file, '==>', out_prefix + '.bgr']) for chr, start, end, score in bigwigReader(in_file, bin_size = binSize ): maps = map_coordinates(mapping, chr, start, end, '+') try: if maps is None: continue if len(maps) == 2: print('\t'.join([str(i) for i in [maps[1][0],maps[1][1],maps[1][2], score]]), file=OUT_FILE1) else: continue except: continue maps[:]=[] OUT_FILE1.close() printlog (["Merging overlapped entries in bedGraph file ..."]) for (chr, start, end, score) in bgrMerge.merge(out_prefix + '.bgr'): print('\t'.join([str(i) for i in (chr, start, end, score )]), file=OUT_FILE2) OUT_FILE2.close() os.remove(out_prefix + '.bgr') #remove .bgr, keep .sorted.bgr # add header to bigwig file printlog (["Writing header to \"%s\" ..." % (out_prefix + '.bw') ]) target_chroms_sorted = [(k,taget_chrom_size[k]) for k in sorted(taget_chrom_size.keys())] OUT_FILE3.addHeader(target_chroms_sorted) # add entries to bigwig file printlog (["Writing entries to \"%s\" ..." % (out_prefix + '.bw') ]) for line in ireader.reader(out_prefix + '.sorted.bgr'): r_chr,r_st,r_end,r_value = line.split() OUT_FILE3.addEntries([r_chr], [int(r_st)], ends=[int(r_end)], values=[float(r_value)]) OUT_FILE3.close() else: raise Exception("Unknown foramt. Must be 'wiggle' or 'bigwig'") def general_help(): desc="""CrossMap is a program for convenient conversion of genome coordinates and genome \ annotation files between assemblies (eg. lift from human hg18 to hg19 or vice versa). \ It supports file in BAM, SAM, BED, Wiggle, BigWig, GFF, GTF and VCF format.""" print("Program: %s (v%s)" % ("CrossMap", __version__), file=sys.stderr) print("\nDescription: \n%s" % '\n'.join(' '+i for i in wrap(desc,width=80)), file=sys.stderr) print("\nUsage: CrossMap.py <command> [options]\n", file=sys.stderr) for k in sorted(commands): print(' ' + k + '\t' + commands[k], file=sys.stderr) print(file=sys.stderr) def bed_help(): msg =[ ('Usage:', "CrossMap.py bed input_chain_file input_bed_file [output_file]"), ('Description:', "\"input_chain_file\" and \"input_bed_file\" can be regular or compressed (*.gz, *.Z, *.z, *.bz, *.bz2, *.bzip2) file, local file or URL (http://, https://, ftp://) pointing to remote file. BED format file must have at least 3 columns (chrom, start, end) and no more than 12 columns. If no \"output_file\" is specified, output will be directed to the screen (console). BED format: http://genome.ucsc.edu/FAQ/FAQformat.html#format1"), ('Example:', "CrossMapy.py bed hg18ToHg19.over.chain.gz test.hg18.bed test.hg19.bed # write output to \"test.hg19.bed\""), ('Example:', "CrossMapy.py bed hg18ToHg19.over.chain.gz test.hg18.bed # write output to screen"), ] for i,j in msg: print('\n' + i + '\n' + '\n'.join([' ' + k for k in wrap(j,width=80)]), file=sys.stderr) def gff_help(): msg =[ ('Usage:', "CrossMap.py gff input_chain_file input_gff_file output_file"), ('Description:', "\"input_chain_file\" can be regular or compressed (*.gz, *.Z, *.z, *.bz, *.bz2, *.bzip2) file, local file or URL (http://, https://, ftp://) pointing to remote file. Input file must be in GFF or GTF format. GFF format: http://genome.ucsc.edu/FAQ/FAQformat.html#format3 GTF format: http://genome.ucsc.edu/FAQ/FAQformat.html#format4"), ('Example:', "CrossMap.py gff hg19ToHg18.over.chain.gz test.hg19.gtf test.hg18.gtf # write output to \"test.hg18.gff\""), ('Example:', "CrossMap.py gff hg19ToHg18.over.chain.gz test.hg19.gtf # write output to screen"), ] for i,j in msg: print('\n' + i + '\n' + '\n'.join([' ' + k for k in wrap(j,width=80)]), file=sys.stderr) def wig_help(): msg =[ ('Usage:', "CrossMap.py wig input_chain_file input_wig_file output_prefix"), ('Description:', "\"input_chain_file\" can be regular or compressed (*.gz, *.Z, *.z, *.bz, *.bz2, *.bzip2) file, local file or URL (http://, https://, ftp://) pointing to remote file. Both \"variableStep\" and \"fixedStep\" wiggle lines are supported. Wiggle format: http://genome.ucsc.edu/goldenPath/help/wiggle.html"), ('Example:', "CrossMapy.py wig hg18ToHg19.over.chain.gz test.hg18.wig test.hg19"), ] for i,j in msg: print('\n' + i + '\n' + '\n'.join([' ' + k for k in wrap(j,width=80)]), file=sys.stderr) def bigwig_help(): msg =[ ('Usage:', "CrossMap.py bigwig input_chain_file input__bigwig_file output_prefix"), ('Description:', "\"input_chain_file\" can be regular or compressed (*.gz, *.Z, *.z, *.bz, *.bz2, *.bzip2) file, local file or URL (http://, https://, ftp://) pointing to remote file. Bigwig format: http://genome.ucsc.edu/goldenPath/help/bigWig.html"), ('Example:', "CrossMapy.py bigwig hg18ToHg19.over.chain.gz test.hg18.bw test.hg19"), ] for i,j in msg: print('\n' + i + '\n' + '\n'.join([' ' + k for k in wrap(j,width=80)]), file=sys.stderr) def bam_help(): usage="CrossMap.py bam -a input_chain_file input_bam_file output_file [options] " import optparse parser.print_help() def vcf_help(): msg =[ ("usage:","CrossMap.py vcf input_chain_file input_VCF_file ref_genome_file output_file"), ("Description:", "\"input_chain_file\" and \"input_VCF_file\" can be regular or compressed (*.gz, *.Z, *.z, *.bz, *.bz2, *.bzip2) file, local file or URL (http://, https://, ftp://) pointing to remote file. \"ref_genome_file\" is genome sequence file of 'target assembly' in FASTA format."), ("Example:", " CrossMap.py vcf hg19ToHg18.over.chain.gz test.hg19.vcf hg18.fa test.hg18.vcf"), ] for i,j in msg: print('\n' + i + '\n' + '\n'.join([' ' + k for k in wrap(j,width=80)]), file=sys.stderr) if __name__=='__main__': # test read_chain_file() #(mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(sys.argv[1], print_table=True) #q_chr, q_start, q_end, q_strand = '+', print_match=False): #map_coordinates(mapTree, 'chr1', 45953452, 45953456, '+', print_match=True) #a= sam_header.bam_header_generator(chrom_size = targetChromSizes, prog_name="CrossMap",prog_ver = __version__, format_ver=1.0,sort_type = 'coordinate',co=['a','b','c']) #crossmap_bed_file(mapTree, 'test.hg18.bed3',outfile='aa') #crossmap_bed_file(mapTree, 'test.bed') #crossmap_gff_file(mapTree,'test.hg18.gtf',outfile = 'aa') #crossmap_bam_file(mapTree, targetChromSizes, sys.argv[1], 'eg.abnormal.sam','out') #printlog (['Sort output bam file ...']) #pysam.sort('-m','1000000000','out.bam','out.sorted') #printlog (['Index bam file ...']) #pysam.index('out.sorted.bam','out.sorted.bam.bai') #crossmap_wig_file(mapTree, 'GSM686950_reverse.hg18.bw', 'GSM686950_reverse.hg19', sourceChromSizes, targetChromSizes, in_format = 'bigwig') #parser = optparse.OptionParser() #parser.add_option("-i","--input-sam",action="store",type="string",dest="input_sam_file", help="BAM/SAM format file.") #parser.add_option("-o","--out-file",action="store",type="string",dest="output_sam_file", help="Prefix of output files. Foramt is determined from input: SAM <=> SAM, BAM <=> BAM") #parser.add_option("-m","--insert-mean",action="store",type="float",dest="insert_size", default=200.0, help="Average insert size of pair-end sequencing (bp). Used to tell wheather a mapped pair is \"proper pair\" or not. [default=%default]") #parser.add_option("-s","--insert-stdev",action="store",type="float",dest="insert_size_stdev", default=30.0, help="Stanadard deviation of insert size. [default=%default]" ) #parser.add_option("-t","--times-of-stdev",action="store",type="float",dest="insert_size_fold", default=3.0, help="A mapped pair is considered as \"proper pair\" if both ends mapped to different strand and the distance between them is less then '-t' * stdev from the mean. [default=%default]") #(options,args)=parser.parse_args() #print options #print args commands = { 'bed':'convert genome cooridnate or annotation file in BED, bedGraph or other BED-like format.', 'bam':'convert alignment file in BAM or SAM format.', 'gff':'convert genome cooridnate or annotation file in GFF or GTF format.', 'wig':'convert genome coordinate file in Wiggle, or bedGraph format.', 'bigwig':'convert genome coordinate file in BigWig format.', 'vcf':'convert genome coordinate file in VCF format.' } kwds = list(commands.keys()) if len(sys.argv) == 1: general_help() sys.exit(0) elif len(sys.argv) >=2: # deal with bed input if sys.argv[1].lower() == 'bed': if len(sys.argv) == 4: chain_file = sys.argv[2] in_file = sys.argv[3] out_file = None (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file, print_table = False) crossmap_bed_file(mapTree, in_file, out_file) elif len(sys.argv) == 5: chain_file = sys.argv[2] in_file = sys.argv[3] out_file = sys.argv[4] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_bed_file(mapTree, in_file, out_file) else: bed_help() sys.exit(0) elif sys.argv[1].lower() == 'gff': if len(sys.argv) == 4: chain_file = sys.argv[2] in_file = sys.argv[3] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_gff_file(mapTree, in_file, None) elif len(sys.argv) == 5: chain_file = sys.argv[2] in_file = sys.argv[3] out_file = sys.argv[4] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_gff_file(mapTree, in_file, out_file) else: gff_help() sys.exit(0) elif sys.argv[1].lower() == 'wig': if len(sys.argv) == 5: chain_file = sys.argv[2] in_file = sys.argv[3] out_file = sys.argv[4] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_wig_file(mapTree, in_file, out_file, targetChromSizes, in_format = 'wiggle') else: wig_help() sys.exit(0) elif sys.argv[1].lower() == 'bigwig': if len(sys.argv) == 5: chain_file = sys.argv[2] in_file = sys.argv[3] try: bw = pyBigWig.open(in_file) except: print ("\nPlease check if \"%s\" is in bigWig format!\n" % in_file, file=sys.stderr) sys.exit(0) out_file = sys.argv[4] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_wig_file(mapTree, in_file, out_file, targetChromSizes, in_format = 'bigwig') else: bigwig_help() sys.exit(0) elif sys.argv[1].lower() == 'bam': #def crossmap_bam_file(mapping, chainfile, infile, outfile_prefix, chrom_size, IS_size=200, IS_std=30, fold=3): usage="CrossMap.py bam input_chain_file input_bam_file output_file [options]\nNote: If output_file == STDOUT or -, CrossMap will write BAM file to the screen" parser = optparse.OptionParser(usage, add_help_option=False) parser.add_option("-m", "--mean", action="store",type="float",dest="insert_size", default=200.0, help="Average insert size of pair-end sequencing (bp). [default=%default]") parser.add_option("-s", "--stdev", action="store",type="float",dest="insert_size_stdev", default=30.0, help="Stanadard deviation of insert size. [default=%default]" ) parser.add_option("-t", "--times", action="store",type="float",dest="insert_size_fold", default=3.0, help="A mapped pair is considered as \"proper pair\" if both ends mapped to different strand and the distance between them is less then '-t' * stdev from the mean. [default=%default]") parser.add_option("-a","--append-tags",action="store_true",dest="add_tags",help="Add tag to each alignment.") (options,args)=parser.parse_args() if len(args) >= 3: print("Insert size = %f" % (options.insert_size), file=sys.stderr) print("Insert size stdev = %f" % (options.insert_size_stdev), file=sys.stderr) print("Number of stdev from the mean = %f" % (options.insert_size_fold), file=sys.stderr) if options.add_tags: print("Add tags to each alignment = %s" % ( options.add_tags), file=sys.stderr) else: print("Add tags to each alignment = %s" % ( False), file=sys.stderr) chain_file = args[1] in_file = args[2] out_file = args[3] if len(args) >= 4 else None (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) if out_file in ["STDOUT","-"]: out_file = None if options.add_tags: crossmap_bam_file(mapping = mapTree, chainfile = chain_file, infile = in_file, outfile_prefix = out_file, chrom_size = targetChromSizes, IS_size=options.insert_size, IS_std=options.insert_size_stdev, fold=options.insert_size_fold,addtag=True) else: crossmap_bam_file(mapping = mapTree, chainfile = chain_file, infile = in_file, outfile_prefix = out_file, chrom_size = targetChromSizes, IS_size=options.insert_size, IS_std=options.insert_size_stdev, fold=options.insert_size_fold,addtag=False) else: parser.print_help() elif sys.argv[1].lower() == 'vcf': if len(sys.argv) == 6: chain_file = sys.argv[2] in_file = sys.argv[3] genome_file = sys.argv[4] out_file = sys.argv[5] (mapTree,targetChromSizes, sourceChromSizes) = read_chain_file(chain_file) crossmap_vcf_file(mapping = mapTree, infile= in_file, outfile = out_file, liftoverfile = sys.argv[2], refgenome = genome_file) else: vcf_help() sys.exit(0) else: general_help() sys.exit(0)
ivanamihalek/progesterone
utils/CrossMap.py
Python
gpl-2.0
82,502
[ "pysam" ]
3b379eaaf8a81639a5b4802d465090c7fe6cdbe94086d92c0889aba1e0e36f0d
""" Tests for discussion pages """ import datetime from uuid import uuid4 from nose.plugins.attrib import attr from pytz import UTC from flaky import flaky from common.test.acceptance.tests.discussion.helpers import BaseDiscussionTestCase from common.test.acceptance.tests.helpers import UniqueCourseTest from common.test.acceptance.pages.lms.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.courseware import CoursewarePage from common.test.acceptance.pages.lms.discussion import ( DiscussionTabSingleThreadPage, InlineDiscussionPage, InlineDiscussionThreadPage, DiscussionUserProfilePage, DiscussionTabHomePage, DiscussionSortPreferencePage, ) from common.test.acceptance.pages.lms.learner_profile import LearnerProfilePage from common.test.acceptance.pages.lms.tab_nav import TabNavPage from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from common.test.acceptance.fixtures.discussion import ( SingleThreadViewFixture, UserProfileViewFixture, SearchResultFixture, Thread, Response, Comment, SearchResult, MultipleThreadFixture) from common.test.acceptance.tests.discussion.helpers import BaseDiscussionMixin from common.test.acceptance.tests.helpers import skip_if_browser THREAD_CONTENT_WITH_LATEX = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n----------\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. (b).\n\n **(a)** $H_1(e^{j\\omega}) = \\sum_{n=-\\infty}^{\\infty}h_1[n]e^{-j\\omega n} = \\sum_{n=-\\infty} ^{\\infty}h[n]e^{-j\\omega n}+\\delta_2e^{-j\\omega n_0}$ $= H(e^{j\\omega})+\\delta_2e^{-j\\omega n_0}=A_e (e^{j\\omega}) e^{-j\\omega n_0} +\\delta_2e^{-j\\omega n_0}=e^{-j\\omega n_0} (A_e(e^{j\\omega})+\\delta_2) $H_3(e^{j\\omega})=A_e(e^{j\\omega})+\\delta_2$. Dummy $A_e(e^{j\\omega})$ dummy post $. $A_e(e^{j\\omega}) \\ge -\\delta_2$, it follows that $H_3(e^{j\\omega})$ is real and $H_3(e^{j\\omega})\\ge 0$.\n\n**(b)** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur.\n\n **Case 1:** If $re^{j\\theta}$ is a Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. \n\n**Case 3:** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem $H_3(e^{j\\omega}) = P(cos\\omega)(cos\\omega - cos\\theta)^k$, Lorem Lorem Lorem Lorem Lorem Lorem $P(cos\\omega)$ has no $(cos\\omega - cos\\theta)$ factor. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. $P(cos\\theta) \\neq 0$. Since $P(cos\\omega)$ this is a dummy data post $\\omega$, dummy $\\delta > 0$ such that for all $\\omega$ dummy $|\\omega - \\theta| < \\delta$, $P(cos\\omega)$ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit sse cillum dolore eu fugiat nulla pariatur. """ class DiscussionResponsePaginationTestMixin(BaseDiscussionMixin): """ A mixin containing tests for response pagination for use by both inline discussion and the discussion tab """ def assert_response_display_correct(self, response_total, displayed_responses): """ Assert that various aspects of the display of responses are all correct: * Text indicating total number of responses * Presence of "Add a response" button * Number of responses actually displayed * Presence and text of indicator of how many responses are shown * Presence and text of button to load more responses """ self.assertEqual( self.thread_page.get_response_total_text(), str(response_total) + " responses" ) self.assertEqual(self.thread_page.has_add_response_button(), response_total != 0) self.assertEqual(self.thread_page.get_num_displayed_responses(), displayed_responses) self.assertEqual( self.thread_page.get_shown_responses_text(), ( None if response_total == 0 else "Showing all responses" if response_total == displayed_responses else "Showing first {} responses".format(displayed_responses) ) ) self.assertEqual( self.thread_page.get_load_responses_button_text(), ( None if response_total == displayed_responses else "Load all responses" if response_total - displayed_responses < 100 else "Load next 100 responses" ) ) def test_pagination_no_responses(self): self.setup_thread(0) self.assert_response_display_correct(0, 0) def test_pagination_few_responses(self): self.setup_thread(5) self.assert_response_display_correct(5, 5) def test_pagination_two_response_pages(self): self.setup_thread(50) self.assert_response_display_correct(50, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(50, 50) def test_pagination_exactly_two_response_pages(self): self.setup_thread(125) self.assert_response_display_correct(125, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(125, 125) def test_pagination_three_response_pages(self): self.setup_thread(150) self.assert_response_display_correct(150, 25) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 125) self.thread_page.load_more_responses() self.assert_response_display_correct(150, 150) def test_add_response_button(self): self.setup_thread(5) self.assertTrue(self.thread_page.has_add_response_button()) self.thread_page.click_add_response_button() def test_add_response_button_closed_thread(self): self.setup_thread(5, closed=True) self.assertFalse(self.thread_page.has_add_response_button()) @attr(shard=2) class DiscussionHomePageTest(BaseDiscussionTestCase): """ Tests for the discussion home page. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionHomePageTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() @attr(shard=2) def test_new_post_button(self): """ Scenario: I can create new posts from the Discussion home page. Given that I am on the Discussion home page When I click on the 'New Post' button Then I should be shown the new post form """ self.assertIsNotNone(self.page.new_post_button) self.page.click_new_post_button() self.assertIsNotNone(self.page.new_post_form) @attr('a11y') def test_page_accessibility(self): self.page.a11y_audit.config.set_rules({ "ignore": [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) self.page.a11y_audit.check_for_accessibility_errors() @attr(shard=2) class DiscussionNavigationTest(BaseDiscussionTestCase): """ Tests for breadcrumbs navigation in the Discussions page nav bar """ def setUp(self): super(DiscussionNavigationTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() thread_id = "test_thread_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread( id=thread_id, body=THREAD_CONTENT_WITH_LATEX, commentable_id=self.discussion_id ) ) thread_fixture.push() self.thread_page = DiscussionTabSingleThreadPage( self.browser, self.course_id, self.discussion_id, thread_id ) self.thread_page.visit() def test_breadcrumbs_push_topic(self): topic_button = self.thread_page.q( css=".forum-nav-browse-menu-item[data-discussion-id='{}']".format(self.discussion_id) ) self.assertTrue(topic_button.visible) topic_button.click() # Verify the thread's topic has been pushed to breadcrumbs breadcrumbs = self.thread_page.q(css=".breadcrumbs .nav-item") self.assertEqual(len(breadcrumbs), 2) self.assertEqual(breadcrumbs[1].text, "Test Discussion Topic") def test_breadcrumbs_back_to_all_topics(self): topic_button = self.thread_page.q( css=".forum-nav-browse-menu-item[data-discussion-id='{}']".format(self.discussion_id) ) self.assertTrue(topic_button.visible) topic_button.click() # Verify clicking the first breadcrumb takes you back to all topics self.thread_page.q(css=".breadcrumbs .nav-item")[0].click() self.assertEqual(len(self.thread_page.q(css=".breadcrumbs .nav-item")), 1) def test_breadcrumbs_clear_search(self): self.thread_page.q(css=".search-input").fill("search text") self.thread_page.q(css=".search-btn").click() # Verify that clicking the first breadcrumb clears your search self.thread_page.q(css=".breadcrumbs .nav-item")[0].click() self.assertEqual(self.thread_page.q(css=".search-input").text[0], "") @attr(shard=2) class DiscussionTabSingleThreadTest(BaseDiscussionTestCase, DiscussionResponsePaginationTestMixin): """ Tests for the discussion page displaying a single thread """ def setUp(self): super(DiscussionTabSingleThreadTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.tab_nav = TabNavPage(self.browser) def setup_thread_page(self, thread_id): self.thread_page = self.create_single_thread_page(thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.visit() def test_mathjax_rendering(self): thread_id = "test_thread_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread( id=thread_id, body=THREAD_CONTENT_WITH_LATEX, commentable_id=self.discussion_id, thread_type="discussion" ) ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertTrue(self.thread_page.is_discussion_body_visible()) self.thread_page.verify_mathjax_preview_available() self.thread_page.verify_mathjax_rendered() def test_markdown_reference_link(self): """ Check markdown editor renders reference link correctly and colon(:) in reference link is not converted to %3a """ sample_link = "http://example.com/colon:test" thread_content = """[enter link description here][1]\n[1]: http://example.com/colon:test""" thread_id = "test_thread_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread( id=thread_id, body=thread_content, commentable_id=self.discussion_id, thread_type="discussion" ) ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertEqual(self.thread_page.get_link_href(), sample_link) def test_marked_answer_comments(self): thread_id = "test_thread_{}".format(uuid4().hex) response_id = "test_response_{}".format(uuid4().hex) comment_id = "test_comment_{}".format(uuid4().hex) thread_fixture = SingleThreadViewFixture( Thread(id=thread_id, commentable_id=self.discussion_id, thread_type="question") ) thread_fixture.addResponse( Response(id=response_id, endorsed=True), [Comment(id=comment_id)] ) thread_fixture.push() self.setup_thread_page(thread_id) self.assertFalse(self.thread_page.is_comment_visible(comment_id)) self.assertFalse(self.thread_page.is_add_comment_visible(response_id)) self.assertTrue(self.thread_page.is_show_comments_visible(response_id)) self.thread_page.show_comments(response_id) self.assertTrue(self.thread_page.is_comment_visible(comment_id)) self.assertTrue(self.thread_page.is_add_comment_visible(response_id)) self.assertFalse(self.thread_page.is_show_comments_visible(response_id)) def test_discussion_blackout_period(self): """ Verify that new discussion can not be started during course blackout period. Blackout period is the period between which students cannot post new or contribute to existing discussions. """ now = datetime.datetime.now(UTC) # Update course advance settings with a valid blackout period. self.course_fixture.add_advanced_settings( { u"discussion_blackouts": { "value": [ [ (now - datetime.timedelta(days=14)).isoformat(), (now + datetime.timedelta(days=2)).isoformat() ] ] } } ) self.course_fixture._add_advanced_settings() # pylint: disable=protected-access self.browser.refresh() thread = Thread(id=uuid4().hex, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.addResponse( Response(id="response1"), [Comment(id="comment1")]) thread_fixture.push() self.setup_thread_page(thread.get("id")) # pylint: disable=no-member # Verify that `Add a Post` is not visible on course tab nav. self.assertFalse(self.tab_nav.has_new_post_button_visible_on_tab()) # Verify that `Add a response` button is not visible. self.assertFalse(self.thread_page.has_add_response_button()) # Verify user can not add new responses or modify existing responses. self.assertFalse(self.thread_page.has_discussion_reply_editor()) self.assertFalse(self.thread_page.is_response_editable("response1")) self.assertFalse(self.thread_page.is_response_deletable("response1")) # Verify that user can not add new comment to a response or modify existing responses. self.assertFalse(self.thread_page.is_add_comment_visible("response1")) self.assertFalse(self.thread_page.is_comment_editable("comment1")) self.assertFalse(self.thread_page.is_comment_deletable("comment1")) class DiscussionTabMultipleThreadTest(BaseDiscussionTestCase): """ Tests for the discussion page with multiple threads """ def setUp(self): super(DiscussionTabMultipleThreadTest, self).setUp() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.thread_count = 2 self.thread_ids = [] self.setup_multiple_threads(thread_count=self.thread_count) self.thread_page_1 = DiscussionTabSingleThreadPage( self.browser, self.course_id, self.discussion_id, self.thread_ids[0] ) self.thread_page_2 = DiscussionTabSingleThreadPage( self.browser, self.course_id, self.discussion_id, self.thread_ids[1] ) self.thread_page_1.visit() @attr(shard=2) def setup_multiple_threads(self, thread_count): threads = [] for i in range(thread_count): thread_id = "test_thread_{}_{}".format(i, uuid4().hex) thread_body = "Dummy Long text body." * 50 threads.append( Thread(id=thread_id, commentable_id=self.discussion_id, body=thread_body), ) self.thread_ids.append(thread_id) view = MultipleThreadFixture(threads) view.push() @attr('a11y') def test_page_accessibility(self): self.thread_page_1.a11y_audit.config.set_rules({ "ignore": [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) self.thread_page_1.a11y_audit.check_for_accessibility_errors() self.thread_page_2.a11y_audit.config.set_rules({ "ignore": [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) self.thread_page_2.a11y_audit.check_for_accessibility_errors() class DiscussionOpenClosedThreadTest(BaseDiscussionTestCase): """ Tests for checking the display of attributes on open and closed threads """ def setUp(self): super(DiscussionOpenClosedThreadTest, self).setUp() self.thread_id = "test_thread_{}".format(uuid4().hex) def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self, **thread_kwargs): thread_kwargs.update({'commentable_id': self.discussion_id}) view = SingleThreadViewFixture( Thread(id=self.thread_id, **thread_kwargs) ) view.addResponse(Response(id="response1")) view.push() def setup_openclosed_thread_page(self, closed=False): self.setup_user(roles=['Moderator']) if closed: self.setup_view(closed=True) else: self.setup_view() page = self.create_single_thread_page(self.thread_id) page.visit() page.close_open_thread() return page @attr(shard=2) def test_originally_open_thread_vote_display(self): page = self.setup_openclosed_thread_page() self.assertFalse(page.is_element_visible('.thread-main-wrapper .action-vote')) self.assertTrue(page.is_element_visible('.thread-main-wrapper .display-vote')) self.assertFalse(page.is_element_visible('.response_response1 .action-vote')) self.assertTrue(page.is_element_visible('.response_response1 .display-vote')) @attr(shard=2) def test_originally_closed_thread_vote_display(self): page = self.setup_openclosed_thread_page(True) self.assertTrue(page.is_element_visible('.thread-main-wrapper .action-vote')) self.assertFalse(page.is_element_visible('.thread-main-wrapper .display-vote')) self.assertTrue(page.is_element_visible('.response_response1 .action-vote')) self.assertFalse(page.is_element_visible('.response_response1 .display-vote')) @attr('a11y') def test_page_accessibility(self): page = self.setup_openclosed_thread_page() page.a11y_audit.config.set_rules({ 'ignore': [ 'section', # TODO: AC-491 'color-contrast', # Commented out for now because they reproducibly fail on Jenkins but not locally ] }) page.a11y_audit.check_for_accessibility_errors() page = self.setup_openclosed_thread_page(True) page.a11y_audit.config.set_rules({ 'ignore': [ 'section', # TODO: AC-491 'color-contrast', # Commented out for now because they reproducibly fail on Jenkins but not locally ] }) page.a11y_audit.check_for_accessibility_errors() @attr(shard=2) class DiscussionCommentDeletionTest(BaseDiscussionTestCase): """ Tests for deleting comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_deletion_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [ Comment(id="comment_other_author"), Comment(id="comment_self_author", user_id=self.user_id, thread_id="comment_deletion_test_thread") ] ) view.push() def test_comment_deletion_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") def test_comment_deletion_as_moderator(self): self.setup_user(roles=['Moderator']) self.setup_view() page = self.create_single_thread_page("comment_deletion_test_thread") page.visit() self.assertTrue(page.is_comment_deletable("comment_self_author")) self.assertTrue(page.is_comment_deletable("comment_other_author")) page.delete_comment("comment_self_author") page.delete_comment("comment_other_author") class DiscussionResponseEditTest(BaseDiscussionTestCase): """ Tests for editing responses displayed beneath thread in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="response_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response_other_author", user_id="other", thread_id="response_edit_test_thread"), ) view.addResponse( Response(id="response_self_author", user_id=self.user_id, thread_id="response_edit_test_thread"), ) view.push() def edit_response(self, page, response_id): self.assertTrue(page.is_response_editable(response_id)) page.start_response_edit(response_id) new_response = "edited body" page.set_response_editor_value(response_id, new_response) page.submit_response_edit(response_id, new_response) @attr(shard=2) def test_edit_response_add_link(self): """ Scenario: User submits valid input to the 'add link' form Given I am editing a response on a discussion page When I click the 'add link' icon in the editor toolbar And enter a valid url to the URL input field And enter a valid string in the Description input field And click the 'OK' button Then the edited response should contain the new link """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() response_id = "response_self_author" url = "http://example.com" description = "example" page.start_response_edit(response_id) page.set_response_editor_value(response_id, "") page.add_content_via_editor_button( "link", response_id, url, description) page.submit_response_edit(response_id, description) expected_response_html = ( '<p><a href="{}">{}</a></p>'.format(url, description) ) actual_response_html = page.q( css=".response_{} .response-body".format(response_id) ).html[0] self.assertEqual(expected_response_html, actual_response_html) @attr(shard=2) def test_edit_response_add_image(self): """ Scenario: User submits valid input to the 'add image' form Given I am editing a response on a discussion page When I click the 'add image' icon in the editor toolbar And enter a valid url to the URL input field And enter a valid string in the Description input field And click the 'OK' button Then the edited response should contain the new image """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() response_id = "response_self_author" url = "http://www.example.com/something.png" description = "image from example.com" page.start_response_edit(response_id) page.set_response_editor_value(response_id, "") page.add_content_via_editor_button( "image", response_id, url, description) page.submit_response_edit(response_id, '') expected_response_html = ( '<p><img src="{}" alt="{}" title=""></p>'.format(url, description) ) actual_response_html = page.q( css=".response_{} .response-body".format(response_id) ).html[0] self.assertEqual(expected_response_html, actual_response_html) @attr(shard=2) def test_edit_response_add_image_error_msg(self): """ Scenario: User submits invalid input to the 'add image' form Given I am editing a response on a discussion page When I click the 'add image' icon in the editor toolbar And enter an invalid url to the URL input field And enter an empty string in the Description input field And click the 'OK' button Then I should be shown 2 error messages """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() page.start_response_edit("response_self_author") page.add_content_via_editor_button( "image", "response_self_author", '', '') page.verify_link_editor_error_messages_shown() @attr(shard=2) def test_edit_response_add_decorative_image(self): """ Scenario: User submits invalid input to the 'add image' form Given I am editing a response on a discussion page When I click the 'add image' icon in the editor toolbar And enter a valid url to the URL input field And enter an empty string in the Description input field And I check the 'image is decorative' checkbox And click the 'OK' button Then the edited response should contain the new image """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() response_id = "response_self_author" url = "http://www.example.com/something.png" description = "" page.start_response_edit(response_id) page.set_response_editor_value(response_id, "Some content") page.add_content_via_editor_button( "image", response_id, url, description, is_decorative=True) page.submit_response_edit(response_id, "Some content") expected_response_html = ( '<p>Some content<img src="{}" alt="{}" title=""></p>'.format( url, description) ) actual_response_html = page.q( css=".response_{} .response-body".format(response_id) ).html[0] self.assertEqual(expected_response_html, actual_response_html) @attr(shard=2) def test_edit_response_add_link_error_msg(self): """ Scenario: User submits invalid input to the 'add link' form Given I am editing a response on a discussion page When I click the 'add link' icon in the editor toolbar And enter an invalid url to the URL input field And enter an empty string in the Description input field And click the 'OK' button Then I should be shown 2 error messages """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() page.start_response_edit("response_self_author") page.add_content_via_editor_button( "link", "response_self_author", '', '') page.verify_link_editor_error_messages_shown() @attr(shard=2) def test_edit_response_as_student(self): """ Scenario: Students should be able to edit the response they created not responses of other users Given that I am on discussion page with student logged in When I try to edit the response created by student Then the response should be edited and rendered successfully And responses from other users should be shown over there And the student should be able to edit the response of other people """ self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.assertTrue(page.is_response_visible("response_other_author")) self.assertFalse(page.is_response_editable("response_other_author")) self.edit_response(page, "response_self_author") @attr(shard=2) def test_edit_response_as_moderator(self): """ Scenario: Moderator should be able to edit the response they created and responses of other users Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") @attr(shard=2) @flaky # TODO fix this, see TNL-5453 def test_vote_report_endorse_after_edit(self): """ Scenario: Moderator should be able to vote, report or endorse after editing the response. Given that I am on discussion page with moderator logged in When I try to edit the response created by moderator Then the response should be edited and rendered successfully And I try to edit the response created by other users Then the response should be edited and rendered successfully And I try to vote the response created by moderator Then the response should not be able to be voted And I try to vote the response created by other users Then the response should be voted successfully And I try to report the response created by moderator Then the response should not be able to be reported And I try to report the response created by other users Then the response should be reported successfully And I try to endorse the response created by moderator Then the response should be endorsed successfully And I try to endorse the response created by other users Then the response should be endorsed successfully """ self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.visit() self.edit_response(page, "response_self_author") self.edit_response(page, "response_other_author") page.cannot_vote_response('response_self_author') page.vote_response('response_other_author') page.cannot_report_response('response_self_author') page.report_response('response_other_author') page.endorse_response('response_self_author') page.endorse_response('response_other_author') @attr('a11y') def test_page_accessibility(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("response_edit_test_thread") page.a11y_audit.config.set_rules({ 'ignore': [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) page.visit() page.a11y_audit.check_for_accessibility_errors() class DiscussionCommentEditTest(BaseDiscussionTestCase): """ Tests for editing comments displayed beneath responses in the single thread view. """ def setup_user(self, roles=[]): roles_str = ','.join(roles) self.user_id = AutoAuthPage(self.browser, course_id=self.course_id, roles=roles_str).visit().get_user_id() def setup_view(self): view = SingleThreadViewFixture(Thread(id="comment_edit_test_thread", commentable_id=self.discussion_id)) view.addResponse( Response(id="response1"), [Comment(id="comment_other_author", user_id="other"), Comment(id="comment_self_author", user_id=self.user_id)]) view.push() def edit_comment(self, page, comment_id): page.start_comment_edit(comment_id) new_comment = "edited body" page.set_comment_editor_value(comment_id, new_comment) page.submit_comment_edit(comment_id, new_comment) @attr(shard=2) def test_edit_comment_as_student(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_visible("comment_other_author")) self.assertFalse(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") @attr(shard=2) def test_edit_comment_as_moderator(self): self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.edit_comment(page, "comment_self_author") self.edit_comment(page, "comment_other_author") @attr(shard=2) def test_cancel_comment_edit(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") page.set_comment_editor_value("comment_self_author", "edited body") page.cancel_comment_edit("comment_self_author", original_body) @attr(shard=2) def test_editor_visibility(self): """Only one editor should be visible at a time within a single response""" self.setup_user(roles=["Moderator"]) self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() self.assertTrue(page.is_comment_editable("comment_self_author")) self.assertTrue(page.is_comment_editable("comment_other_author")) self.assertTrue(page.is_add_comment_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_add_comment_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.set_comment_editor_value("comment_self_author", "edited body") page.start_comment_edit("comment_other_author") self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_comment_editor_visible("comment_other_author")) self.assertEqual(page.get_comment_body("comment_self_author"), original_body) page.start_response_edit("response1") self.assertFalse(page.is_comment_editor_visible("comment_other_author")) self.assertTrue(page.is_response_editor_visible("response1")) original_body = page.get_comment_body("comment_self_author") page.start_comment_edit("comment_self_author") self.assertFalse(page.is_response_editor_visible("response1")) self.assertTrue(page.is_comment_editor_visible("comment_self_author")) page.cancel_comment_edit("comment_self_author", original_body) self.assertFalse(page.is_comment_editor_visible("comment_self_author")) self.assertTrue(page.is_add_comment_visible("response1")) @attr('a11y') def test_page_accessibility(self): self.setup_user() self.setup_view() page = self.create_single_thread_page("comment_edit_test_thread") page.visit() page.a11y_audit.config.set_rules({ 'ignore': [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) page.a11y_audit.check_for_accessibility_errors() @attr(shard=2) class DiscussionEditorPreviewTest(UniqueCourseTest): def setUp(self): super(DiscussionEditorPreviewTest, self).setUp() CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() self.page.click_new_post_button() def test_text_rendering(self): """When I type plain text into the editor, it should be rendered as plain text in the preview box""" self.page.set_new_post_editor_value("Some plain text") self.assertEqual(self.page.get_new_post_preview_value(), "<p>Some plain text</p>") def test_markdown_rendering(self): """When I type Markdown into the editor, it should be rendered as formatted Markdown in the preview box""" self.page.set_new_post_editor_value( "Some markdown\n" "\n" "- line 1\n" "- line 2" ) self.assertEqual(self.page.get_new_post_preview_value(), ( "<p>Some markdown</p>\n" "\n" "<ul>\n" "<li>line 1</li>\n" "<li>line 2</li>\n" "</ul>" )) def test_mathjax_rendering_in_order(self): """ Tests that mathjax is rendered in proper order. When user types mathjax expressions into discussion editor, it should render in the proper order. """ self.page.set_new_post_editor_value( 'Text line 1 \n' '$$e[n]=d_1$$ \n' 'Text line 2 \n' '$$e[n]=d_2$$' ) self.assertEqual(self.page.get_new_post_preview_text(), 'Text line 1\nText line 2') @attr(shard=2) class InlineDiscussionTest(UniqueCourseTest, DiscussionResponsePaginationTestMixin): """ Tests for inline discussions """ def setUp(self): super(InlineDiscussionTest, self).setUp() self.thread_ids = [] self.discussion_id = "test_discussion_{}".format(uuid4().hex) self.additional_discussion_id = "test_discussion_{}".format(uuid4().hex) self.course_fix = CourseFixture(**self.course_info).add_children( XBlockFixtureDesc("chapter", "Test Section").add_children( XBlockFixtureDesc("sequential", "Test Subsection").add_children( XBlockFixtureDesc("vertical", "Test Unit").add_children( XBlockFixtureDesc( "discussion", "Test Discussion", metadata={"discussion_id": self.discussion_id} ), XBlockFixtureDesc( "discussion", "Test Discussion 1", metadata={"discussion_id": self.additional_discussion_id} ) ) ) ) ).install() self.user_id = AutoAuthPage(self.browser, course_id=self.course_id).visit().get_user_id() self.courseware_page = CoursewarePage(self.browser, self.course_id) self.courseware_page.visit() self.discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) self.additional_discussion_page = InlineDiscussionPage(self.browser, self.additional_discussion_id) def setup_thread_page(self, thread_id): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 1) self.thread_page = InlineDiscussionThreadPage(self.browser, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.expand() def setup_multiple_inline_threads(self, thread_count): """ Set up multiple treads on the page by passing 'thread_count' """ threads = [] for i in range(thread_count): thread_id = "test_thread_{}_{}".format(i, uuid4().hex) threads.append( Thread(id=thread_id, commentable_id=self.discussion_id), ) self.thread_ids.append(thread_id) thread_fixture = MultipleThreadFixture(threads) thread_fixture.add_response( Response(id="response1"), [Comment(id="comment1", user_id="other"), Comment(id="comment2", user_id=self.user_id)], threads[0] ) thread_fixture.push() def test_page_while_expanding_inline_discussion(self): """ Tests for the Inline Discussion page with multiple treads. Page should not focus 'thread-wrapper' after loading responses. """ self.setup_multiple_inline_threads(thread_count=3) self.discussion_page.expand_discussion() thread_page = InlineDiscussionThreadPage(self.browser, self.thread_ids[0]) thread_page.expand() # Check if 'thread-wrapper' is focused after expanding thread self.assertFalse(thread_page.check_if_selector_is_focused(selector='.thread-wrapper')) def test_add_a_post_is_present_if_can_create_thread_when_expanded(self): self.discussion_page.expand_discussion() # Add a Post link is present self.assertTrue(self.discussion_page.q(css='.new-post-btn').present) def test_initial_render(self): self.assertFalse(self.discussion_page.is_discussion_expanded()) def test_expand_discussion_empty(self): self.discussion_page.expand_discussion() self.assertEqual(self.discussion_page.get_num_displayed_threads(), 0) def check_anonymous_to_peers(self, is_staff): thread = Thread(id=uuid4().hex, anonymous_to_peers=True, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertEqual(self.thread_page.is_thread_anonymous(), not is_staff) def test_anonymous_to_peers_threads_as_staff(self): AutoAuthPage(self.browser, course_id=self.course_id, roles="Administrator").visit() self.courseware_page.visit() self.check_anonymous_to_peers(True) def test_anonymous_to_peers_threads_as_peer(self): self.check_anonymous_to_peers(False) def test_discussion_blackout_period(self): now = datetime.datetime.now(UTC) self.course_fix.add_advanced_settings( { u"discussion_blackouts": { "value": [ [ (now - datetime.timedelta(days=14)).isoformat(), (now + datetime.timedelta(days=2)).isoformat() ] ] } } ) self.course_fix._add_advanced_settings() self.browser.refresh() thread = Thread(id=uuid4().hex, commentable_id=self.discussion_id) thread_fixture = SingleThreadViewFixture(thread) thread_fixture.addResponse( Response(id="response1"), [Comment(id="comment1", user_id="other"), Comment(id="comment2", user_id=self.user_id)]) thread_fixture.push() self.setup_thread_page(thread.get("id")) self.assertFalse(self.thread_page.has_add_response_button()) self.assertFalse(self.thread_page.is_element_visible("action-more")) def test_dual_discussion_xblock(self): """ Scenario: Two discussion xblocks in one unit shouldn't override their actions Given that I'm on courseware page where there are two inline discussion When I click on one discussion xblock new post button Then it should add new post form of that xblock in DOM And I should be shown new post form of that xblock And I shouldn't be shown second discussion xblock new post form And I click on second discussion xblock new post button Then it should add new post form of second xblock in DOM And I should be shown second discussion new post form And I shouldn't be shown first discussion xblock new post form And I have two new post form in the DOM When I click back on first xblock new post button And I should be shown new post form of that xblock And I shouldn't be shown second discussion xblock new post form """ self.discussion_page.wait_for_page() self.additional_discussion_page.wait_for_page() self.discussion_page.expand_discussion() self.discussion_page.click_new_post_button() with self.discussion_page.handle_alert(): self.discussion_page.click_cancel_new_post() self.additional_discussion_page.expand_discussion() self.additional_discussion_page.click_new_post_button() self.assertFalse(self.discussion_page._is_element_visible(".new-post-article")) with self.additional_discussion_page.handle_alert(): self.additional_discussion_page.click_cancel_new_post() self.discussion_page.expand_discussion() self.discussion_page.click_new_post_button() self.assertFalse(self.additional_discussion_page._is_element_visible(".new-post-article")) @attr(shard=2) class DiscussionUserProfileTest(UniqueCourseTest): """ Tests for user profile page in discussion tab. """ PAGE_SIZE = 20 # discussion.views.THREADS_PER_PAGE PROFILED_USERNAME = "profiled-user" def setUp(self): super(DiscussionUserProfileTest, self).setUp() CourseFixture(**self.course_info).install() # The following line creates a user enrolled in our course, whose # threads will be viewed, but not the one who will view the page. # It isn't necessary to log them in, but using the AutoAuthPage # saves a lot of code. self.profiled_user_id = AutoAuthPage( self.browser, username=self.PROFILED_USERNAME, course_id=self.course_id ).visit().get_user_id() # now create a second user who will view the profile. self.user_id = AutoAuthPage( self.browser, course_id=self.course_id ).visit().get_user_id() def check_pages(self, num_threads): # set up the stub server to return the desired amount of thread results threads = [Thread(id=uuid4().hex) for _ in range(num_threads)] UserProfileViewFixture(threads).push() # navigate to default view (page 1) page = DiscussionUserProfilePage( self.browser, self.course_id, self.profiled_user_id, self.PROFILED_USERNAME ) page.visit() current_page = 1 total_pages = max(num_threads - 1, 1) / self.PAGE_SIZE + 1 all_pages = range(1, total_pages + 1) return page def _check_page(): # ensure the page being displayed as "current" is the expected one self.assertEqual(page.get_current_page(), current_page) # ensure the expected threads are being shown in the right order threads_expected = threads[(current_page - 1) * self.PAGE_SIZE:current_page * self.PAGE_SIZE] self.assertEqual(page.get_shown_thread_ids(), [t["id"] for t in threads_expected]) # ensure the clickable page numbers are the expected ones self.assertEqual(page.get_clickable_pages(), [ p for p in all_pages if p != current_page and p - 2 <= current_page <= p + 2 or (current_page > 2 and p == 1) or (current_page < total_pages and p == total_pages) ]) # ensure the previous button is shown, but only if it should be. # when it is shown, make sure it works. if current_page > 1: self.assertTrue(page.is_prev_button_shown(current_page - 1)) page.click_prev_page() self.assertEqual(page.get_current_page(), current_page - 1) page.click_next_page() self.assertEqual(page.get_current_page(), current_page) else: self.assertFalse(page.is_prev_button_shown()) # ensure the next button is shown, but only if it should be. if current_page < total_pages: self.assertTrue(page.is_next_button_shown(current_page + 1)) else: self.assertFalse(page.is_next_button_shown()) # click all the way up through each page for __ in range(current_page, total_pages): _check_page() if current_page < total_pages: page.click_on_page(current_page + 1) current_page += 1 # click all the way back down for __ in range(current_page, 0, -1): _check_page() if current_page > 1: page.click_on_page(current_page - 1) current_page -= 1 def test_0_threads(self): self.check_pages(0) def test_1_thread(self): self.check_pages(1) def test_20_threads(self): self.check_pages(20) def test_21_threads(self): self.check_pages(21) def test_151_threads(self): self.check_pages(151) def test_pagination_window_reposition(self): page = self.check_pages(50) page.click_next_page() page.wait_for_ajax() self.assertTrue(page.is_window_on_top()) def test_redirects_to_learner_profile(self): """ Scenario: Verify that learner-profile link is present on forum discussions page and we can navigate to it. Given that I am on discussion forum user's profile page. And I can see a username on left sidebar When I click on my username. Then I will be navigated to Learner Profile page. And I can my username on Learner Profile page """ learner_profile_page = LearnerProfilePage(self.browser, self.PROFILED_USERNAME) page = self.check_pages(1) page.click_on_sidebar_username() learner_profile_page.wait_for_page() self.assertTrue(learner_profile_page.field_is_visible('username')) class DiscussionSearchAlertTest(UniqueCourseTest): """ Tests for spawning and dismissing alerts related to user search actions and their results. """ SEARCHED_USERNAME = "gizmo" def setUp(self): super(DiscussionSearchAlertTest, self).setUp() CourseFixture(**self.course_info).install() # first auto auth call sets up a user that we will search for in some tests self.searched_user_id = AutoAuthPage( self.browser, username=self.SEARCHED_USERNAME, course_id=self.course_id ).visit().get_user_id() # this auto auth call creates the actual session user AutoAuthPage(self.browser, course_id=self.course_id).visit() self.page = DiscussionTabHomePage(self.browser, self.course_id) self.page.visit() def setup_corrected_text(self, text): SearchResultFixture(SearchResult(corrected_text=text)).push() def check_search_alert_messages(self, expected): actual = self.page.get_search_alert_messages() self.assertTrue(all(map(lambda msg, sub: msg.lower().find(sub.lower()) >= 0, actual, expected))) @attr(shard=2) def test_no_rewrite(self): self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) @attr(shard=2) def test_rewrite_dismiss(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.page.dismiss_alert_message("foo") self.check_search_alert_messages([]) @attr(shard=2) def test_new_search(self): self.setup_corrected_text("foo") self.page.perform_search() self.check_search_alert_messages(["foo"]) self.setup_corrected_text("bar") self.page.perform_search() self.check_search_alert_messages(["bar"]) self.setup_corrected_text(None) self.page.perform_search() self.check_search_alert_messages(["no threads"]) @attr(shard=2) def test_rewrite_and_user(self): self.setup_corrected_text("foo") self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["foo", self.SEARCHED_USERNAME]) @attr(shard=2) def test_user_only(self): self.setup_corrected_text(None) self.page.perform_search(self.SEARCHED_USERNAME) self.check_search_alert_messages(["no threads", self.SEARCHED_USERNAME]) # make sure clicking the link leads to the user profile page UserProfileViewFixture([]).push() self.page.get_search_alert_links().first.click() DiscussionUserProfilePage( self.browser, self.course_id, self.searched_user_id, self.SEARCHED_USERNAME ).wait_for_page() @attr('a11y') def test_page_accessibility(self): self.page.a11y_audit.config.set_rules({ 'ignore': [ 'section', # TODO: AC-491 'aria-required-children', # TODO: AC-534 ] }) self.page.a11y_audit.check_for_accessibility_errors() @attr(shard=2) class DiscussionSortPreferenceTest(UniqueCourseTest): """ Tests for the discussion page displaying a single thread. """ def setUp(self): super(DiscussionSortPreferenceTest, self).setUp() # Create a course to register for. CourseFixture(**self.course_info).install() AutoAuthPage(self.browser, course_id=self.course_id).visit() self.sort_page = DiscussionSortPreferencePage(self.browser, self.course_id) self.sort_page.visit() self.sort_page.show_all_discussions() def test_default_sort_preference(self): """ Test to check the default sorting preference of user. (Default = date ) """ selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, "activity") @skip_if_browser('chrome') # TODO TE-1542 and TE-1543 def test_change_sort_preference(self): """ Test that if user sorting preference is changing properly. """ selected_sort = "" for sort_type in ["votes", "comments", "activity"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) @skip_if_browser('chrome') # TODO TE-1542 and TE-1543 def test_last_preference_saved(self): """ Test that user last preference is saved. """ selected_sort = "" for sort_type in ["votes", "comments", "activity"]: self.assertNotEqual(selected_sort, sort_type) self.sort_page.change_sort_preference(sort_type) selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type) self.sort_page.refresh_page() self.sort_page.show_all_discussions() selected_sort = self.sort_page.get_selected_sort_preference() self.assertEqual(selected_sort, sort_type)
itsjeyd/edx-platform
common/test/acceptance/tests/discussion/test_discussion.py
Python
agpl-3.0
61,987
[ "VisIt" ]
eea23caeff7cf365876e3c50fb2d2284c998f868e6cb2d8ab674a18a074b39df
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of the copyright holder nor the names of # its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # 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. '''NeuroM neuron checking functions. Contains functions for checking validity of neuron neurites and somata. Tests assumes neurites and/or soma have been succesfully built where applicable, i.e. soma- and neurite-related structural tests pass. ''' import numpy as np from neurom import NeuriteType from neurom.core import Tree, iter_segments from neurom.core.dataformat import COLS from neurom.morphmath import section_length, segment_length from neurom.check.morphtree import get_flat_neurites, get_nonmonotonic_neurites from neurom.fst import _neuritefunc as _nf from neurom.check import CheckResult from neurom._compat import zip def _read_neurite_type(neurite): '''Simply read the stored neurite type''' return neurite.type def has_axon(neuron, treefun=_read_neurite_type): '''Check if a neuron has an axon Arguments: neuron(Neuron): The neuron object to test treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' return CheckResult(NeuriteType.axon in (treefun(n) for n in neuron.neurites)) def has_apical_dendrite(neuron, min_number=1, treefun=_read_neurite_type): '''Check if a neuron has apical dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of apical dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' types = [treefun(n) for n in neuron.neurites] return CheckResult(types.count(NeuriteType.apical_dendrite) >= min_number) def has_basal_dendrite(neuron, min_number=1, treefun=_read_neurite_type): '''Check if a neuron has basal dendrites Arguments: neuron(Neuron): The neuron object to test min_number: minimum number of basal dendrites required treefun: Optional function to calculate the tree type of neuron's neurites Returns: CheckResult with result ''' types = [treefun(n) for n in neuron.neurites] return CheckResult(types.count(NeuriteType.basal_dendrite) >= min_number) def has_no_flat_neurites(neuron, tol=0.1, method='ratio'): '''Check that a neuron has no flat neurites Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' as described in :meth:`neurom.check.morphtree.get_flat_neurites` Returns: CheckResult with result ''' return CheckResult(len(get_flat_neurites(neuron, tol, method)) == 0) def has_all_monotonic_neurites(neuron, tol=1e-6): '''Check that a neuron has only neurites that are monotonic Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance Returns: CheckResult with result ''' return CheckResult(len(get_nonmonotonic_neurites(neuron, tol)) == 0) def has_all_nonzero_segment_lengths(neuron, threshold=0.0): '''Check presence of neuron segments with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a segment length is considered to be non-zero Returns: CheckResult with result including list of (section_id, segment_id) of zero length segments ''' bad_ids = [] for sec in _nf.iter_sections(neuron): p = sec.points for i, s in enumerate(zip(p[:-1], p[1:])): if segment_length(s) <= threshold: bad_ids.append((sec.id, i)) return CheckResult(len(bad_ids) == 0, bad_ids) def has_all_nonzero_section_lengths(neuron, threshold=0.0): '''Check presence of neuron sections with length not above threshold Arguments: neuron(Neuron): The neuron object to test threshold(float): value above which a section length is considered to be non-zero Returns: CheckResult with result including list of ids bad sections ''' bad_ids = [s.id for s in _nf.iter_sections(neuron.neurites) if section_length(s.points) <= threshold] return CheckResult(len(bad_ids) == 0, bad_ids) def has_all_nonzero_neurite_radii(neuron, threshold=0.0): '''Check presence of neurite points with radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which a radius is considered to be non-zero Returns: CheckResult with result including list of (section ID, point ID) pairs of zero-radius points ''' bad_ids = [] seen_ids = set() for s in _nf.iter_sections(neuron): for i, p in enumerate(s.points): info = (s.id, i) if p[COLS.R] <= threshold and info not in seen_ids: seen_ids.add(info) bad_ids.append(info) return CheckResult(len(bad_ids) == 0, bad_ids) def has_nonzero_soma_radius(neuron, threshold=0.0): '''Check if soma radius not above threshold Arguments: neuron(Neuron): The neuron object to test threshold: value above which the soma radius is considered to be non-zero Returns: CheckResult with result ''' return CheckResult(neuron.soma.radius > threshold) def has_no_jumps(neuron, max_distance=30.0, axis='z'): '''Check if there are jumps (large movements in the `axis`) Arguments: neuron(Neuron): The neuron object to test max_z_distance(float): value above which consecutive z-values are considered a jump axis(str): one of x/y/z, which axis to check for jumps Returns: CheckResult with result list of ids bad sections ''' bad_ids = [] axis = {'x': COLS.X, 'y': COLS.Y, 'z': COLS.Z, }[axis.lower()] for sec in _nf.iter_sections(neuron): for i, (p0, p1) in enumerate(iter_segments(sec)): info = (sec.id, i) if max_distance < abs(p0[axis] - p1[axis]): bad_ids.append(info) return CheckResult(len(bad_ids) == 0, bad_ids) def has_no_fat_ends(neuron, multiple_of_mean=2.0, final_point_count=5): '''Check if leaf points are too large Arguments: neuron(Neuron): The neuron object to test multiple_of_mean(float): how many times larger the final radius has to be compared to the mean of the final points final_point_count(int): how many points to include in the mean Returns: CheckResult with result list of ids bad sections Note: A fat end is defined as a leaf segment whose last point is larger by a factor of `multiple_of_mean` than the mean of the points in `final_point_count` ''' bad_ids = [] for leaf in _nf.iter_sections(neuron.neurites, iterator_type=Tree.ileaf): mean_radius = np.mean(leaf.points[-final_point_count:, COLS.R]) if mean_radius * multiple_of_mean < leaf.points[-1, COLS.R]: bad_ids.append((leaf.id, len(leaf.points))) return CheckResult(len(bad_ids) == 0, bad_ids)
liesbethvanherpe/NeuroM
neurom/check/neuron_checks.py
Python
bsd-3-clause
8,829
[ "NEURON" ]
be1ac99802210ed66c786a18b56f68ff8a21c3d06bce7471467dc9562689a223
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function import logging import math import itertools import warnings from collections import OrderedDict import six import numpy as np from monty.json import jsanitize from pymatgen.core.periodic_table import Element from pymatgen.electronic_structure.core import Spin, Orbital, OrbitalType from pymatgen.electronic_structure.bandstructure import BandStructureSymmLine from pymatgen.util.plotting import pretty_plot, \ add_fig_kwargs, get_ax3d_fig_plt from collections import Counter import copy from pymatgen.electronic_structure.boltztrap import BoltztrapError from pymatgen.symmetry.bandstructure import HighSymmKpath """ This module implements plotter for DOS and band structure. """ __author__ = "Shyue Ping Ong, Geoffroy Hautier, Anubhav Jain" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "May 1, 2012" logger = logging.getLogger(__name__) class DosPlotter(object): """ Class for plotting DOSs. Note that the interface is extremely flexible given that there are many different ways in which people want to view DOS. The typical usage is:: # Initializes plotter with some optional args. Defaults are usually # fine, plotter = DosPlotter() # Adds a DOS with a label. plotter.add_dos("Total DOS", dos) # Alternatively, you can add a dict of DOSs. This is the typical # form returned by CompleteDos.get_spd/element/others_dos(). plotter.add_dos_dict({"dos1": dos1, "dos2": dos2}) plotter.add_dos_dict(complete_dos.get_spd_dos()) Args: zero_at_efermi: Whether to shift all Dos to have zero energy at the fermi energy. Defaults to True. stack: Whether to plot the DOS as a stacked area graph key_sort_func: function used to sort the dos_dict keys. sigma: A float specifying a standard deviation for Gaussian smearing the DOS for nicer looking plots. Defaults to None for no smearing. """ def __init__(self, zero_at_efermi=True, stack=False, sigma=None): self.zero_at_efermi = zero_at_efermi self.stack = stack self.sigma = sigma self._doses = OrderedDict() def add_dos(self, label, dos): """ Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: Dos object """ energies = dos.energies - dos.efermi if self.zero_at_efermi \ else dos.energies densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities efermi = dos.efermi self._doses[label] = {'energies': energies, 'densities': densities, 'efermi': efermi} def add_dos_dict(self, dos_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_func: keys = sorted(dos_dict.keys(), key=key_sort_func) else: keys = dos_dict.keys() for label in keys: self.add_dos(label, dos_dict[label]) def get_dos_dict(self): """ Returns the added doses as a json-serializable dict. Note that if you have specified smearing for the DOS plot, the densities returned will be the smeared densities, not the original densities. Returns: dict: Dict of dos data. Generally of the form {label: {'energies':..., 'densities': {'up':...}, 'efermi':efermi}} """ return jsanitize(self._doses) def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) import palettable colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors y = None alldensities = [] allenergies = [] plt = pretty_plot(12, 8) # Note that this complicated processing of energies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): energies = dos['energies'] densities = dos['densities'] if not y: y = {Spin.up: np.zeros(energies.shape), Spin.down: np.zeros(energies.shape)} newdens = {} for spin in [Spin.up, Spin.down]: if spin in densities: if self.stack: y[spin] += densities[spin] newdens[spin] = y[spin].copy() else: newdens[spin] = densities[spin] allenergies.append(energies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allenergies.reverse() allpts = [] for i, key in enumerate(keys): x = [] y = [] for spin in [Spin.up, Spin.down]: if spin in alldensities[i]: densities = list(int(spin) * alldensities[i][spin]) energies = list(allenergies[i]) if spin == Spin.down: energies.reverse() densities.reverse() x.extend(energies) y.extend(densities) allpts.extend(list(zip(x, y))) if self.stack: plt.fill(x, y, color=colors[i % ncolors], label=str(key)) else: plt.plot(x, y, color=colors[i % ncolors], label=str(key), linewidth=3) if not self.zero_at_efermi: ylim = plt.ylim() plt.plot([self._doses[key]['efermi'], self._doses[key]['efermi']], ylim, color=colors[i % ncolors], linestyle='--', linewidth=2) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) if self.zero_at_efermi: ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Energies (eV)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt def save_plot(self, filename, img_format="eps", xlim=None, ylim=None): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.savefig(filename, format=img_format) def show(self, xlim=None, ylim=None): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ plt = self.get_plot(xlim, ylim) plt.show() class BSPlotter(object): """ Class to plot or get data to facilitate the plot of band structure objects. Args: bs: A BandStructureSymmLine object. """ def __init__(self, bs): if not isinstance(bs, BandStructureSymmLine): raise ValueError( "BSPlotter only works with BandStructureSymmLine objects. " "A BandStructure object (on a uniform grid for instance and " "not along symmetry lines won't work)") self._bs = bs # TODO: come with an intelligent way to cut the highest unconverged # bands self._nb_bands = self._bs.nb_bands def _maketicks(self, plt): """ utility private method to add ticks to a band structure """ ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in range(len(temp_ticks)): if i == 0: uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) else: if temp_ticks[i][1] == temp_ticks[i - 1][1]: logger.debug("Skipping label {i}".format( i=temp_ticks[i][1])) else: logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Unique labels are %s" % list(zip(uniq_d, uniq_l))) plt.gca().set_xticks(uniq_d) plt.gca().set_xticklabels(uniq_l) for i in range(len(ticks['label'])): if ticks['label'][i] is not None: # don't print the same label twice if i != 0: if ticks['label'][i] == ticks['label'][i - 1]: logger.debug("already print label... " "skipping label {i}".format( i=ticks['label'][i])) else: logger.debug("Adding a line at {d}" " for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') else: logger.debug("Adding a line at {d} for label {l}".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') return plt def bs_plot_data(self, zero_to_efermi=True): """ Get the data nicely formatted for a plot Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot. Returns: dict: A dictionary of the following format: ticks: A dict with the 'distances' at which there is a kpoint (the x axis) and the labels (None if no label). energy: A dict storing bands for spin up and spin down data [{Spin:[band_index][k_point_index]}] as a list (one element for each branch) of energy for each kpoint. The data is stored by branch to facilitate the plotting. vbm: A list of tuples (distance,energy) marking the vbms. The energies are shifted with respect to the fermi level is the option has been selected. cbm: A list of tuples (distance,energy) marking the cbms. The energies are shifted with respect to the fermi level is the option has been selected. lattice: The reciprocal lattice. zero_energy: This is the energy used as zero for the plot. band_gap:A string indicating the band gap and its nature (empty if it's a metal). is_metal: True if the band structure is metallic (i.e., there is at least one band crossing the fermi level). """ distance = [] energy = [] if self._bs.is_metal(): zero_energy = self._bs.efermi else: zero_energy = self._bs.get_vbm()['energy'] if not zero_to_efermi: zero_energy = 0.0 for b in self._bs.branches: if self._bs.is_spin_polarized: energy.append({str(Spin.up): [], str(Spin.down): []}) else: energy.append({str(Spin.up): []}) distance.append([self._bs.distance[j] for j in range(b['start_index'], b['end_index'] + 1)]) ticks = self.get_ticks() for i in range(self._nb_bands): energy[-1][str(Spin.up)].append( [self._bs.bands[Spin.up][i][j] - zero_energy for j in range(b['start_index'], b['end_index'] + 1)]) if self._bs.is_spin_polarized: for i in range(self._nb_bands): energy[-1][str(Spin.down)].append( [self._bs.bands[Spin.down][i][j] - zero_energy for j in range(b['start_index'], b['end_index'] + 1)]) vbm = self._bs.get_vbm() cbm = self._bs.get_cbm() vbm_plot = [] cbm_plot = [] for index in cbm['kpoint_index']: cbm_plot.append((self._bs.distance[index], cbm['energy'] - zero_energy if zero_to_efermi else cbm['energy'])) for index in vbm['kpoint_index']: vbm_plot.append((self._bs.distance[index], vbm['energy'] - zero_energy if zero_to_efermi else vbm['energy'])) bg = self._bs.get_band_gap() direct = "Indirect" if bg['direct']: direct = "Direct" return {'ticks': ticks, 'distances': distance, 'energy': energy, 'vbm': vbm_plot, 'cbm': cbm_plot, 'lattice': self._bs.lattice_rec.as_dict(), 'zero_energy': zero_energy, 'is_metal': self._bs.is_metal(), 'band_gap': "{} {} bandgap = {}".format(direct, bg['transition'], bg['energy']) if not self._bs.is_metal() else ""} def get_plot(self, zero_to_efermi=True, ylim=None, smooth=False, vbm_cbm_marker=False, smooth_tol=None): """ Get a matplotlib object for the bandstructure plot. Blue lines are up spin, red lines are down spin. Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot (E-Ef). ylim: Specify the y-axis (energy) limits; by default None let the code choose. It is vbm-4 and cbm+4 if insulator efermi-10 and efermi+10 if metal smooth: interpolates the bands by a spline cubic smooth_tol (float) : tolerance for fitting spline to band data. Default is None such that no tolerance will be used. """ plt = pretty_plot(12, 8) from matplotlib import rc import scipy.interpolate as scint # main internal config options e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 # band_linewidth = 3 band_linewidth = 1 data = self.bs_plot_data(zero_to_efermi) if not smooth: for d in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][d], [data['energy'][d][str(Spin.up)][i][j] for j in range(len(data['distances'][d]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][d], [data['energy'][d][str(Spin.down)][i][j] for j in range(len(data['distances'][d]))], 'r--', linewidth=band_linewidth) else: # Interpolation failure can be caused by trying to fit an entire # band with one spline rather than fitting with piecewise splines # (splines are ill-suited to fit discontinuities). # # The number of splines used to fit a band is determined by the # number of branches (high symmetry lines) defined in the # BandStructureSymmLine object (see BandStructureSymmLine._branches). warning = "WARNING! Distance / branch {d}, band {i} cannot be " + \ "interpolated.\n" + \ "See full warning in source.\n" + \ "If this is not a mistake, try increasing " + \ "smooth_tol.\nCurrent smooth_tol is {s}." for d in range(len(data['distances'])): for i in range(self._nb_bands): tck = scint.splrep( data['distances'][d], [data['energy'][d][str(Spin.up)][i][j] for j in range(len(data['distances'][d]))], s=smooth_tol) step = (data['distances'][d][-1] - data['distances'][d][0]) / 1000 xs = [x * step + data['distances'][d][0] for x in range(1000)] ys = [scint.splev(x * step + data['distances'][d][0], tck, der=0) for x in range(1000)] for y in ys: if np.isnan(y): print(warning.format(d=str(d), i=str(i), s=str(smooth_tol))) break plt.plot(xs, ys, 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: tck = scint.splrep( data['distances'][d], [data['energy'][d][str(Spin.down)][i][j] for j in range(len(data['distances'][d]))], s=smooth_tol) step = (data['distances'][d][-1] - data['distances'][d][0]) / 1000 xs = [x * step + data['distances'][d][0] for x in range(1000)] ys = [scint.splev( x * step + data['distances'][d][0], tck, der=0) for x in range(1000)] for y in ys: if np.isnan(y): print(warning.format(d=str(d), i=str(i), s=str(smooth_tol))) break plt.plot(xs, ys, 'r--', linewidth=band_linewidth) self._maketicks(plt) # Main X and Y Labels plt.xlabel(r'$\mathrm{Wave\ Vector}$', fontsize=30) ylabel = r'$\mathrm{E\ -\ E_f\ (eV)}$' if zero_to_efermi \ else r'$\mathrm{Energy\ (eV)}$' plt.ylabel(ylabel, fontsize=30) # Draw Fermi energy, only if not the zero if not zero_to_efermi: ef = self._bs.efermi plt.axhline(ef, linewidth=2, color='k') # X range (K) # last distance point x_max = data['distances'][-1][-1] plt.xlim(0, x_max) if ylim is None: if self._bs.is_metal(): # Plot A Metal if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs.efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) if not self._bs.is_metal() and vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.tight_layout() return plt def show(self, zero_to_efermi=True, ylim=None, smooth=False, smooth_tol=None): """ Show the plot using matplotlib. Args: zero_to_efermi: Automatically subtract off the Fermi energy from the eigenvalues and plot (E-Ef). ylim: Specify the y-axis (energy) limits; by default None let the code choose. It is vbm-4 and cbm+4 if insulator efermi-10 and efermi+10 if metal smooth: interpolates the bands by a spline cubic smooth_tol (float) : tolerance for fitting spline to band data. Default is None such that no tolerance will be used. """ plt = self.get_plot(zero_to_efermi, ylim, smooth) plt.show() def save_plot(self, filename, img_format="eps", ylim=None, zero_to_efermi=True, smooth=False): """ Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. """ plt = self.get_plot(ylim=ylim, zero_to_efermi=zero_to_efermi, smooth=smooth) plt.savefig(filename, format=img_format) plt.close() def get_ticks(self): """ Get all ticks and labels for a band structure plot. Returns: dict: A dictionary with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """ tick_distance = [] tick_labels = [] previous_label = self._bs.kpoints[0].label previous_branch = self._bs.branches[0]['name'] for i, c in enumerate(self._bs.kpoints): if c.label is not None: tick_distance.append(self._bs.distance[i]) this_branch = None for b in self._bs.branches: if b['start_index'] <= i <= b['end_index']: this_branch = b['name'] break if c.label != previous_label \ and previous_branch != this_branch: label1 = c.label if label1.startswith("\\") or label1.find("_") != -1: label1 = "$" + label1 + "$" label0 = previous_label if label0.startswith("\\") or label0.find("_") != -1: label0 = "$" + label0 + "$" tick_labels.pop() tick_distance.pop() tick_labels.append(label0 + "$\\mid$" + label1) else: if c.label.startswith("\\") or c.label.find("_") != -1: tick_labels.append("$" + c.label + "$") else: tick_labels.append(c.label) previous_label = c.label previous_branch = this_branch return {'distance': tick_distance, 'label': tick_labels} def plot_compare(self, other_plotter, legend=True): """ plot two band structure for comparison. One is in red the other in blue (no difference in spins). The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the BSPlotter Args: another band structure object defined along the same symmetry lines Returns: a matplotlib object with both band structures """ # TODO: add exception if the band structures are not compatible import matplotlib.lines as mlines plt = self.get_plot() data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() band_linewidth = 1 for i in range(other_plotter._nb_bands): for d in range(len(data_orig['distances'])): plt.plot(data_orig['distances'][d], [e[str(Spin.up)][i] for e in data['energy']][d], 'c-', linewidth=band_linewidth) if other_plotter._bs.is_spin_polarized: plt.plot(data_orig['distances'][d], [e[str(Spin.down)][i] for e in data['energy']][d], 'm--', linewidth=band_linewidth) if legend: handles = [mlines.Line2D([], [], linewidth=2, color='b', label='bs 1 up'), mlines.Line2D([], [], linewidth=2, color='r', label='bs 1 down', linestyle="--"), mlines.Line2D([], [], linewidth=2, color='c', label='bs 2 up'), mlines.Line2D([], [], linewidth=2, color='m', linestyle="--", label='bs 2 down')] plt.legend(handles=handles) return plt def plot_brillouin(self): """ plot the Brillouin zone """ # get labels and lines labels = {} for k in self._bs.kpoints: if k.label: labels[k.label] = k.frac_coords lines = [] for b in self._bs.branches: lines.append([self._bs.kpoints[b['start_index']].frac_coords, self._bs.kpoints[b['end_index']].frac_coords]) plot_brillouin_zone(self._bs.lattice_rec, lines=lines, labels=labels) class BSPlotterProjected(BSPlotter): """ Class to plot or get data to facilitate the plot of band structure objects projected along orbitals, elements or sites. Args: bs: A BandStructureSymmLine object with projections. """ def __init__(self, bs): if len(bs.projections) == 0: raise ValueError("try to plot projections" " on a band structure without any") super(BSPlotterProjected, self).__init__(bs) def _get_projections_by_branches(self, dictio): proj = self._bs.get_projections_on_elements_and_orbitals(dictio) proj_br = [] for b in self._bs.branches: if self._bs.is_spin_polarized: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)], str(Spin.down): [[] for l in range(self._nb_bands)]}) else: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)]}) for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): proj_br[-1][str(Spin.up)][i].append( {e: {o: proj[Spin.up][i][j][e][o] for o in proj[Spin.up][i][j][e]} for e in proj[Spin.up][i][j]}) if self._bs.is_spin_polarized: for b in self._bs.branches: for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): proj_br[-1][str(Spin.down)][i].append( {e: {o: proj[Spin.down][i][j][e][o] for o in proj[Spin.down][i][j][e]} for e in proj[Spin.down][i][j]}) return proj_br def get_projected_plots_dots(self, dictio, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False): """ Method returning a plot composed of subplots along different elements and orbitals. Args: dictio: The element and orbitals you want a projection on. The format is {Element:[Orbitals]} for instance {'Cu':['d','s'],'O':['p']} will give projections for Cu on d and s orbitals and on oxygen p. Returns: a pylab object with different subfigures for each projection The blue and red colors are for spin up and spin down. The bigger the red or blue dot in the band structure the higher character for the corresponding element and orbital. """ band_linewidth = 1.0 fig_number = sum([len(v) for v in dictio.values()]) proj = self._get_projections_by_branches(dictio) data = self.bs_plot_data(zero_to_efermi) plt = pretty_plot(12, 8) e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 count = 1 for el in dictio: for o in dictio[el]: plt.subplot(100 * math.ceil(fig_number / 2) + 20 + count) self._maketicks(plt) for b in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][b], [data['energy'][b][str(Spin.up)][i][j] for j in range(len(data['distances'][b]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][b], [data['energy'][b][str(Spin.down)][i][j] for j in range(len(data['distances'][b]))], 'r--', linewidth=band_linewidth) for j in range( len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.down)][i][ j], 'ro', markersize= proj[b][str(Spin.down)][i][j][str(el)][ o] * 15.0) for j in range(len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.up)][i][j], 'bo', markersize= proj[b][str(Spin.up)][i][j][str(el)][ o] * 15.0) if ylim is None: if self._bs.is_metal(): if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs.efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.title(str(el) + " " + str(o)) count += 1 return plt def get_elt_projected_plots(self, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False): """ Method returning a plot composed of subplots along different elements Returns: a pylab object with different subfigures for each projection The blue and red colors are for spin up and spin down The bigger the red or blue dot in the band structure the higher character for the corresponding element and orbital """ band_linewidth = 1.0 proj = self._get_projections_by_branches({e.symbol: ['s', 'p', 'd'] for e in self._bs.structure.composition.elements}) data = self.bs_plot_data(zero_to_efermi) plt = pretty_plot(12, 8) e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 count = 1 for el in self._bs.structure.composition.elements: plt.subplot(220 + count) self._maketicks(plt) for b in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][b], [data['energy'][b][str(Spin.up)][i][j] for j in range(len(data['distances'][b]))], '-', color=[192 / 255, 192 / 255, 192 / 255], linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(data['distances'][b], [data['energy'][b][str(Spin.down)][i][j] for j in range(len(data['distances'][b]))], '--', color=[128 / 255, 128 / 255, 128 / 255], linewidth=band_linewidth) for j in range(len(data['energy'][b][str(Spin.up)][i])): markerscale = sum([proj[b][str(Spin.down)][i][ j][str(el)][o] for o in proj[b] [str(Spin.down)][i][j][ str(el)]]) plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.down)][i][j], 'bo', markersize=markerscale * 15.0, color=[markerscale, 0.3 * markerscale, 0.4 * markerscale]) for j in range(len(data['energy'][b][str(Spin.up)][i])): markerscale = sum( [proj[b][str(Spin.up)][i][j][str(el)][o] for o in proj[b] [str(Spin.up)][i][j][str(el)]]) plt.plot(data['distances'][b][j], data['energy'][b][str(Spin.up)][i][j], 'o', markersize=markerscale * 15.0, color=[markerscale, 0.3 * markerscale, 0.4 * markerscale]) if ylim is None: if self._bs.is_metal(): if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs.efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.title(str(el)) count += 1 return plt def get_elt_projected_plots_color(self, zero_to_efermi=True, elt_ordered=None): """ returns a pylab plot object with one plot where the band structure line color depends on the character of the band (along different elements). Each element is associated with red, green or blue and the corresponding rgb color depending on the character of the band is used. The method can only deal with binary and ternary compounds spin up and spin down are differientiated by a '-' and a '--' line Args: elt_ordered: A list of Element ordered. The first one is red, second green, last blue Returns: a pylab object """ band_linewidth = 3.0 if len(self._bs.structure.composition.elements) > 3: raise ValueError if elt_ordered is None: elt_ordered = self._bs.structure.composition.elements proj = self._get_projections_by_branches( {e.symbol: ['s', 'p', 'd'] for e in self._bs.structure.composition.elements}) data = self.bs_plot_data(zero_to_efermi) plt = pretty_plot(12, 8) spins = [Spin.up] if self._bs.is_spin_polarized: spins = [Spin.up, Spin.down] self._maketicks(plt) for s in spins: for b in range(len(data['distances'])): for i in range(self._nb_bands): for j in range(len(data['energy'][b][str(s)][i]) - 1): sum_e = 0.0 for el in elt_ordered: sum_e = sum_e + \ sum([proj[b][str(s)][i][j][str(el)][o] for o in proj[b][str(s)][i][j][str(el)]]) if sum_e == 0.0: color = [0.0] * len(elt_ordered) else: color = [sum([proj[b][str(s)][i][j][str(el)][o] for o in proj[b][str(s)][i][j][str(el)]]) / sum_e for el in elt_ordered] if len(color) == 2: color.append(0.0) color[2] = color[1] color[1] = 0.0 sign = '-' if s == Spin.down: sign = '--' plt.plot([data['distances'][b][j], data['distances'][b][j + 1]], [data['energy'][b][str(s)][i][j], data['energy'][b][str(s)][i][j + 1]], sign, color=color, linewidth=band_linewidth) if self._bs.is_metal(): if zero_to_efermi: e_min = -10 e_max = 10 plt.ylim(e_min, e_max) plt.ylim(self._bs.efermi + e_min, self._bs.efermi + e_max) else: plt.ylim(data['vbm'][0][1] - 4.0, data['cbm'][0][1] + 2.0) return plt def _get_projections_by_branches_patom_pmorb(self, dictio, dictpa, sum_atoms, sum_morbs, selected_branches): import copy setos = {'s': 0, 'py': 1, 'pz': 2, 'px': 3, 'dxy': 4, 'dyz': 5, 'dz2': 6, 'dxz': 7, 'dx2': 8, 'f_3': 9, 'f_2': 10, 'f_1': 11, 'f0': 12, 'f1': 13, 'f2': 14, 'f3': 15} num_branches = len(self._bs.branches) if selected_branches is not None: indices = [] if not isinstance(selected_branches, list): raise TypeError( "You do not give a correct type of 'selected_branches'. It should be 'list' type.") elif len(selected_branches) == 0: raise ValueError( "The 'selected_branches' is empty. We cannot do anything.") else: for index in selected_branches: if not isinstance(index, int): raise ValueError( "You do not give a correct type of index of symmetry lines. It should be " "'int' type") elif index > num_branches or index < 1: raise ValueError( "You give a incorrect index of symmetry lines: %s. The index should be in " "range of [1, %s]." % ( str(index), str(num_branches))) else: indices.append(index - 1) else: indices = range(0, num_branches) proj = self._bs.projections proj_br = [] for index in indices: b = self._bs.branches[index] print(b) if self._bs.is_spin_polarized: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)], str(Spin.down): [[] for l in range(self._nb_bands)]}) else: proj_br.append( {str(Spin.up): [[] for l in range(self._nb_bands)]}) for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): edict = {} for elt in dictpa: for anum in dictpa[elt]: edict[elt + str(anum)] = {} for morb in dictio[elt]: edict[elt + str(anum)][morb] = \ proj[Spin.up][i][j][setos[morb]][anum - 1] proj_br[-1][str(Spin.up)][i].append(edict) if self._bs.is_spin_polarized: for i in range(self._nb_bands): for j in range(b['start_index'], b['end_index'] + 1): edict = {} for elt in dictpa: for anum in dictpa[elt]: edict[elt + str(anum)] = {} for morb in dictio[elt]: edict[elt + str(anum)][morb] = \ proj[Spin.up][i][j][setos[morb]][anum - 1] proj_br[-1][str(Spin.down)][i].append(edict) # Adjusting projections for plot dictio_d, dictpa_d = self._summarize_keys_for_plot(dictio, dictpa, sum_atoms, sum_morbs) print('dictio_d: %s' % str(dictio_d)) print('dictpa_d: %s' % str(dictpa_d)) if (sum_atoms is None) and (sum_morbs is None): proj_br_d = copy.deepcopy(proj_br) else: proj_br_d = [] branch = -1 for index in indices: branch += 1 br = self._bs.branches[index] if self._bs.is_spin_polarized: proj_br_d.append( {str(Spin.up): [[] for l in range(self._nb_bands)], str(Spin.down): [[] for l in range(self._nb_bands)]}) else: proj_br_d.append( {str(Spin.up): [[] for l in range(self._nb_bands)]}) if (sum_atoms is not None) and (sum_morbs is None): for i in range(self._nb_bands): for j in range(br['end_index'] - br['start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.up)][i][j]) edict = {} for elt in dictpa: if elt in sum_atoms: for anum in dictpa_d[elt][:-1]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio[elt]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) proj_br_d[-1][str(Spin.up)][i].append(edict) if self._bs.is_spin_polarized: for i in range(self._nb_bands): for j in range(br['end_index'] - br[ 'start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.down)][i][j]) edict = {} for elt in dictpa: if elt in sum_atoms: for anum in dictpa_d[elt][:-1]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio[elt]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][ morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) proj_br_d[-1][str(Spin.down)][i].append(edict) elif (sum_atoms is None) and (sum_morbs is not None): for i in range(self._nb_bands): for j in range(br['end_index'] - br['start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.up)][i][j]) edict = {} for elt in dictpa: if elt in sum_morbs: for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) proj_br_d[-1][str(Spin.up)][i].append(edict) if self._bs.is_spin_polarized: for i in range(self._nb_bands): for j in range(br['end_index'] - br[ 'start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.down)][i][j]) edict = {} for elt in dictpa: if elt in sum_morbs: for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) proj_br_d[-1][str(Spin.down)][i].append(edict) else: for i in range(self._nb_bands): for j in range(br['end_index'] - br['start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.up)][i][j]) edict = {} for elt in dictpa: if (elt in sum_atoms) and (elt in sum_morbs): for anum in dictpa_d[elt][:-1]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio_d[elt][:-1]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection sprojection = 0.0 for anum in sum_atoms[elt]: for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + str(anum)][morb] edict[elt + dictpa_d[elt][-1]][ dictio_d[elt][-1]] = sprojection elif (elt in sum_atoms) and ( elt not in sum_morbs): for anum in dictpa_d[elt][:-1]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio[elt]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection elif (elt not in sum_atoms) and ( elt in sum_morbs): for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] proj_br_d[-1][str(Spin.up)][i].append(edict) if self._bs.is_spin_polarized: for i in range(self._nb_bands): for j in range(br['end_index'] - br[ 'start_index'] + 1): atoms_morbs = copy.deepcopy( proj_br[branch][str(Spin.down)][i][j]) edict = {} for elt in dictpa: if (elt in sum_atoms) and ( elt in sum_morbs): for anum in dictpa_d[elt][:-1]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio_d[elt][:-1]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][ morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection sprojection = 0.0 for anum in sum_atoms[elt]: for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + str(anum)][ morb] edict[elt + dictpa_d[elt][-1]][ dictio_d[elt][-1]] = sprojection elif (elt in sum_atoms) and ( elt not in sum_morbs): for anum in dictpa_d[elt][:-1]: edict[elt + anum] = copy.deepcopy( atoms_morbs[elt + anum]) edict[elt + dictpa_d[elt][-1]] = {} for morb in dictio[elt]: sprojection = 0.0 for anum in sum_atoms[elt]: sprojection += \ atoms_morbs[elt + str(anum)][ morb] edict[elt + dictpa_d[elt][-1]][ morb] = sprojection elif (elt not in sum_atoms) and ( elt in sum_morbs): for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt][:-1]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] sprojection = 0.0 for morb in sum_morbs[elt]: sprojection += \ atoms_morbs[elt + anum][morb] edict[elt + anum][ dictio_d[elt][-1]] = sprojection else: for anum in dictpa_d[elt]: edict[elt + anum] = {} for morb in dictio_d[elt]: edict[elt + anum][morb] = \ atoms_morbs[elt + anum][morb] proj_br_d[-1][str(Spin.down)][i].append(edict) return proj_br_d, dictio_d, dictpa_d, indices def get_projected_plots_dots_patom_pmorb(self, dictio, dictpa, sum_atoms=None, sum_morbs=None, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False, selected_branches=None, w_h_size=(12, 8), num_column=None): """ Method returns a plot composed of subplots for different atoms and orbitals (subshell orbitals such as 's', 'p', 'd' and 'f' defined by azimuthal quantum numbers l = 0, 1, 2 and 3, respectively or individual orbitals like 'px', 'py' and 'pz' defined by magnetic quantum numbers m = -1, 1 and 0, respectively). This is an extension of "get_projected_plots_dots" method. Args: dictio: The elements and the orbitals you need to project on. The format is {Element:[Orbitals]}, for instance: {'Cu':['dxy','s','px'],'O':['px','py','pz']} will give projections for Cu on orbitals dxy, s, px and for O on orbitals px, py, pz. If you want to sum over all individual orbitals of subshell orbitals, for example, 'px', 'py' and 'pz' of O, just simply set {'Cu':['dxy','s','px'],'O':['p']} and set sum_morbs (see explanations below) as {'O':[p],...}. Otherwise, you will get an error. dictpa: The elements and their sites (defined by site numbers) you need to project on. The format is {Element: [Site numbers]}, for instance: {'Cu':[1,5],'O':[3,4]} will give projections for Cu on site-1 and on site-5, O on site-3 and on site-4 in the cell. Attention: The correct site numbers of atoms are consistent with themselves in the structure computed. Normally, the structure should be totally similar with POSCAR file, however, sometimes VASP can rotate or translate the cell. Thus, it would be safe if using Vasprun class to get the final_structure and as a result, correct index numbers of atoms. sum_atoms: Sum projection of the similar atoms together (e.g.: Cu on site-1 and Cu on site-5). The format is {Element: [Site numbers]}, for instance: {'Cu': [1,5], 'O': [3,4]} means summing projections over Cu on site-1 and Cu on site-5 and O on site-3 and on site-4. If you do not want to use this functional, just turn it off by setting sum_atoms = None. sum_morbs: Sum projections of individual orbitals of similar atoms together (e.g.: 'dxy' and 'dxz'). The format is {Element: [individual orbitals]}, for instance: {'Cu': ['dxy', 'dxz'], 'O': ['px', 'py']} means summing projections over 'dxy' and 'dxz' of Cu and 'px' and 'py' of O. If you do not want to use this functional, just turn it off by setting sum_morbs = None. selected_branches: The index of symmetry lines you chose for plotting. This can be useful when the number of symmetry lines (in KPOINTS file) are manny while you only want to show for certain ones. The format is [index of line], for instance: [1, 3, 4] means you just need to do projection along lines number 1, 3 and 4 while neglecting lines number 2 and so on. By default, this is None type and all symmetry lines will be plotted. w_h_size: This variable help you to control the width and height of figure. By default, width = 12 and height = 8 (inches). The width/height ratio is kept the same for subfigures and the size of each depends on how many number of subfigures are plotted. num_column: This variable help you to manage how the subfigures are arranged in the figure by setting up the number of columns of subfigures. The value should be an int number. For example, num_column = 3 means you want to plot subfigures in 3 columns. By default, num_column = None and subfigures are aligned in 2 columns. Returns: A pylab object with different subfigures for different projections. The blue and red colors lines are bands for spin up and spin down. The green and cyan dots are projections for spin up and spin down. The bigger the green or cyan dots in the projected band structures, the higher character for the corresponding elements and orbitals. List of individual orbitals and their numbers (set up by VASP and no special meaning): s = 0; py = 1 pz = 2 px = 3; dxy = 4 dyz = 5 dz2 = 6 dxz = 7 dx2 = 8; f_3 = 9 f_2 = 10 f_1 = 11 f0 = 12 f1 = 13 f2 = 14 f3 = 15 """ dictio, sum_morbs = self._Orbitals_SumOrbitals(dictio, sum_morbs) dictpa, sum_atoms, number_figs = self._number_of_subfigures(dictio, dictpa, sum_atoms, sum_morbs) print('Number of subfigures: %s' % str(number_figs)) if number_figs > 9: print( "The number of sub-figures %s might be too manny and the implementation might take a long time.\n" "A smaller number or a plot with selected symmetry lines (selected_branches) might be better.\n" % str(number_figs)) import math from pymatgen.util.plotting import pretty_plot band_linewidth = 0.5 plt = pretty_plot(w_h_size[0], w_h_size[1]) proj_br_d, dictio_d, dictpa_d, branches = self._get_projections_by_branches_patom_pmorb( dictio, dictpa, sum_atoms, sum_morbs, selected_branches) data = self.bs_plot_data(zero_to_efermi) e_min = -4 e_max = 4 if self._bs.is_metal(): e_min = -10 e_max = 10 count = 0 for elt in dictpa_d: for numa in dictpa_d[elt]: for o in dictio_d[elt]: count += 1 if num_column is None: if number_figs == 1: plt.subplot(1, 1, 1) else: row = number_figs / 2 if number_figs % 2 == 0: plt.subplot(row, 2, count) else: plt.subplot(row + 1, 2, count) elif isinstance(num_column, int): row = number_figs / num_column if number_figs % num_column == 0: plt.subplot(row, num_column, count) else: plt.subplot(row + 1, num_column, count) else: raise ValueError( "The invalid 'num_column' is assigned. It should be an integer.") plt, shift = self._maketicks_selected(plt, branches) br = -1 for b in branches: br += 1 for i in range(self._nb_bands): plt.plot(list(map(lambda x: x - shift[br], data['distances'][b])), [data['energy'][b][str(Spin.up)][i][j] for j in range(len(data['distances'][b]))], 'b-', linewidth=band_linewidth) if self._bs.is_spin_polarized: plt.plot(list(map(lambda x: x - shift[br], data['distances'][b])), [data['energy'][b][str(Spin.down)][i][ j] for j in range(len(data['distances'][b]))], 'r--', linewidth=band_linewidth) for j in range(len( data['energy'][b][str(Spin.up)][i])): plt.plot( data['distances'][b][j] - shift[br], data['energy'][b][str(Spin.down)][i][j], 'co', markersize= \ proj_br_d[br][str(Spin.down)][i][j][ elt + numa][o] * 15.0) for j in range( len(data['energy'][b][str(Spin.up)][i])): plt.plot(data['distances'][b][j] - shift[br], data['energy'][b][str(Spin.up)][i][j], 'go', markersize= \ proj_br_d[br][str(Spin.up)][i][j][ elt + numa][o] * 15.0) if ylim is None: if self._bs.is_metal(): if zero_to_efermi: plt.ylim(e_min, e_max) else: plt.ylim(self._bs.efermi + e_min, self._bs._efermi + e_max) else: if vbm_cbm_marker: for cbm in data['cbm']: plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100) for vbm in data['vbm']: plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100) plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max) else: plt.ylim(ylim) plt.title(elt + " " + numa + " " + str(o)) return plt def _Orbitals_SumOrbitals(self, dictio, sum_morbs): all_orbitals = ['s', 'p', 'd', 'f', 'px', 'py', 'pz', 'dxy', 'dyz', 'dxz', 'dx2', 'dz2', 'f_3', 'f_2', 'f_1', 'f0', 'f1', 'f2', 'f3'] individual_orbs = {'p': ['px', 'py', 'pz'], 'd': ['dxy', 'dyz', 'dxz', 'dx2', 'dz2'], 'f': ['f_3', 'f_2', 'f_1', 'f0', 'f1', 'f2', 'f3']} if not isinstance(dictio, dict): raise TypeError( "The invalid type of 'dictio' was bound. It should be dict type.") elif len(dictio.keys()) == 0: raise KeyError("The 'dictio' is empty. We cannot do anything.") else: for elt in dictio: if Element.is_valid_symbol(elt): if isinstance(dictio[elt], list): if len(dictio[elt]) == 0: raise ValueError( "The dictio[%s] is empty. We cannot do anything" % elt) for orb in dictio[elt]: if not isinstance(orb, six.string_types): raise ValueError( "The invalid format of orbitals is in 'dictio[%s]': %s. " "They should be string." % (elt, str(orb))) elif orb not in all_orbitals: raise ValueError( "The invalid name of orbital is given in 'dictio[%s]'." % elt) else: if orb in individual_orbs.keys(): if len(set(dictio[elt]).intersection( individual_orbs[orb])) != 0: raise ValueError( "The 'dictio[%s]' contains orbitals repeated." % elt) nelems = Counter(dictio[elt]).values() if sum(nelems) > len(nelems): raise ValueError( "You put in at least two similar orbitals in dictio[%s]." % elt) else: raise TypeError( "The invalid type of value was put into 'dictio[%s]'. It should be list " "type." % elt) else: raise KeyError( "The invalid element was put into 'dictio' as a key: %s" % elt) if sum_morbs is None: print("You do not want to sum projection over orbitals.") elif not isinstance(sum_morbs, dict): raise TypeError( "The invalid type of 'sum_orbs' was bound. It should be dict or 'None' type.") elif len(sum_morbs.keys()) == 0: raise KeyError("The 'sum_morbs' is empty. We cannot do anything") else: for elt in sum_morbs: if Element.is_valid_symbol(elt): if isinstance(sum_morbs[elt], list): for orb in sum_morbs[elt]: if not isinstance(orb, six.string_types): raise TypeError( "The invalid format of orbitals is in 'sum_morbs[%s]': %s. " "They should be string." % (elt, str(orb))) elif orb not in all_orbitals: raise ValueError( "The invalid name of orbital in 'sum_morbs[%s]' is given." % elt) else: if orb in individual_orbs.keys(): if len(set(sum_morbs[elt]).intersection( individual_orbs[orb])) != 0: raise ValueError( "The 'sum_morbs[%s]' contains orbitals repeated." % elt) nelems = Counter(sum_morbs[elt]).values() if sum(nelems) > len(nelems): raise ValueError( "You put in at least two similar orbitals in sum_morbs[%s]." % elt) else: raise TypeError( "The invalid type of value was put into 'sum_morbs[%s]'. It should be list " "type." % elt) if elt not in dictio.keys(): raise ValueError( "You cannot sum projection over orbitals of atoms '%s' because they are not " "mentioned in 'dictio'." % elt) else: raise KeyError( "The invalid element was put into 'sum_morbs' as a key: %s" % elt) for elt in dictio: if len(dictio[elt]) == 1: if len(dictio[elt][0]) > 1: if elt in sum_morbs.keys(): raise ValueError( "You cannot sum projection over one individual orbital '%s' of '%s'." % (dictio[elt][0], elt)) else: if sum_morbs is None: pass elif elt not in sum_morbs.keys(): print( "You do not want to sum projection over orbitals of element: %s" % elt) else: if len(sum_morbs[elt]) == 0: raise ValueError( "The empty list is an invalid value for sum_morbs[%s]." % elt) elif len(sum_morbs[elt]) > 1: for orb in sum_morbs[elt]: if dictio[elt][0] not in orb: raise ValueError( "The invalid orbital '%s' was put into 'sum_morbs[%s]'." % (orb, elt)) else: if orb == 's' or len(orb) > 1: raise ValueError( "The invalid orbital '%s' was put into sum_orbs['%s']." % ( orb, elt)) else: sum_morbs[elt] = individual_orbs[dictio[elt][0]] dictio[elt] = individual_orbs[dictio[elt][0]] else: duplicate = copy.deepcopy(dictio[elt]) for orb in dictio[elt]: if orb in individual_orbs.keys(): duplicate.remove(orb) for o in individual_orbs[orb]: duplicate.append(o) dictio[elt] = copy.deepcopy(duplicate) if sum_morbs is None: pass elif elt not in sum_morbs.keys(): print( "You do not want to sum projection over orbitals of element: %s" % elt) else: if len(sum_morbs[elt]) == 0: raise ValueError( "The empty list is an invalid value for sum_morbs[%s]." % elt) elif len(sum_morbs[elt]) == 1: orb = sum_morbs[elt][0] if orb == 's': raise ValueError( "We do not sum projection over only 's' orbital of the same " "type of element.") elif orb in individual_orbs.keys(): sum_morbs[elt].pop(0) for o in individual_orbs[orb]: sum_morbs[elt].append(o) else: raise ValueError( "You never sum projection over one orbital in sum_morbs[%s]" % elt) else: duplicate = copy.deepcopy(sum_morbs[elt]) for orb in sum_morbs[elt]: if orb in individual_orbs.keys(): duplicate.remove(orb) for o in individual_orbs[orb]: duplicate.append(o) sum_morbs[elt] = copy.deepcopy(duplicate) for orb in sum_morbs[elt]: if orb not in dictio[elt]: raise ValueError( "The orbitals of sum_morbs[%s] conflict with those of dictio[%s]." % (elt, elt)) return dictio, sum_morbs def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): from pymatgen.core.periodic_table import Element from collections import Counter if (not isinstance(dictpa, dict)): raise TypeError( "The invalid type of 'dictpa' was bound. It should be dict type.") elif len(dictpa.keys()) == 0: raise KeyError("The 'dictpa' is empty. We cannot do anything.") else: for elt in dictpa: if Element.is_valid_symbol(elt): if isinstance(dictpa[elt], list): if len(dictpa[elt]) == 0: raise ValueError( "The dictpa[%s] is empty. We cannot do anything" % elt) _sites = self._bs.structure.sites indices = [] for i in range(0, len(_sites)): if list(_sites[i]._species.keys())[0].__eq__( Element(elt)): indices.append(i + 1) for number in dictpa[elt]: if isinstance(number, str): if 'all' == number.lower(): dictpa[elt] = indices print( "You want to consider all '%s' atoms." % elt) break else: raise ValueError( "You put wrong site numbers in 'dictpa[%s]': %s." % (elt, str(number))) elif isinstance(number, int): if number not in indices: raise ValueError( "You put wrong site numbers in 'dictpa[%s]': %s." % (elt, str(number))) else: raise ValueError( "You put wrong site numbers in 'dictpa[%s]': %s." % ( elt, str(number))) nelems = Counter(dictpa[elt]).values() if sum(nelems) > len(nelems): raise ValueError( "You put at least two similar site numbers into 'dictpa[%s]'." % elt) else: raise TypeError( "The invalid type of value was put into 'dictpa[%s]'. It should be list " "type." % elt) else: raise KeyError( "The invalid element was put into 'dictpa' as a key: %s" % elt) if len(list(dictio.keys())) != len(list(dictpa.keys())): raise KeyError( "The number of keys in 'dictio' and 'dictpa' are not the same.") else: for elt in dictio.keys(): if elt not in dictpa.keys(): raise KeyError( "The element '%s' is not in both dictpa and dictio." % elt) for elt in dictpa.keys(): if elt not in dictio.keys(): raise KeyError( "The element '%s' in not in both dictpa and dictio." % elt) if sum_atoms is None: print("You do not want to sum projection over atoms.") elif (not isinstance(sum_atoms, dict)): raise TypeError( "The invalid type of 'sum_atoms' was bound. It should be dict type.") elif len(sum_atoms.keys()) == 0: raise KeyError("The 'sum_atoms' is empty. We cannot do anything.") else: for elt in sum_atoms: if Element.is_valid_symbol(elt): if isinstance(sum_atoms[elt], list): if len(sum_atoms[elt]) == 0: raise ValueError( "The sum_atoms[%s] is empty. We cannot do anything" % elt) _sites = self._bs.structure.sites indices = [] for i in range(0, len(_sites)): if list(_sites[i]._species.keys())[0].__eq__( Element(elt)): indices.append(i + 1) for number in sum_atoms[elt]: if isinstance(number, str): if 'all' == number.lower(): sum_atoms[elt] = indices print( "You want to sum projection over all '%s' atoms." % elt) break else: raise ValueError( "You put wrong site numbers in 'sum_atoms[%s]'." % elt) elif isinstance(number, int): if number not in indices: raise ValueError( "You put wrong site numbers in 'sum_atoms[%s]'." % elt) elif number not in dictpa[elt]: raise ValueError( "You cannot sum projection with atom number '%s' because it is not " "metioned in dicpta[%s]" % ( str(number), elt)) else: raise ValueError( "You put wrong site numbers in 'sum_atoms[%s]'." % elt) nelems = Counter(sum_atoms[elt]).values() if sum(nelems) > len(nelems): raise ValueError( "You put at least two similar site numbers into 'sum_atoms[%s]'." % elt) else: raise TypeError( "The invalid type of value was put into 'sum_atoms[%s]'. It should be list " "type." % elt) if elt not in dictpa.keys(): raise ValueError( "You cannot sum projection over atoms '%s' because it is not " "mentioned in 'dictio'." % elt) else: raise KeyError( "The invalid element was put into 'sum_atoms' as a key: %s" % elt) if len(sum_atoms[elt]) == 1: raise ValueError( "We do not sum projection over only one atom: %s" % elt) max_number_figs = 0 decrease = 0 for elt in dictio: max_number_figs += len(dictio[elt]) * len(dictpa[elt]) if (sum_atoms is None) and (sum_morbs is None): number_figs = max_number_figs elif (sum_atoms is not None) and (sum_morbs is None): for elt in sum_atoms: decrease += (len(sum_atoms[elt]) - 1) * len(dictio[elt]) number_figs = max_number_figs - decrease elif (sum_atoms is None) and (sum_morbs is not None): for elt in sum_morbs: decrease += (len(sum_morbs[elt]) - 1) * len(dictpa[elt]) number_figs = max_number_figs - decrease elif (sum_atoms is not None) and (sum_morbs is not None): for elt in sum_atoms: decrease += (len(sum_atoms[elt]) - 1) * len(dictio[elt]) for elt in sum_morbs: if elt in sum_atoms: decrease += (len(sum_morbs[elt]) - 1) * ( len(dictpa[elt]) - len(sum_atoms[elt]) + 1) else: decrease += (len(sum_morbs[elt]) - 1) * len(dictpa[elt]) number_figs = max_number_figs - decrease else: raise ValueError("Invalid format of 'sum_atoms' and 'sum_morbs'.") return dictpa, sum_atoms, number_figs def _summarize_keys_for_plot(self, dictio, dictpa, sum_atoms, sum_morbs): from pymatgen.core.periodic_table import Element individual_orbs = {'p': ['px', 'py', 'pz'], 'd': ['dxy', 'dyz', 'dxz', 'dx2', 'dz2'], 'f': ['f_3', 'f_2', 'f_1', 'f0', 'f1', 'f2', 'f3']} def number_label(list_numbers): list_numbers = sorted(list_numbers) divide = [[]] divide[0].append(list_numbers[0]) group = 0 for i in range(1, len(list_numbers)): if list_numbers[i] == list_numbers[i - 1] + 1: divide[group].append(list_numbers[i]) else: group += 1 divide.append([list_numbers[i]]) label = "" for elem in divide: if len(elem) > 1: label += str(elem[0]) + "-" + str(elem[-1]) + "," else: label += str(elem[0]) + "," return label[:-1] def orbital_label(list_orbitals): divide = {} for orb in list_orbitals: if orb[0] in divide: divide[orb[0]].append(orb) else: divide[orb[0]] = [] divide[orb[0]].append(orb) label = "" for elem in divide: if elem == 's': label += "s" + "," else: if len(divide[elem]) == len(individual_orbs[elem]): label += elem + "," else: l = [o[1:] for o in divide[elem]] label += elem + str(l).replace("['", "").replace("']", "").replace( "', '", "-") + "," return label[:-1] if (sum_atoms is None) and (sum_morbs is None): dictio_d = dictio dictpa_d = {elt: [str(anum) for anum in dictpa[elt]] for elt in dictpa} elif (sum_atoms is not None) and (sum_morbs is None): dictio_d = dictio dictpa_d = {} for elt in dictpa: dictpa_d[elt] = [] if elt in sum_atoms: _sites = self._bs.structure.sites indices = [] for i in range(0, len(_sites)): if _sites[i]._species.keys()[0].__eq__(Element(elt)): indices.append(i + 1) flag_1 = len(set(dictpa[elt]).intersection(indices)) flag_2 = len(set(sum_atoms[elt]).intersection(indices)) if flag_1 == len(indices) and flag_2 == len(indices): dictpa_d[elt].append('all') else: for anum in dictpa[elt]: if anum not in sum_atoms[elt]: dictpa_d[elt].append(str(anum)) label = number_label(sum_atoms[elt]) dictpa_d[elt].append(label) else: for anum in dictpa[elt]: dictpa_d[elt].append(str(anum)) elif (sum_atoms is None) and (sum_morbs is not None): dictio_d = {} for elt in dictio: dictio_d[elt] = [] if elt in sum_morbs: for morb in dictio[elt]: if morb not in sum_morbs[elt]: dictio_d[elt].append(morb) label = orbital_label(sum_morbs[elt]) dictio_d[elt].append(label) else: dictio_d[elt] = dictio[elt] dictpa_d = {elt: [str(anum) for anum in dictpa[elt]] for elt in dictpa} else: dictio_d = {} for elt in dictio: dictio_d[elt] = [] if elt in sum_morbs: for morb in dictio[elt]: if morb not in sum_morbs[elt]: dictio_d[elt].append(morb) label = orbital_label(sum_morbs[elt]) dictio_d[elt].append(label) else: dictio_d[elt] = dictio[elt] dictpa_d = {} for elt in dictpa: dictpa_d[elt] = [] if elt in sum_atoms: _sites = self._bs.structure.sites indices = [] for i in range(0, len(_sites)): if _sites[i]._species.keys()[0].__eq__(Element(elt)): indices.append(i + 1) flag_1 = len(set(dictpa[elt]).intersection(indices)) flag_2 = len(set(sum_atoms[elt]).intersection(indices)) if flag_1 == len(indices) and flag_2 == len(indices): dictpa_d[elt].append('all') else: for anum in dictpa[elt]: if anum not in sum_atoms[elt]: dictpa_d[elt].append(str(anum)) label = number_label(sum_atoms[elt]) dictpa_d[elt].append(label) else: for anum in dictpa[elt]: dictpa_d[elt].append(str(anum)) return dictio_d, dictpa_d def _maketicks_selected(self, plt, branches): """ utility private method to add ticks to a band structure with selected branches """ ticks = self.get_ticks() distance = [] label = [] rm_elems = [] for i in range(1, len(ticks['distance'])): if ticks['label'][i] == ticks['label'][i - 1]: rm_elems.append(i) for i in range(len(ticks['distance'])): if i not in rm_elems: distance.append(ticks['distance'][i]) label.append(ticks['label'][i]) l_branches = [distance[i] - distance[i - 1] for i in range(1, len(distance))] n_distance = [] n_label = [] for branch in branches: n_distance.append(l_branches[branch]) if ("$\\mid$" not in label[branch]) and ( "$\\mid$" not in label[branch + 1]): n_label.append([label[branch], label[branch + 1]]) elif ("$\\mid$" in label[branch]) and ( "$\\mid$" not in label[branch + 1]): n_label.append( [label[branch].split("$")[-1], label[branch + 1]]) elif ("$\\mid$" not in label[branch]) and ( "$\\mid$" in label[branch + 1]): n_label.append([label[branch], label[branch + 1].split("$")[0]]) else: n_label.append([label[branch].split("$")[-1], label[branch + 1].split("$")[0]]) f_distance = [] rf_distance = [] f_label = [] f_label.append(n_label[0][0]) f_label.append(n_label[0][1]) f_distance.append(0.0) f_distance.append(n_distance[0]) rf_distance.append(0.0) rf_distance.append(n_distance[0]) length = n_distance[0] for i in range(1, len(n_distance)): if n_label[i][0] == n_label[i - 1][1]: f_distance.append(length) f_distance.append(length + n_distance[i]) f_label.append(n_label[i][0]) f_label.append(n_label[i][1]) else: f_distance.append(length + n_distance[i]) f_label[-1] = n_label[i - 1][1] + "$\\mid$" + n_label[i][0] f_label.append(n_label[i][1]) rf_distance.append(length + n_distance[i]) length += n_distance[i] n_ticks = {'distance': f_distance, 'label': f_label} uniq_d = [] uniq_l = [] temp_ticks = list(zip(n_ticks['distance'], n_ticks['label'])) for i in range(len(temp_ticks)): if i == 0: uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) else: if temp_ticks[i][1] == temp_ticks[i - 1][1]: logger.debug("Skipping label {i}".format( i=temp_ticks[i][1])) else: logger.debug("Adding label {l} at {d}".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug("Unique labels are %s" % list(zip(uniq_d, uniq_l))) plt.gca().set_xticks(uniq_d) plt.gca().set_xticklabels(uniq_l) for i in range(len(n_ticks['label'])): if n_ticks['label'][i] is not None: # don't print the same label twice if i != 0: if n_ticks['label'][i] == n_ticks['label'][i - 1]: logger.debug("already print label... " "skipping label {i}".format( i=n_ticks['label'][i])) else: logger.debug("Adding a line at {d}" " for label {l}".format( d=n_ticks['distance'][i], l=n_ticks['label'][i])) plt.axvline(n_ticks['distance'][i], color='k') else: logger.debug("Adding a line at {d} for label {l}".format( d=n_ticks['distance'][i], l=n_ticks['label'][i])) plt.axvline(n_ticks['distance'][i], color='k') shift = [] br = -1 for branch in branches: br += 1 shift.append(distance[branch] - rf_distance[br]) return plt, shift class BSDOSPlotter(object): """ A joint, aligned band structure and density of states plot. Contributions from Jan Pohls as well as the online example from Germain Salvato-Vallverdu: http://gvallver.perso.univ-pau.fr/?p=587 """ def __init__(self, bs_projection="elements", dos_projection="elements", vb_energy_range=4, cb_energy_range=4, fixed_cb_energy=False, egrid_interval=1, font="Times New Roman", axis_fontsize=20, tick_fontsize=15, legend_fontsize=14, bs_legend="best", dos_legend="best", rgb_legend=True, fig_size=(11, 8.5)): """ Instantiate plotter settings. Args: bs_projection (str): "elements" or None dos_projection (str): "elements", "orbitals", or None vb_energy_range (float): energy in eV to show of valence bands cb_energy_range (float): energy in eV to show of conduction bands fixed_cb_energy (bool): If true, the cb_energy_range will be interpreted as constant (i.e., no gap correction for cb energy) egrid_interval (float): interval for grid marks font (str): font family axis_fontsize (float): font size for axis tick_fontsize (float): font size for axis tick labels legend_fontsize (float): font size for legends bs_legend (str): matplotlib string location for legend or None dos_legend (str): matplotlib string location for legend or None rgb_legend (bool): (T/F) whether to draw RGB triangle/bar for element proj. fig_size(tuple): dimensions of figure size (width, height) """ self.bs_projection = bs_projection self.dos_projection = dos_projection self.vb_energy_range = vb_energy_range self.cb_energy_range = cb_energy_range self.fixed_cb_energy = fixed_cb_energy self.egrid_interval = egrid_interval self.font = font self.axis_fontsize = axis_fontsize self.tick_fontsize = tick_fontsize self.legend_fontsize = legend_fontsize self.bs_legend = bs_legend self.dos_legend = dos_legend self.rgb_legend = rgb_legend self.fig_size = fig_size def get_plot(self, bs, dos=None): """ Get a matplotlib plot object. Args: bs (BandStructureSymmLine): the bandstructure to plot. Projection data must exist for projected plots. dos (Dos): the Dos to plot. Projection data must exist (i.e., CompleteDos) for projected plots. Returns: matplotlib.pyplot object on which you can call commands like show() and savefig() """ import matplotlib.lines as mlines from matplotlib.gridspec import GridSpec import matplotlib.pyplot as mplt # make sure the user-specified band structure projection is valid bs_projection = self.bs_projection if dos: elements = [e.symbol for e in dos.structure.composition.elements] elif bs_projection and bs.structure: elements = [e.symbol for e in bs.structure.composition.elements] else: elements = [] rgb_legend = self.rgb_legend and bs_projection and \ bs_projection.lower() == "elements" and \ len(elements) in [2, 3] if bs_projection and bs_projection.lower() == "elements" and \ (len(elements) not in [2, 3] or not bs.get_projection_on_elements()): warnings.warn( "Cannot get element projected data; either the projection data " "doesn't exist, or you don't have a compound with exactly 2 " "or 3 unique elements.") bs_projection = None # specify energy range of plot emin = -self.vb_energy_range emax = self.cb_energy_range if self.fixed_cb_energy else \ self.cb_energy_range + bs.get_band_gap()["energy"] # initialize all the k-point labels and k-point x-distances for bs plot xlabels = [] # all symmetry point labels on x-axis xlabel_distances = [] # positions of symmetry point x-labels x_distances = [] # x positions of kpoint data prev_right_klabel = None # used to determine which branches require a midline separator for idx, l in enumerate(bs.branches): # get left and right kpoint labels of this branch left_k, right_k = l["name"].split("-") # add $ notation for LaTeX kpoint labels if left_k[0] == "\\" or "_" in left_k: left_k = "$" + left_k + "$" if right_k[0] == "\\" or "_" in right_k: right_k = "$" + right_k + "$" # add left k label to list of labels if prev_right_klabel is None: xlabels.append(left_k) xlabel_distances.append(0) elif prev_right_klabel != left_k: # used for pipe separator xlabels[-1] = xlabels[-1] + "$\\mid$ " + left_k # add right k label to list of labels xlabels.append(right_k) prev_right_klabel = right_k # add x-coordinates for labels left_kpoint = bs.kpoints[l["start_index"]].cart_coords right_kpoint = bs.kpoints[l["end_index"]].cart_coords distance = np.linalg.norm(right_kpoint - left_kpoint) xlabel_distances.append(xlabel_distances[-1] + distance) # add x-coordinates for kpoint data npts = l["end_index"] - l["start_index"] distance_interval = distance / npts x_distances.append(xlabel_distances[-2]) for i in range(npts): x_distances.append(x_distances[-1] + distance_interval) # set up bs and dos plot gs = GridSpec(1, 2, width_ratios=[2, 1]) if dos else GridSpec(1, 1) fig = mplt.figure(figsize=self.fig_size) fig.patch.set_facecolor('white') bs_ax = mplt.subplot(gs[0]) if dos: dos_ax = mplt.subplot(gs[1]) # set basic axes limits for the plot bs_ax.set_xlim(0, x_distances[-1]) bs_ax.set_ylim(emin, emax) if dos: dos_ax.set_ylim(emin, emax) # add BS xticks, labels, etc. bs_ax.set_xticks(xlabel_distances) bs_ax.set_xticklabels(xlabels, size=self.tick_fontsize) bs_ax.set_xlabel('Wavevector $k$', fontsize=self.axis_fontsize, family=self.font) bs_ax.set_ylabel('$E-E_F$ / eV', fontsize=self.axis_fontsize, family=self.font) # add BS fermi level line at E=0 and gridlines bs_ax.hlines(y=0, xmin=0, xmax=x_distances[-1], color="k", lw=2) bs_ax.set_yticks(np.arange(emin, emax + 1E-5, self.egrid_interval)) bs_ax.set_yticklabels(np.arange(emin, emax + 1E-5, self.egrid_interval), size=self.tick_fontsize) bs_ax.set_axisbelow(True) bs_ax.grid(color=[0.5, 0.5, 0.5], linestyle='dotted', linewidth=1) if dos: dos_ax.set_yticks(np.arange(emin, emax + 1E-5, self.egrid_interval)) dos_ax.set_yticklabels([]) dos_ax.grid(color=[0.5, 0.5, 0.5], linestyle='dotted', linewidth=1) # renormalize the band energy to the Fermi level band_energies = {} for spin in (Spin.up, Spin.down): if spin in bs.bands: band_energies[spin] = [] for band in bs.bands[spin]: band_energies[spin].append([e - bs.efermi for e in band]) # renormalize the DOS energies to Fermi level if dos: dos_energies = [e - dos.efermi for e in dos.energies] # get the projection data to set colors for the band structure colordata = self._get_colordata(bs, elements, bs_projection) # plot the colored band structure lines for spin in (Spin.up, Spin.down): if spin in band_energies: linestyles = "solid" if spin == Spin.up else "dotted" for band_idx, band in enumerate(band_energies[spin]): self._rgbline(bs_ax, x_distances, band, colordata[spin][band_idx, :, 0], colordata[spin][band_idx, :, 1], colordata[spin][band_idx, :, 2], linestyles=linestyles) if dos: # Plot the DOS and projected DOS for spin in (Spin.up, Spin.down): if spin in dos.densities: # plot the total DOS dos_densities = dos.densities[spin] * int(spin) label = "total" if spin == Spin.up else None dos_ax.plot(dos_densities, dos_energies, color=(0.6, 0.6, 0.6), label=label) dos_ax.fill_between(dos_densities, 0, dos_energies, color=(0.7, 0.7, 0.7), facecolor=(0.7, 0.7, 0.7)) # plot the atom-projected DOS if self.dos_projection.lower() == "elements": colors = ['b', 'r', 'g', 'm', 'y', 'c', 'k', 'w'] el_dos = dos.get_element_dos() for idx, el in enumerate(elements): dos_densities = el_dos[Element(el)].densities[ spin] * int(spin) label = el if spin == Spin.up else None dos_ax.plot(dos_densities, dos_energies, color=colors[idx], label=label) elif self.dos_projection.lower() == "orbitals": # plot each of the atomic projected DOS colors = ['b', 'r', 'g', 'm'] spd_dos = dos.get_spd_dos() for idx, orb in enumerate([OrbitalType.s, OrbitalType.p, OrbitalType.d, OrbitalType.f]): if orb in spd_dos: dos_densities = spd_dos[orb].densities[spin] * \ int(spin) label = orb if spin == Spin.up else None dos_ax.plot(dos_densities, dos_energies, color=colors[idx], label=label) # get index of lowest and highest energy being plotted, used to help auto-scale DOS x-axis emin_idx = next(x[0] for x in enumerate(dos_energies) if x[1] >= emin) emax_idx = len(dos_energies) - \ next(x[0] for x in enumerate(reversed(dos_energies)) if x[1] <= emax) # determine DOS x-axis range dos_xmin = 0 if Spin.down not in dos.densities else -max( dos.densities[Spin.down][emin_idx:emax_idx + 1] * 1.05) dos_xmax = max([max(dos.densities[Spin.up][emin_idx:emax_idx]) * 1.05, abs(dos_xmin)]) # set up the DOS x-axis and add Fermi level line dos_ax.set_xlim(dos_xmin, dos_xmax) dos_ax.set_xticklabels([]) dos_ax.hlines(y=0, xmin=dos_xmin, xmax=dos_xmax, color="k", lw=2) dos_ax.set_xlabel('DOS', fontsize=self.axis_fontsize, family=self.font) # add legend for band structure if self.bs_legend and not rgb_legend: handles = [] if bs_projection is None: handles = [mlines.Line2D([], [], linewidth=2, color='k', label='spin up'), mlines.Line2D([], [], linewidth=2, color='b', linestyle="dotted", label='spin down')] elif bs_projection.lower() == "elements": colors = ['b', 'r', 'g'] for idx, el in enumerate(elements): handles.append(mlines.Line2D([], [], linewidth=2, color=colors[idx], label=el)) bs_ax.legend(handles=handles, fancybox=True, prop={'size': self.legend_fontsize, 'family': self.font}, loc=self.bs_legend) elif self.bs_legend and rgb_legend: if len(elements) == 2: self._rb_line(bs_ax, elements[1], elements[0], loc=self.bs_legend) elif len(elements) == 3: self._rgb_triangle(bs_ax, elements[1], elements[2], elements[0], loc=self.bs_legend) # add legend for DOS if dos and self.dos_legend: dos_ax.legend(fancybox=True, prop={'size': self.legend_fontsize, 'family': self.font}, loc=self.dos_legend) mplt.subplots_adjust(wspace=0.1) return mplt @staticmethod def _rgbline(ax, k, e, red, green, blue, alpha=1, linestyles="solid"): """ An RGB colored line for plotting. creation of segments based on: http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb Args: ax: matplotlib axis k: x-axis data (k-points) e: y-axis data (energies) red: red data green: green data blue: blue data alpha: alpha values data linestyles: linestyle for plot (e.g., "solid" or "dotted") """ from matplotlib.collections import LineCollection pts = np.array([k, e]).T.reshape(-1, 1, 2) seg = np.concatenate([pts[:-1], pts[1:]], axis=1) nseg = len(k) - 1 r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)] g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)] b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)] a = np.ones(nseg, np.float) * alpha lc = LineCollection(seg, colors=list(zip(r, g, b, a)), linewidth=2, linestyles=linestyles) ax.add_collection(lc) @staticmethod def _get_colordata(bs, elements, bs_projection): """ Get color data, including projected band structures Args: bs: Bandstructure object elements: elements (in desired order) for setting to blue, red, green bs_projection: None for no projection, "elements" for element projection Returns: """ contribs = {} if bs_projection and bs_projection.lower() == "elements": projections = bs.get_projection_on_elements() for spin in (Spin.up, Spin.down): if spin in bs.bands: contribs[spin] = [] for band_idx in range(bs.nb_bands): colors = [] for k_idx in range(len(bs.kpoints)): if bs_projection and bs_projection.lower() == "elements": c = [0, 0, 0] projs = projections[spin][band_idx][k_idx] # note: squared color interpolations are smoother # see: https://youtu.be/LKnqECcg6Gw projs = dict( [(k, v ** 2) for k, v in projs.items()]) total = sum(projs.values()) if total > 0: for idx, e in enumerate(elements): c[idx] = math.sqrt(projs[ e] / total) # min is to handle round errors c = [c[1], c[2], c[0]] # prefer blue, then red, then green else: c = [0, 0, 0] if spin == Spin.up \ else [0, 0, 1] # black for spin up, blue for spin down colors.append(c) contribs[spin].append(colors) contribs[spin] = np.array(contribs[spin]) return contribs @staticmethod def _rgb_triangle(ax, r_label, g_label, b_label, loc): """ Draw an RGB triangle legend on the desired axis """ if not loc in range(1, 11): loc = 2 from mpl_toolkits.axes_grid.inset_locator import inset_axes inset_ax = inset_axes(ax, width=1, height=1, loc=loc) mesh = 35 x = [] y = [] color = [] for r in range(0, mesh): for g in range(0, mesh): for b in range(0, mesh): if not (r == 0 and b == 0 and g == 0): r1 = r / (r + g + b) g1 = g / (r + g + b) b1 = b / (r + g + b) x.append(0.33 * (2. * g1 + r1) / (r1 + b1 + g1)) y.append(0.33 * np.sqrt(3) * r1 / (r1 + b1 + g1)) rc = math.sqrt(r ** 2 / (r ** 2 + g ** 2 + b ** 2)) gc = math.sqrt(g ** 2 / (r ** 2 + g ** 2 + b ** 2)) bc = math.sqrt(b ** 2 / (r ** 2 + g ** 2 + b ** 2)) color.append([rc, gc, bc]) # x = [n + 0.25 for n in x] # nudge x coordinates # y = [n + (max_y - 1) for n in y] # shift y coordinates to top # plot the triangle inset_ax.scatter(x, y, s=7, marker='.', edgecolor=color) inset_ax.set_xlim([-0.35, 1.00]) inset_ax.set_ylim([-0.35, 1.00]) # add the labels inset_ax.text(0.70, -0.2, g_label, fontsize=13, family='Times New Roman', color=(0, 0, 0), horizontalalignment='left') inset_ax.text(0.325, 0.70, r_label, fontsize=13, family='Times New Roman', color=(0, 0, 0), horizontalalignment='center') inset_ax.text(-0.05, -0.2, b_label, fontsize=13, family='Times New Roman', color=(0, 0, 0), horizontalalignment='right') inset_ax.get_xaxis().set_visible(False) inset_ax.get_yaxis().set_visible(False) @staticmethod def _rb_line(ax, r_label, b_label, loc): # Draw an rb bar legend on the desired axis if not loc in range(1, 11): loc = 2 from mpl_toolkits.axes_grid.inset_locator import inset_axes inset_ax = inset_axes(ax, width=1.2, height=0.4, loc=loc) x = [] y = [] color = [] for i in range(0, 1000): x.append(i / 1800. + 0.55) y.append(0) color.append([math.sqrt(c) for c in [1 - (i / 1000) ** 2, 0, (i / 1000) ** 2]]) # plot the bar inset_ax.scatter(x, y, s=250., marker='s', edgecolor=color) inset_ax.set_xlim([-0.1, 1.7]) inset_ax.text(1.35, 0, b_label, fontsize=13, family='Times New Roman', color=(0, 0, 0), horizontalalignment="left", verticalalignment="center") inset_ax.text(0.30, 0, r_label, fontsize=13, family='Times New Roman', color=(0, 0, 0), horizontalalignment="right", verticalalignment="center") inset_ax.get_xaxis().set_visible(False) inset_ax.get_yaxis().set_visible(False) class BoltztrapPlotter(object): # TODO: We need a unittest for this. Come on folks. """ class containing methods to plot the data from Boltztrap. Args: bz: a BoltztrapAnalyzer object """ def __init__(self, bz): self._bz = bz def _plot_doping(self, temp): import matplotlib.pyplot as plt if len(self._bz.doping) != 0: limit = 2.21e15 plt.axvline(self._bz.mu_doping['n'][temp][0], linewidth=3.0, linestyle="--") plt.text(self._bz.mu_doping['n'][temp][0] + 0.01, limit, "$n$=10$^{" + str( math.log10(self._bz.doping['n'][0])) + "}$", color='b') plt.axvline(self._bz.mu_doping['n'][temp][-1], linewidth=3.0, linestyle="--") plt.text(self._bz.mu_doping['n'][temp][-1] + 0.01, limit, "$n$=10$^{" + str(math.log10(self._bz.doping['n'][-1])) + "}$", color='b') plt.axvline(self._bz.mu_doping['p'][temp][0], linewidth=3.0, linestyle="--") plt.text(self._bz.mu_doping['p'][temp][0] + 0.01, limit, "$p$=10$^{" + str( math.log10(self._bz.doping['p'][0])) + "}$", color='b') plt.axvline(self._bz.mu_doping['p'][temp][-1], linewidth=3.0, linestyle="--") plt.text(self._bz.mu_doping['p'][temp][-1] + 0.01, limit, "$p$=10$^{" + str(math.log10(self._bz.doping['p'][-1])) + "}$", color='b') def _plot_bg_limits(self): import matplotlib.pyplot as plt plt.axvline(0.0, color='k', linewidth=3.0) plt.axvline(self._bz.gap, color='k', linewidth=3.0) def plot_seebeck_eff_mass_mu(self, temps=[300], output='average', Lambda=0.5): """ Plot respect to the chemical potential of the Seebeck effective mass calculated as explained in Ref. Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor from ab initio band structure calculations. npj Computational Materials 3, 8 (2017). Args: output: 'average' returns the seebeck effective mass calculated using the average of the three diagonal components of the seebeck tensor. 'tensor' returns the seebeck effective mass respect to the three diagonal components of the seebeck tensor. temps: list of temperatures of calculated seebeck. Lambda: fitting parameter used to model the scattering (0.5 means constant relaxation time). Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.figure(figsize=(9, 7)) for T in temps: sbk_mass = self._bz.get_seebeck_eff_mass(output=output, temp=T, Lambda=0.5) # remove noise inside the gap start = self._bz.mu_doping['p'][T][0] stop = self._bz.mu_doping['n'][T][0] mu_steps_1 = [] mu_steps_2 = [] sbk_mass_1 = [] sbk_mass_2 = [] for i, mu in enumerate(self._bz.mu_steps): if mu <= start: mu_steps_1.append(mu) sbk_mass_1.append(sbk_mass[i]) elif mu >= stop: mu_steps_2.append(mu) sbk_mass_2.append(sbk_mass[i]) plt.plot(mu_steps_1, sbk_mass_1, label=str(T) + 'K', linewidth=3.0) plt.plot(mu_steps_2, sbk_mass_2, linewidth=3.0) if output == 'average': plt.gca().get_lines()[1].set_c(plt.gca().get_lines()[0].get_c()) elif output == 'tensor': plt.gca().get_lines()[3].set_c(plt.gca().get_lines()[0].get_c()) plt.gca().get_lines()[4].set_c(plt.gca().get_lines()[1].get_c()) plt.gca().get_lines()[5].set_c(plt.gca().get_lines()[2].get_c()) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.ylabel("Seebeck effective mass", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) if output == 'tensor': plt.legend([str(i) + '_' + str(T) + 'K' for T in temps for i in ('x', 'y', 'z')], fontsize=20) elif output == 'average': plt.legend(fontsize=20) plt.tight_layout() return plt def plot_complexity_factor_mu(self, temps=[300], output='average', Lambda=0.5): """ Plot respect to the chemical potential of the Fermi surface complexity factor calculated as explained in Ref. Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor from ab initio band structure calculations. npj Computational Materials 3, 8 (2017). Args: output: 'average' returns the complexity factor calculated using the average of the three diagonal components of the seebeck and conductivity tensors. 'tensor' returns the complexity factor respect to the three diagonal components of seebeck and conductivity tensors. temps: list of temperatures of calculated seebeck and conductivity. Lambda: fitting parameter used to model the scattering (0.5 means constant relaxation time). Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.figure(figsize=(9, 7)) for T in temps: cmplx_fact = self._bz.get_complexity_factor(output=output, temp=T, Lambda=Lambda) start = self._bz.mu_doping['p'][T][0] stop = self._bz.mu_doping['n'][T][0] mu_steps_1 = [] mu_steps_2 = [] cmplx_fact_1 = [] cmplx_fact_2 = [] for i, mu in enumerate(self._bz.mu_steps): if mu <= start: mu_steps_1.append(mu) cmplx_fact_1.append(cmplx_fact[i]) elif mu >= stop: mu_steps_2.append(mu) cmplx_fact_2.append(cmplx_fact[i]) plt.plot(mu_steps_1, cmplx_fact_1, label=str(T) + 'K', linewidth=3.0) plt.plot(mu_steps_2, cmplx_fact_2, linewidth=3.0) if output == 'average': plt.gca().get_lines()[1].set_c(plt.gca().get_lines()[0].get_c()) elif output == 'tensor': plt.gca().get_lines()[3].set_c(plt.gca().get_lines()[0].get_c()) plt.gca().get_lines()[4].set_c(plt.gca().get_lines()[1].get_c()) plt.gca().get_lines()[5].set_c(plt.gca().get_lines()[2].get_c()) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.ylabel("Complexity Factor", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) if output == 'tensor': plt.legend([str(i) + '_' + str(T) + 'K' for T in temps for i in ('x', 'y', 'z')], fontsize=20) elif output == 'average': plt.legend(fontsize=20) plt.tight_layout() return plt def plot_seebeck_mu(self, temp=600, output='eig', xlim=None): """ Plot the seebeck coefficient in function of Fermi level Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.figure(figsize=(9, 7)) seebeck = self._bz.get_seebeck(output=output, doping_levels=False)[ temp] plt.plot(self._bz.mu_steps, seebeck, linewidth=3.0) self._plot_bg_limits() self._plot_doping(temp) if output == 'eig': plt.legend(['S$_1$', 'S$_2$', 'S$_3$']) if xlim is None: plt.xlim(-0.5, self._bz.gap + 0.5) else: plt.xlim(xlim[0], xlim[1]) plt.ylabel("Seebeck \n coefficient ($\\mu$V/K)", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_conductivity_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None): """ Plot the conductivity in function of Fermi level. Semi-log plot Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) tau: A relaxation time in s. By default none and the plot is by units of relaxation time Returns: a matplotlib object """ import matplotlib.pyplot as plt cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output=output, doping_levels=False)[ temp] plt.figure(figsize=(9, 7)) plt.semilogy(self._bz.mu_steps, cond, linewidth=3.0) self._plot_bg_limits() self._plot_doping(temp) if output == 'eig': plt.legend(['$\\Sigma_1$', '$\\Sigma_2$', '$\\Sigma_3$']) if xlim is None: plt.xlim(-0.5, self._bz.gap + 0.5) else: plt.xlim(xlim) plt.ylim([1e13 * relaxation_time, 1e20 * relaxation_time]) plt.ylabel("conductivity,\n $\\Sigma$ (1/($\\Omega$ m))", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30.0) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_power_factor_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None): """ Plot the power factor in function of Fermi level. Semi-log plot Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) tau: A relaxation time in s. By default none and the plot is by units of relaxation time Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.figure(figsize=(9, 7)) pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output=output, doping_levels=False)[ temp] plt.semilogy(self._bz.mu_steps, pf, linewidth=3.0) self._plot_bg_limits() self._plot_doping(temp) if output == 'eig': plt.legend(['PF$_1$', 'PF$_2$', 'PF$_3$']) if xlim is None: plt.xlim(-0.5, self._bz.gap + 0.5) else: plt.xlim(xlim) plt.ylabel("Power factor, ($\\mu$W/(mK$^2$))", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30.0) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_zt_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None): """ Plot the ZT in function of Fermi level. Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) tau: A relaxation time in s. By default none and the plot is by units of relaxation time Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.figure(figsize=(9, 7)) zt = self._bz.get_zt(relaxation_time=relaxation_time, output=output, doping_levels=False)[temp] plt.plot(self._bz.mu_steps, zt, linewidth=3.0) self._plot_bg_limits() self._plot_doping(temp) if output == 'eig': plt.legend(['ZT$_1$', 'ZT$_2$', 'ZT$_3$']) if xlim is None: plt.xlim(-0.5, self._bz.gap + 0.5) else: plt.xlim(xlim) plt.ylabel("ZT", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30.0) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_seebeck_temp(self, doping='all', output='average'): """ Plot the Seebeck coefficient in function of temperature for different doping levels. Args: dopings: the default 'all' plots all the doping levels in the analyzer. Specify a list of doping levels if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': sbk = self._bz.get_seebeck(output='average') elif output == 'eigs': sbk = self._bz.get_seebeck(output='eigs') plt.figure(figsize=(22, 14)) tlist = np.sort(sbk['n'].keys()) doping = self._bz.doping['n'] if doping == 'all' else doping for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for dop in doping: d = self._bz.doping[dt].index(dop) sbk_temp = [] for temp in tlist: sbk_temp.append(sbk[dt][temp][d]) if output == 'average': plt.plot(tlist, sbk_temp, marker='s', label=str(dop) + ' $cm^{-3}$') elif output == 'eigs': for xyz in range(3): plt.plot(tlist, zip(*sbk_temp)[xyz], marker='s', label=str(xyz) + ' ' + str(dop) + ' $cm^{-3}$') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Seebeck \n coefficient ($\\mu$V/K)", fontsize=30.0) plt.xlabel('Temperature (K)', fontsize=30.0) p = 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_conductivity_temp(self, doping='all', output='average', relaxation_time=1e-14): """ Plot the conductivity in function of temperature for different doping levels. Args: dopings: the default 'all' plots all the doping levels in the analyzer. Specify a list of doping levels if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt import matplotlib.ticker as mtick if output == 'average': cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output='average') elif output == 'eigs': cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output='eigs') plt.figure(figsize=(22, 14)) tlist = np.sort(cond['n'].keys()) doping = self._bz.doping['n'] if doping == 'all' else doping for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for dop in doping: d = self._bz.doping[dt].index(dop) cond_temp = [] for temp in tlist: cond_temp.append(cond[dt][temp][d]) if output == 'average': plt.plot(tlist, cond_temp, marker='s', label=str(dop) + ' $cm^{-3}$') elif output == 'eigs': for xyz in range(3): plt.plot(tlist, zip(*cond_temp)[xyz], marker='s', label=str(xyz) + ' ' + str(dop) + ' $cm^{-3}$') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("conductivity $\\sigma$ (1/($\\Omega$ m))", fontsize=30.0) plt.xlabel('Temperature (K)', fontsize=30.0) p = '' # 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.tight_layout() return plt def plot_power_factor_temp(self, doping='all', output='average', relaxation_time=1e-14): """ Plot the Power Factor in function of temperature for different doping levels. Args: dopings: the default 'all' plots all the doping levels in the analyzer. Specify a list of doping levels if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output='average') elif output == 'eigs': pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output='eigs') plt.figure(figsize=(22, 14)) tlist = np.sort(pf['n'].keys()) doping = self._bz.doping['n'] if doping == 'all' else doping for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for dop in doping: d = self._bz.doping[dt].index(dop) pf_temp = [] for temp in tlist: pf_temp.append(pf[dt][temp][d]) if output == 'average': plt.plot(tlist, pf_temp, marker='s', label=str(dop) + ' $cm^{-3}$') elif output == 'eigs': for xyz in range(3): plt.plot(tlist, zip(*pf_temp)[xyz], marker='s', label=str(xyz) + ' ' + str(dop) + ' $cm^{-3}$') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Power Factor ($\\mu$W/(mK$^2$))", fontsize=30.0) plt.xlabel('Temperature (K)', fontsize=30.0) p = '' # 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.tight_layout() return plt def plot_zt_temp(self, doping='all', output='average', relaxation_time=1e-14): """ Plot the figure of merit zT in function of temperature for different doping levels. Args: dopings: the default 'all' plots all the doping levels in the analyzer. Specify a list of doping levels if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': zt = self._bz.get_zt(relaxation_time=relaxation_time, output='average') elif output == 'eigs': zt = self._bz.get_zt(relaxation_time=relaxation_time, output='eigs') plt.figure(figsize=(22, 14)) tlist = np.sort(zt['n'].keys()) doping = self._bz.doping['n'] if doping == 'all' else doping for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for dop in doping: d = self._bz.doping[dt].index(dop) zt_temp = [] for temp in tlist: zt_temp.append(zt[dt][temp][d]) if output == 'average': plt.plot(tlist, zt_temp, marker='s', label=str(dop) + ' $cm^{-3}$') elif output == 'eigs': for xyz in range(3): plt.plot(tlist, zip(*zt_temp)[xyz], marker='s', label=str(xyz) + ' ' + str(dop) + ' $cm^{-3}$') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("zT", fontsize=30.0) plt.xlabel('Temperature (K)', fontsize=30.0) p = '' # 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_eff_mass_temp(self, doping='all', output='average'): """ Plot the average effective mass in function of temperature for different doping levels. Args: dopings: the default 'all' plots all the doping levels in the analyzer. Specify a list of doping levels if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': em = self._bz.get_average_eff_mass(output='average') elif output == 'eigs': em = self._bz.get_average_eff_mass(output='eigs') plt.figure(figsize=(22, 14)) tlist = np.sort(em['n'].keys()) doping = self._bz.doping['n'] if doping == 'all' else doping for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for dop in doping: d = self._bz.doping[dt].index(dop) em_temp = [] for temp in tlist: em_temp.append(em[dt][temp][d]) if output == 'average': plt.plot(tlist, em_temp, marker='s', label=str(dop) + ' $cm^{-3}$') elif output == 'eigs': for xyz in range(3): plt.plot(tlist, zip(*em_temp)[xyz], marker='s', label=str(xyz) + ' ' + str(dop) + ' $cm^{-3}$') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Effective mass (m$_e$)", fontsize=30.0) plt.xlabel('Temperature (K)', fontsize=30.0) p = '' # 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_seebeck_dop(self, temps='all', output='average'): """ Plot the Seebeck in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': sbk = self._bz.get_seebeck(output='average') elif output == 'eigs': sbk = self._bz.get_seebeck(output='eigs') tlist = np.sort(sbk['n'].keys()) if temps == 'all' else temps plt.figure(figsize=(22, 14)) for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for temp in tlist: if output == 'eigs': for xyz in range(3): plt.semilogx(self._bz.doping[dt], zip(*sbk[dt][temp])[xyz], marker='s', label=str(xyz) + ' ' + str(temp) + ' K') elif output == 'average': plt.semilogx(self._bz.doping[dt], sbk[dt][temp], marker='s', label=str(temp) + ' K') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Seebeck coefficient ($\\mu$V/K)", fontsize=30.0) plt.xlabel('Doping concentration (cm$^{-3}$)', fontsize=30.0) p = 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_conductivity_dop(self, temps='all', output='average', relaxation_time=1e-14): """ Plot the conductivity in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output='average') elif output == 'eigs': cond = self._bz.get_conductivity(relaxation_time=relaxation_time, output='eigs') tlist = np.sort(cond['n'].keys()) if temps == 'all' else temps plt.figure(figsize=(22, 14)) for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for temp in tlist: if output == 'eigs': for xyz in range(3): plt.semilogx(self._bz.doping[dt], zip(*cond[dt][temp])[xyz], marker='s', label=str(xyz) + ' ' + str(temp) + ' K') elif output == 'average': plt.semilogx(self._bz.doping[dt], cond[dt][temp], marker='s', label=str(temp) + ' K') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("conductivity $\\sigma$ (1/($\\Omega$ m))", fontsize=30.0) plt.xlabel('Doping concentration ($cm^{-3}$)', fontsize=30.0) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.legend(fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_power_factor_dop(self, temps='all', output='average', relaxation_time=1e-14): """ Plot the Power Factor in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output='average') elif output == 'eigs': pf = self._bz.get_power_factor(relaxation_time=relaxation_time, output='eigs') tlist = np.sort(pf['n'].keys()) if temps == 'all' else temps plt.figure(figsize=(22, 14)) for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for temp in tlist: if output == 'eigs': for xyz in range(3): plt.semilogx(self._bz.doping[dt], zip(*pf[dt][temp])[xyz], marker='s', label=str(xyz) + ' ' + str(temp) + ' K') elif output == 'average': plt.semilogx(self._bz.doping[dt], pf[dt][temp], marker='s', label=str(temp) + ' K') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Power Factor ($\\mu$W/(mK$^2$))", fontsize=30.0) plt.xlabel('Doping concentration ($cm^{-3}$)', fontsize=30.0) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) p = '' # 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_zt_dop(self, temps='all', output='average', relaxation_time=1e-14): """ Plot the figure of merit zT in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': zt = self._bz.get_zt(relaxation_time=relaxation_time, output='average') elif output == 'eigs': zt = self._bz.get_zt(relaxation_time=relaxation_time, output='eigs') tlist = np.sort(zt['n'].keys()) if temps == 'all' else temps plt.figure(figsize=(22, 14)) for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for temp in tlist: if output == 'eigs': for xyz in range(3): plt.semilogx(self._bz.doping[dt], zip(*zt[dt][temp])[xyz], marker='s', label=str(xyz) + ' ' + str(temp) + ' K') elif output == 'average': plt.semilogx(self._bz.doping[dt], zt[dt][temp], marker='s', label=str(temp) + ' K') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("zT", fontsize=30.0) plt.xlabel('Doping concentration ($cm^{-3}$)', fontsize=30.0) p = 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_eff_mass_dop(self, temps='all', output='average'): """ Plot the average effective mass in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an average of the three directions with 'eigs' you get all the three directions. relaxation_time: specify a constant relaxation time value Returns: a matplotlib object """ import matplotlib.pyplot as plt if output == 'average': em = self._bz.get_average_eff_mass(output='average') elif output == 'eigs': em = self._bz.get_average_eff_mass(output='eigs') tlist = np.sort(em['n'].keys()) if temps == 'all' else temps plt.figure(figsize=(22, 14)) for i, dt in enumerate(['n', 'p']): plt.subplot(121 + i) for temp in tlist: if output == 'eigs': for xyz in range(3): plt.semilogx(self._bz.doping[dt], zip(*em[dt][temp])[xyz], marker='s', label=str(xyz) + ' ' + str(temp) + ' K') elif output == 'average': plt.semilogx(self._bz.doping[dt], em[dt][temp], marker='s', label=str(temp) + ' K') plt.title(dt + '-type', fontsize=20) if i == 0: plt.ylabel("Effective mass (m$_e$)", fontsize=30.0) plt.xlabel('Doping concentration ($cm^{-3}$)', fontsize=30.0) p = 'lower right' if i == 0 else '' plt.legend(loc=p, fontsize=15) plt.grid() plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.tight_layout() return plt def plot_dos(self, sigma=0.05): """ plot dos Args: sigma: a smearing Returns: a matplotlib object """ plotter = DosPlotter(sigma=sigma) plotter.add_dos("t", self._bz.dos) return plotter.get_plot() def plot_carriers(self, temp=300): """ Plot the carrier concentration in function of Fermi level Args: temp: the temperature Returns: a matplotlib object """ import matplotlib.pyplot as plt plt.semilogy(self._bz.mu_steps, abs(self._bz.carrier_conc[temp] / (self._bz.vol * 1e-24)), linewidth=3.0, color='r') self._plot_bg_limits() self._plot_doping(temp) plt.xlim(-0.5, self._bz.gap + 0.5) plt.ylim(1e14, 1e22) plt.ylabel("carrier concentration (cm-3)", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) return plt def plot_hall_carriers(self, temp=300): """ Plot the Hall carrier concentration in function of Fermi level Args: temp: the temperature Returns: a matplotlib object """ import matplotlib.pyplot as plt hall_carriers = [abs(i) for i in self._bz.get_hall_carrier_concentration()[temp]] plt.semilogy(self._bz.mu_steps, hall_carriers, linewidth=3.0, color='r') self._plot_bg_limits() self._plot_doping(temp) plt.xlim(-0.5, self._bz.gap + 0.5) plt.ylim(1e14, 1e22) plt.ylabel("Hall carrier concentration (cm-3)", fontsize=30.0) plt.xlabel("E-E$_f$ (eV)", fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) return plt class CohpPlotter(object): """ Class for plotting crystal orbital Hamilton populations (COHPs) or crystal orbital overlap populations (COOPs). It is modeled after the DosPlotter object. Args/attributes: zero_at_efermi: Whether to shift all populations to have zero energy at the Fermi level. Defaults to True. are_coops: Switch to indicate that these are COOPs, not COHPs. Defaults to False for COHPs. """ def __init__(self, zero_at_efermi=True, are_coops=False): self.zero_at_efermi = zero_at_efermi self.are_coops = are_coops self._cohps = OrderedDict() def add_cohp(self, label, cohp): """ Adds a COHP for plotting. Args: label: Label for the COHP. Must be unique. cohp: COHP object. """ energies = cohp.energies - cohp.efermi if self.zero_at_efermi \ else cohp.energies populations = cohp.get_cohp() int_populations = cohp.get_icohp() self._cohps[label] = {"energies": energies, "COHP": populations, "ICOHP": int_populations, "efermi": cohp.efermi} def add_cohp_dict(self, cohp_dict, key_sort_func=None): """ Adds a dictionary of COHPs with an optional sorting function for the keys. Args: cohp_dict: dict of the form {label: Cohp} key_sort_func: function used to sort the cohp_dict keys. """ if key_sort_func: keys = sorted(cohp_dict.keys(), key=key_sort_func) else: keys = cohp_dict.keys() for label in keys: self.add_cohp(label, cohp_dict[label]) def get_cohp_dict(self): """ Returns the added COHPs as a json-serializable dict. Note that if you have specified smearing for the COHP plot, the populations returned will be the smeared and not the original populations. Returns: dict: Dict of COHP data of the form {label: {"efermi": efermi, "energies": ..., "COHP": {Spin.up: ...}, "ICOHP": ...}}. """ return jsanitize(self._cohps) def get_plot(self, xlim=None, ylim=None, plot_negative=None, integrated=False, invert_axes=True): """ Get a matplotlib plot showing the COHP. Args: xlim: Specifies the x-axis limits. Defaults to None for automatic determination. ylim: Specifies the y-axis limits. Defaults to None for automatic determination. plot_negative: It is common to plot -COHP(E) so that the sign means the same for COOPs and COHPs. Defaults to None for automatic determination: If are_coops is True, this will be set to False, else it will be set to True. integrated: Switch to plot ICOHPs. Defaults to False. invert_axes: Put the energies onto the y-axis, which is common in chemistry. Returns: A matplotlib object. """ if self.are_coops: cohp_label = "COOP" else: cohp_label = "COHP" if plot_negative is None: plot_negative = True if not self.are_coops else False if integrated: cohp_label = "I" + cohp_label + " (eV)" if plot_negative: cohp_label = "-" + cohp_label if self.zero_at_efermi: energy_label = "$E - E_f$ (eV)" else: energy_label = "$E$ (eV)" ncolors = max(3, len(self._cohps)) ncolors = min(9, ncolors) import palettable colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors plt = pretty_plot(12, 8) allpts = [] keys = self._cohps.keys() for i, key in enumerate(keys): energies = self._cohps[key]["energies"] if not integrated: populations = self._cohps[key]["COHP"] else: populations = self._cohps[key]["ICOHP"] for spin in [Spin.up, Spin.down]: if spin in populations: if invert_axes: x = -populations[spin] if plot_negative \ else populations[spin] y = energies else: x = energies y = -populations[spin] if plot_negative \ else populations[spin] allpts.extend(list(zip(x, y))) if spin == Spin.up: plt.plot(x, y, color=colors[i % ncolors], linestyle='-', label=str(key), linewidth=3) else: plt.plot(x, y, color=colors[i % ncolors], linestyle='--', linewidth=3) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) xlim = plt.xlim() ylim = plt.ylim() if not invert_axes: plt.plot(xlim, [0, 0], "k-", linewidth=2) if self.zero_at_efermi: plt.plot([0, 0], ylim, "k--", linewidth=2) else: plt.plot([self._cohps[key]['efermi'], self._cohps[key]['efermi']], ylim, color=colors[i % ncolors], linestyle='--', linewidth=2) else: plt.plot([0, 0], ylim, "k-", linewidth=2) if self.zero_at_efermi: plt.plot(xlim, [0, 0], "k--", linewidth=2) else: plt.plot(xlim, [self._cohps[key]['efermi'], self._cohps[key]['efermi']], color=colors[i % ncolors], linestyle='--', linewidth=2) if invert_axes: plt.xlabel(cohp_label) plt.ylabel(energy_label) else: plt.xlabel(energy_label) plt.ylabel(cohp_label) plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() plt.setp(ltext, fontsize=30) plt.tight_layout() return plt def save_plot(self, filename, img_format="eps", xlim=None, ylim=None): """ Save matplotlib plot to a file. Args: filename: File name to write to. img_format: Image format to use. Defaults to EPS. xlim: Specifies the x-axis limits. Defaults to None for automatic determination. ylim: Specifies the y-axis limits. Defaults to None for automatic determination. """ plt = self.get_plot(xlim, ylim) plt.savefig(filename, format=img_format) def show(self, xlim=None, ylim=None): """ Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Defaults to None for automatic determination. ylim: Specifies the y-axis limits. Defaults to None for automatic determination. """ plt = self.get_plot(xlim, ylim) plt.show() def plot_fermi_surface(data, structure, cbm, energy_levels=[], multiple_figure=True, mlab_figure=None, kpoints_dict={}, color=(0, 0, 1), transparency_factor=[], labels_scale_factor=0.05, points_scale_factor=0.02, interative=True): """ Plot the Fermi surface at specific energy value. Args: data: energy values in a 3D grid from a CUBE file via read_cube_file function, or from a BoltztrapAnalyzer.fermi_surface_data structure: structure object of the material energy_levels: list of energy value of the fermi surface. By default 0 eV correspond to the VBM, as in the plot of band structure along symmetry line. Default: max energy value + 0.01 eV cbm: Boolean value to specify if the considered band is a conduction band or not multiple_figure: if True a figure for each energy level will be shown. If False all the surfaces will be shown in the same figure. In this las case, tune the transparency factor. mlab_figure: provide a previous figure to plot a new surface on it. kpoints_dict: dictionary of kpoints to show in the plot. example: {"K":[0.5,0.0,0.5]}, where the coords are fractional. color: tuple (r,g,b) of integers to define the color of the surface. transparency_factor: list of values in the range [0,1] to tune the opacity of the surfaces. labels_scale_factor: factor to tune the size of the kpoint labels points_scale_factor: factor to tune the size of the kpoint points interative: if True an interactive figure will be shown. If False a non interactive figure will be shown, but it is possible to plot other surfaces on the same figure. To make it interactive, run mlab.show(). Returns: a Mayavi figure and a mlab module to control the plot. Note: Experimental. Please, double check the surface shown by using some other software and report issues. """ try: from mayavi import mlab except ImportError: raise BoltztrapError( "Mayavi package should be installed to use this function") bz = structure.lattice.reciprocal_lattice.get_wigner_seitz_cell() cell = structure.lattice.reciprocal_lattice.matrix fact = 1 if cbm == False else -1 en_min = np.min(fact * data.ravel()) en_max = np.max(fact * data.ravel()) if energy_levels == []: energy_levels = [en_min + 0.01] if cbm == True else \ [en_max - 0.01] print("Energy level set to: " + str(energy_levels[0]) + " eV") else: for e in energy_levels: if e > en_max or e < en_min: raise BoltztrapError("energy level " + str(e) + " not in the range of possible energies: [" + str(en_min) + ", " + str(en_max) + "]") if transparency_factor == []: transparency_factor = [1] * len(energy_levels) if mlab_figure: fig = mlab_figure if mlab_figure == None and not multiple_figure: fig = mlab.figure(size=(1024, 768), bgcolor=(1, 1, 1)) for iface in range(len(bz)): for line in itertools.combinations(bz[iface], 2): for jface in range(len(bz)): if iface < jface and any(np.all(line[0] == x) for x in bz[jface]) and \ any(np.all(line[1] == x) for x in bz[jface]): mlab.plot3d(*zip(line[0], line[1]), color=(0, 0, 0), tube_radius=None, figure=fig) for label, coords in kpoints_dict.iteritems(): label_coords = structure.lattice.reciprocal_lattice \ .get_cartesian_coords(coords) mlab.points3d(*label_coords, scale_factor=points_scale_factor, color=(0, 0, 0), figure=fig) mlab.text3d(*label_coords, text=label, scale=labels_scale_factor, color=(0, 0, 0), figure=fig) for isolevel, alpha in zip(energy_levels, transparency_factor): if multiple_figure: fig = mlab.figure(size=(1024, 768), bgcolor=(1, 1, 1)) for iface in range(len(bz)): for line in itertools.combinations(bz[iface], 2): for jface in range(len(bz)): if iface < jface and any(np.all(line[0] == x) for x in bz[jface]) and \ any(np.all(line[1] == x) for x in bz[jface]): mlab.plot3d(*zip(line[0], line[1]), color=(0, 0, 0), tube_radius=None, figure=fig) for label, coords in kpoints_dict.iteritems(): label_coords = structure.lattice.reciprocal_lattice \ .get_cartesian_coords(coords) mlab.points3d(*label_coords, scale_factor=points_scale_factor, color=(0, 0, 0), figure=fig) mlab.text3d(*label_coords, text=label, scale=labels_scale_factor, color=(0, 0, 0), figure=fig) cp = mlab.contour3d(fact * data, contours=[isolevel], transparent=True, colormap='hot', color=color, opacity=alpha, figure=fig) polydata = cp.actor.actors[0].mapper.input pts = np.array(polydata.points) # - 1 polydata.points = np.dot(pts, cell / np.array(data.shape)[:, np.newaxis]) cx, cy, cz = [np.mean(np.array(polydata.points)[:, i]) for i in range(3)] polydata.points = (np.array(polydata.points) - [cx, cy, cz]) * 2 mlab.view(distance='auto') if interative == True: mlab.show() return fig, mlab def plot_wigner_seitz(lattice, ax=None, **kwargs): """ Adds the skeleton of the Wigner-Seitz cell of the lattice to a matplotlib Axes Args: lattice: Lattice object ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to black and linewidth to 1. Returns: matplotlib figure and matplotlib ax """ ax, fig, plt = get_ax3d_fig_plt(ax) if "color" not in kwargs: kwargs["color"] = "k" if "linewidth" not in kwargs: kwargs["linewidth"] = 1 bz = lattice.get_wigner_seitz_cell() ax, fig, plt = get_ax3d_fig_plt(ax) for iface in range(len(bz)): for line in itertools.combinations(bz[iface], 2): for jface in range(len(bz)): if iface < jface and any( np.all(line[0] == x) for x in bz[jface]) \ and any(np.all(line[1] == x) for x in bz[jface]): ax.plot(*zip(line[0], line[1]), **kwargs) return fig, ax def plot_lattice_vectors(lattice, ax=None, **kwargs): """ Adds the basis vectors of the lattice provided to a matplotlib Axes Args: lattice: Lattice object ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to green and linewidth to 3. Returns: matplotlib figure and matplotlib ax """ ax, fig, plt = get_ax3d_fig_plt(ax) if "color" not in kwargs: kwargs["color"] = "g" if "linewidth" not in kwargs: kwargs["linewidth"] = 3 vertex1 = lattice.get_cartesian_coords([0.0, 0.0, 0.0]) vertex2 = lattice.get_cartesian_coords([1.0, 0.0, 0.0]) ax.plot(*zip(vertex1, vertex2), **kwargs) vertex2 = lattice.get_cartesian_coords([0.0, 1.0, 0.0]) ax.plot(*zip(vertex1, vertex2), **kwargs) vertex2 = lattice.get_cartesian_coords([0.0, 0.0, 1.0]) ax.plot(*zip(vertex1, vertex2), **kwargs) return fig, ax def plot_path(line, lattice=None, coords_are_cartesian=False, ax=None, **kwargs): """ Adds a line passing through the coordinates listed in 'line' to a matplotlib Axes Args: line: list of coordinates. lattice: Lattice object used to convert from reciprocal to cartesian coordinates coords_are_cartesian: Set to True if you are providing coordinates in cartesian coordinates. Defaults to False. Requires lattice if False. ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'plot'. Color defaults to red and linewidth to 3. Returns: matplotlib figure and matplotlib ax """ ax, fig, plt = get_ax3d_fig_plt(ax) if "color" not in kwargs: kwargs["color"] = "r" if "linewidth" not in kwargs: kwargs["linewidth"] = 3 for k in range(1, len(line)): vertex1 = line[k - 1] vertex2 = line[k] if not coords_are_cartesian: if lattice is None: raise ValueError( "coords_are_cartesian False requires the lattice") vertex1 = lattice.get_cartesian_coords(vertex1) vertex2 = lattice.get_cartesian_coords(vertex2) ax.plot(*zip(vertex1, vertex2), **kwargs) return fig, ax def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None, **kwargs): """ Adds labels to a matplotlib Axes Args: labels: dict containing the label as a key and the coordinates as value. lattice: Lattice object used to convert from reciprocal to cartesian coordinates coords_are_cartesian: Set to True if you are providing. coordinates in cartesian coordinates. Defaults to False. Requires lattice if False. ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'text'. Color defaults to blue and size to 25. Returns: matplotlib figure and matplotlib ax """ ax, fig, plt = get_ax3d_fig_plt(ax) if "color" not in kwargs: kwargs["color"] = "b" if "size" not in kwargs: kwargs["size"] = 25 for k, coords in labels.items(): label = k if k.startswith("\\") or k.find("_") != -1: label = "$" + k + "$" off = 0.01 if coords_are_cartesian: coords = np.array(coords) else: if lattice is None: raise ValueError( "coords_are_cartesian False requires the lattice") coords = lattice.get_cartesian_coords(coords) ax.text(*(coords + off), s=label, **kwargs) return fig, ax def fold_point(p, lattice, coords_are_cartesian=False): """ Folds a point with coordinates p inside the first Brillouin zone of the lattice. Args: p: coordinates of one point lattice: Lattice object used to convert from reciprocal to cartesian coordinates coords_are_cartesian: Set to True if you are providing coordinates in cartesian coordinates. Defaults to False. Returns: The cartesian coordinates folded inside the first Brillouin zone """ if coords_are_cartesian: p = lattice.get_fractional_coords(p) else: p = np.array(p) p = np.mod(p + 0.5 - 1e-10, 1) - 0.5 + 1e-10 p = lattice.get_cartesian_coords(p) closest_lattice_point = None smallest_distance = 10000 for i in (-1, 0, 1): for j in (-1, 0, 1): for k in (-1, 0, 1): lattice_point = np.dot((i, j, k), lattice.matrix) dist = np.linalg.norm(p - lattice_point) if closest_lattice_point is None or dist < smallest_distance: closest_lattice_point = lattice_point smallest_distance = dist if not np.allclose(closest_lattice_point, (0, 0, 0)): p = p - closest_lattice_point return p def plot_points(points, lattice=None, coords_are_cartesian=False, fold=False, ax=None, **kwargs): """ Adds Points to a matplotlib Axes Args: points: list of coordinates lattice: Lattice object used to convert from reciprocal to cartesian coordinates coords_are_cartesian: Set to True if you are providing coordinates in cartesian coordinates. Defaults to False. Requires lattice if False. fold: whether the points should be folded inside the first Brillouin Zone. Defaults to False. Requires lattice if True. ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: kwargs passed to the matplotlib function 'scatter'. Color defaults to blue Returns: matplotlib figure and matplotlib ax """ ax, fig, plt = get_ax3d_fig_plt(ax) if "color" not in kwargs: kwargs["color"] = "b" if (not coords_are_cartesian or fold) and lattice is None: raise ValueError( "coords_are_cartesian False or fold True require the lattice") for p in points: if fold: p = fold_point(p, lattice, coords_are_cartesian=coords_are_cartesian) elif not coords_are_cartesian: p = lattice.get_cartesian_coords(p) ax.scatter(*p, **kwargs) return fig, ax @add_fig_kwargs def plot_brillouin_zone_from_kpath(kpath, ax=None, **kwargs): """ Gives the plot (as a matplotlib object) of the symmetry line path in the Brillouin Zone. Args: kpath (HighSymmKpath): a HighSymmKPath object ax: matplotlib :class:`Axes` or None if a new figure should be created. **kwargs: provided by add_fig_kwargs decorator Returns: matplotlib figure """ lines = [[kpath.kpath['kpoints'][k] for k in p] for p in kpath.kpath['path']] return plot_brillouin_zone(bz_lattice=kpath.prim_rec, lines=lines, ax=ax, labels=kpath.kpath['kpoints'], **kwargs) @add_fig_kwargs def plot_brillouin_zone(bz_lattice, lines=None, labels=None, kpoints=None, fold=False, coords_are_cartesian=False, ax=None, **kwargs): """ Plots a 3D representation of the Brillouin zone of the structure. Can add to the plot paths, labels and kpoints Args: bz_lattice: Lattice object of the Brillouin zone lines: list of lists of coordinates. Each list represent a different path labels: dict containing the label as a key and the coordinates as value. kpoints: list of coordinates fold: whether the points should be folded inside the first Brillouin Zone. Defaults to False. Requires lattice if True. coords_are_cartesian: Set to True if you are providing coordinates in cartesian coordinates. Defaults to False. ax: matplotlib :class:`Axes` or None if a new figure should be created. kwargs: provided by add_fig_kwargs decorator Returns: matplotlib figure """ fig, ax = plot_lattice_vectors(bz_lattice, ax=ax) plot_wigner_seitz(bz_lattice, ax=ax) if lines is not None: for line in lines: plot_path(line, bz_lattice, coords_are_cartesian=coords_are_cartesian, ax=ax) if labels is not None: plot_labels(labels, bz_lattice, coords_are_cartesian=coords_are_cartesian, ax=ax) plot_points(labels.values(), bz_lattice, coords_are_cartesian=coords_are_cartesian, fold=False, ax=ax) if kpoints is not None: plot_points(kpoints, bz_lattice, coords_are_cartesian=coords_are_cartesian, ax=ax, fold=fold) ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) ax.set_aspect('equal') ax.axis("off") return fig def plot_ellipsoid(hessian, center, lattice=None, rescale=1.0, ax=None, coords_are_cartesian=False, arrows=False, **kwargs): """ Plots a 3D ellipsoid rappresenting the Hessian matrix in input. Useful to get a graphical visualization of the effective mass of a band in a single k-point. Args: hessian: the Hessian matrix center: the center of the ellipsoid in reciprocal coords (Default) lattice: Lattice object of the Brillouin zone rescale: factor for size scaling of the ellipsoid ax: matplotlib :class:`Axes` or None if a new figure should be created. coords_are_cartesian: Set to True if you are providing a center in cartesian coordinates. Defaults to False. kwargs: kwargs passed to the matplotlib function 'plot_wireframe'. Color defaults to blue, rstride and cstride default to 4, alpha defaults to 0.2. Returns: matplotlib figure and matplotlib ax Example of use: fig,ax=plot_wigner_seitz(struct.reciprocal_lattice) plot_ellipsoid(hessian,[0.0,0.0,0.0], struct.reciprocal_lattice,ax=ax) """ if (not coords_are_cartesian) and lattice is None: raise ValueError( "coords_are_cartesian False or fold True require the lattice") if not coords_are_cartesian: center = lattice.get_cartesian_coords(center) if "color" not in kwargs: kwargs["color"] = "b" if "rstride" not in kwargs: kwargs["rstride"] = 4 if "cstride" not in kwargs: kwargs["cstride"] = 4 if "alpha" not in kwargs: kwargs["alpha"] = 0.2 # calculate the ellipsoid # find the rotation matrix and radii of the axes U, s, rotation = np.linalg.svd(hessian) radii = 1.0 / np.sqrt(s) # from polar coordinates u = np.linspace(0.0, 2.0 * np.pi, 100) v = np.linspace(0.0, np.pi, 100) x = radii[0] * np.outer(np.cos(u), np.sin(v)) y = radii[1] * np.outer(np.sin(u), np.sin(v)) z = radii[2] * np.outer(np.ones_like(u), np.cos(v)) for i in range(len(x)): for j in range(len(x)): [x[i, j], y[i, j], z[i, j]] = np.dot([x[i, j], y[i, j], z[i, j]], rotation) * rescale + center # add the ellipsoid to the current axes ax, fig, plt = get_ax3d_fig_plt(ax) ax.plot_wireframe(x, y, z, **kwargs) if arrows: color = ('b', 'g', 'r') em = np.zeros((3, 3)) for i in range(3): em[i, :] = rotation[i, :] / np.linalg.norm(rotation[i, :]) for i in range(3): ax.quiver3D(center[0], center[1], center[2], em[i, 0], em[i, 1], em[i, 2], pivot='tail', arrow_length_ratio=0.2, length=radii[i] * rescale, color=color[i]) return fig, ax
gpetretto/pymatgen
pymatgen/electronic_structure/plotter.py
Python
mit
183,073
[ "BoltzTrap", "CRYSTAL", "Gaussian", "Mayavi", "VASP", "pymatgen" ]
0cebaae9b560ffcda0fbca2cc04c087961b884d67395244fa3152a1f683ea640
""" Integration tests ================== Setup: >>> import os >>> import time >>> import sqlite3 >>> import smtplib >>> from mocker import Mocker, expect, ANY, ARGS >>> >>> tmp_dir = 'tmp' >>> tmp_db = os.path.join(tmp_dir, 'tmpdb.sqlite') >>> create_tmp = not os.path.isdir(tmp_dir) >>> if create_tmp: ... os.mkdir(tmp_dir) >>> if os.path.exists(tmp_db): ... os.unlink(tmp_db) First of all, let's make sure that our SQL schema is at least valid: >>> schema = open('schema.sql').read() >>> sqlite_conn = sqlite3.connect(tmp_db) >>> sqlite_cursor = sqlite_conn.cursor() >>> sqlite_cursor.executescript(schema) #doctest: +ELLIPSIS <sqlite3.Cursor...> Now, let's register a user: >>> from .. import users >>> from .. import db >>> conn = db.Connection(tmp_db, driver=sqlite3) >>> conn.connect() >>> before_reg = int(time.time()) >>> reg_key = users.register_user('rbp@isnomore.net', 'foobar', conn) >>> results = sqlite_cursor.execute(''' ... select email, password, registration_key, registration_date ... from pending_users''').fetchall() >>> len(results) 1 >>> username, password, key, date = results[0] >>> print username rbp@isnomore.net >>> password != 'foobar' True >>> password == users.mkhash('foobar', users.Hash(password).salt) True >>> len(key) > 0 True >>> reg_key == key True >>> date >= before_reg True Trying to register a user that is already pending registration triggers an IntegrityError: >>> key = users.register_user('anxious_user@isnomore.net', 'passwd', conn) >>> users.register_user('anxious_user@isnomore.net', 'whatever', conn) Traceback (most recent call last): ... IntegrityError: column email is not unique However, if the pending user has been registered for longer than a certain (configurable) period, the old record is purged and a new registration takes place: >>> from .. config import options >>> now = time.time() >>> mocker = Mocker() >>> mock_time = mocker.mock() >>> _ = expect(mock_time.time()).result(now) >>> mock_time.time() #doctest: +ELLIPSIS <mocker.Mock ... >>> mocker.result(now + options.registration_expiration + 1) >>> mocker.replay() >>> t = users.time >>> users.time = mock_time So, the user registers for the first time: >>> key = users.register_user('late_user@isnomore.net', 'passwd', conn) >>> old = conn.get_pending_user('late_user@isnomore.net') #doctest: +ELLIPSIS >>> print old[0] late_user@isnomore.net >>> old[3] == int(now) True And then again, options.registration_expiration + 1 seconds later: >>> key = users.register_user('late_user@isnomore.net', 'passwd', conn) >>> new = conn.get_pending_user('late_user@isnomore.net') #doctest: +ELLIPSIS >>> print new[0] late_user@isnomore.net >>> new[3] == int(now + options.registration_expiration + 1) True >>> mocker.verify() >>> mocker.restore() >>> users.time = t The registration key for a user must not be in use. Trying to insert an already existing key will trigger an IntegrityError: >>> r = users.registration_key >>> users.registration_key = lambda u: 'a single reg key' >>> key = users.register_user('someone@isnomore.net', 'foobar', conn) >>> users.register_user('someone_else@isnomore.net', 'foobar', conn) Traceback (most recent call last): ... IntegrityError: column registration_key is not unique >>> users.registration_key = r The mailer.py script should be run periodically to query the database for pending users and send confirmation messages as needed. First of all, mailer has to grab a list of users that haven't been sent confirmation emails yet: >>> sqlite_cursor.execute('delete from pending_users') #doctest: +ELLIPSIS <sqlite3.Cursor ...> >>> sqlite_conn.commit() >>> conn.get_pending_users_unmailed() [] >>> key1 = users.register_user('someone@isnomore.net', 'a password', conn) >>> key2 = users.register_user('someone_else@isnomore.net', 'another one', conn) >>> to_mail = conn.get_pending_users_unmailed() >>> to_mail #doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE [(u'someone@isnomore.net', ...), (u'someone_else@isnomore.net', ...)] get_pending_users_unmailed returns a list of (email, registration key) tuples: >>> r = users.registration_key >>> users.registration_key = lambda u: 'fixed registration key' >>> key = users.register_user('another@isnomore.net', 'a password', conn) >>> to_mail_again = conn.get_pending_users_unmailed() >>> new = (set(to_mail) ^ set(to_mail_again)).pop() >>> new (u'another@isnomore.net', u'fixed registration key') >>> users.registration_key = r Only users whose confirmation email hasn't been sent yet should be returned by get_pending_users_unmailed: >>> sqlite_cursor.execute(''' ... update pending_users set confirmation_sent = 1 ... where email = 'someone_else@isnomore.net' ''') #doctest: +ELLIPSIS <sqlite3.Cursor ...> >>> sqlite_conn.commit() >>> really_to_mail = conn.get_pending_users_unmailed() >>> len(really_to_mail) 2 >>> really_to_mail #doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE [(u'someone@isnomore.net', u'...'), (u'another@isnomore.net', u'fixed registration key')] Given a list of email addresses (and each one's respective registration key), mailer should send a confirmation message to each of them. Mailer uses config.options to determine the SMTP server, "From" name and address, subject and email message template file. First mailer builds the message, an object from the Python builtin email module: >>> from .. import mailer >>> msg = mailer.create_message('someone@isnomore.net', 'a_registration_key') >>> options.reg_confirmation_from in msg['from'] True >>> '<{0}>'.format(options.reg_confirmation_from_addr) in msg['from'] True >>> print msg['to'] someone@isnomore.net >>> msg['subject'] == options.reg_confirmation_subject True >>> template = open(options.reg_confirmation_template).read() >>> msg.get_payload() == template.replace('{registration_key}', ... 'a_registration_key') True Once the message is built, mailer sends it: >>> mocker = Mocker() >>> mock_smtplib = mocker.mock() >>> mock_smtp = mocker.mock() >>> _ = expect(mock_smtplib.SMTP(options.smtp_server)).result(mock_smtp) >>> mock_smtp.sendmail(options.reg_confirmation_from_addr, ... 'someone@isnomore.net', ... msg.as_string()) #doctest:+ELLIPSIS <mocker.Mock ...> >>> mock_smtp.quit() #doctest: +ELLIPSIS <mocker.Mock ...> >>> l = mailer.smtplib >>> mailer.smtplib = mock_smtplib >>> with mocker: ... mailer.mail_confirmation('someone@isnomore.net', msg.as_string()) >>> mailer.smtplib = l Now, putting it all together: >>> mocker = Mocker() >>> mock_create_msg = mocker.replace(mailer.create_message) >>> mock_confirmation = mocker.mock() >>> mock_options = mocker.replace(options) >>> to_mail = conn.get_pending_users_unmailed() >>> user1, user2 = to_mail >>> >>> _ = expect(mock_create_msg(user1[0], user1[1])).passthrough() >>> _ = expect(mock_create_msg(user2[0], user2[1])).passthrough() >>> mock_confirmation(user1[0], ANY) #doctest: +ELLIPSIS <mocker.Mock ...> >>> mock_confirmation(user2[0], ANY) #doctest: +ELLIPSIS <mocker.Mock ...> >>> _ = expect(mock_options.db_driver).result(sqlite3) >>> _ = expect(mock_options.db_params).result(tmp_db) >>> mc = mailer.mail_confirmation >>> mailer.mail_confirmation = mock_confirmation >>> with mocker: ... results = mailer.send_pending_confirmations() >>> results['failed'] [] >>> mailer.mail_confirmation = mc After emails are sent, the affected pending users are marked as such: >>> conn.get_pending_users_unmailed() [] If an error occurs while sending a message, that users is not marked has having been sent the confirmation email: >>> mocker = Mocker() >>> mock_confirmation = mocker.replace(mailer.mail_confirmation) >>> mock_options = mocker.replace(options) >>> _ = expect(mock_confirmation(ARGS)).throw(smtplib.SMTPSenderRefused(0, '', ... 'user_with_error@isnomore.net')) >>> mock_confirmation(ARGS) #doctest: +ELLIPSIS <mocker.Mock ...> >>> _ = expect(mock_options.db_driver).result(sqlite3) >>> _ = expect(mock_options.db_params).result(tmp_db) >>> >>> key1 = users.register_user('user_with_error@isnomore.net', 'foobar', conn) >>> key2 = users.register_user('user_ok@isnomore.net', 'foobar', conn) >>> with mocker: ... results = mailer.send_pending_confirmations() >>> still_pending = conn.get_pending_users_unmailed() >>> len(still_pending) 1 >>> print still_pending[0][0] user_with_error@isnomore.net Also, mailer.send_pending_confirmations returns a dictionary whose 'failed' key points to a list of tuples (email, exception args): >>> results['failed'] [(u'user_with_error@isnomore.net', (0, '', 'user_with_error@isnomore.net'))] Once registered, the user can click on the URL contained on the email they are sent, which activates that user, given a registration key >>> r = sqlite_cursor.execute('''select registration_key ... from pending_users ... where email = 'user_ok@isnomore.net' ''') >>> key = r.fetchall()[0][0] >>> sqlite_cursor.execute('''select email from users ... where email = 'user_ok@isnomore.net' ''').fetchall() [] >>> users.activate(key, conn) And, once the user is activated, it's moved to the users table, with the same password, and removed from the pending_users table: >>> r = sqlite_cursor.execute('''select email, password from users ... where email = 'user_ok@isnomore.net' ''').fetchall() >>> email, passwd = r[0] >>> email u'user_ok@isnomore.net' >>> passwd == users.mkhash('foobar', passwd[:users.Hash._salt_len]) True >>> sqlite_cursor.execute('''select email from pending_users ... where email = 'user_ok@isnomore.net' ''').fetchall() [] Trying to re-register a user that is already active raises an error: >>> users.register_user('user_ok@isnomore.net', 'secret', conn) Traceback (most recent call last): ... UserAlreadyActiveError: user 'user_ok@isnomore.net' already exists Users that remain on the pending_users table beyond an expiration period will eventually be collected and deleted. All users registered before "now - options.registration_expiration" are considered to be expired, but we'll use a fake time (one hour into the future) here to exemplify deleting users. >>> mocker = Mocker() >>> mock_time = mocker.replace("time.time") >>> future_time = now + options.registration_expiration + 3600 >>> _ = expect(mock_time()).result(future_time) >>> old = conn.get_pending_users_registered_before(future_time) >>> set(old) == set([u'another@isnomore.net', u'someone@isnomore.net', ... u'someone_else@isnomore.net', u'user_with_error@isnomore.net']) True >>> from .. import clear_pending_users >>> with mocker: ... results = clear_pending_users.delete_expired_pending_users(conn) >>> results['failed'] [] >>> conn.get_pending_users_registered_before(future_time) [] Active users can be authenticated with their email and password: >>> sqlite_cursor.execute('delete from users') #doctest: +ELLIPSIS <sqlite3.Cursor ...> >>> sqlite_conn.commit() >>> key = users.register_user('a_new_user@isnomore.net', '1337 p455w0rd', conn) >>> users.activate(key, conn) >>> users.authenticate('a_new_user@isnomore.net', '1337 p455w0rd', conn) True >>> users.authenticate('non_user@isnomore.net', '1337 p455w0rd', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('a_new_user@isnomore.net', 'l4m3 p455w0rd', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials After a configurable number of failed authentication attempts, authentication is disabled for that user: >>> key = users.register_user('mistyper@isnomore.net', 'secret', conn) >>> users.activate(key, conn) >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) True >>> options.failed_auth_limit 3 >>> users.authenticate('mistyper@isnomore.net', 'sceret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('mistyper@isnomore.net', 'aecret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> now = int(time.time()) >>> mocker = Mocker() >>> mock_time = mocker.replace('time.time') >>> _ = expect(mock_time()).result(now) >>> with mocker: ... users.authenticate('mistyper@isnomore.net', 'SECRET', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials The account is now locked, the user can't authenticate even with the correct password: >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials The user is locked out for a period of time, after which they are allowed in once again: >>> options.login_suspended_period 300 >>> suspended_until = sqlite_cursor.execute('''select suspended_until ... from users ... where email = 'mistyper@isnomore.net' ... ''').fetchall()[0][0] >>> suspended_until == now + options.login_suspended_period True >>> mocker = Mocker() >>> mock_time = mocker.replace('time.time') >>> _ = expect(mock_time()).result(now + options.login_suspended_period//2) >>> _ = expect(mock_time()).result(now + options.login_suspended_period - 1) >>> _ = expect(mock_time()).result(now + options.login_suspended_period) >>> _ = expect(mock_time()).result(now + options.login_suspended_period + 1) >>> mocker.replay() >>> >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('mistyper@isnomore.net', 'secret', conn) True >>> mocker.restore() >>> mocker.verify() A valid authentication attempt (while the user is not suspended) clears out previous failed ones: >>> key = users.register_user('biggles@isnomore.net', 'secret', conn) >>> users.activate(key, conn) >>> options.failed_auth_limit 3 >>> users.authenticate('biggles@isnomore.net', 'wrong one', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('biggles@isnomore.net', 'still wrong', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials Here, another incorrect attempt will suspend the user. However, a valid one will reset the count: >>> users.authenticate('biggles@isnomore.net', 'secret', conn) True The following error now counts as the first one, and doesn't lock the user out: >>> users.authenticate('biggles@isnomore.net', 'wrong one', conn) Traceback (most recent call last): ... AuthenticationError: invalid authentication credentials >>> users.authenticate('biggles@isnomore.net', 'secret', conn) True Some resources are only available to certain groups of users. These groups are represented as "roles". Each user can be assigned a role: >>> key = users.register_user('brian@isnomore.net', 'secret', conn) >>> users.activate(key, conn) >>> users.authenticate('brian@isnomore.net', 'secret', conn) True >>> conn.get_user_role('brian@isnomore.net') is None True >>> conn.set_user_role('brian@isnomore.net', 'naughty boy') >>> conn.get_user_role('brian@isnomore.net') u'naughty boy' Each resource (represented by a function) can be marked as requiring users with a certain role. Functions are decorated with the @access_control decorator, which accepts an email and connection object as first parameters, and then any parameters that the function might receive. It is assumed that the front-end has already authenticated the user. >>> @users.access_control('messiah') ... def bless(people): ... return True >>> bless('brian@isnomore.net', conn, 'the meek') Traceback (most recent call last): ... UnauthorizedAccessError: User does not have the role required by this resource >>> @users.access_control('naughty boy') ... def look_on_the_bright_side_of_life(when): ... return '{0} look on the bright side of life'.format(when) >>> look_on_the_bright_side_of_life('brian@isnomore.net', conn, 'Always') 'Always look on the bright side of life' Cleaning up: >>> os.unlink(tmp_db) >>> if create_tmp: ... os.rmdir(tmp_dir) """
rbp/auth
tests/integration_tests.py
Python
mit
16,751
[ "Brian" ]
d009f462e1e848fe1cf7ec902f9da5bbc60407854243543168ebdc732ffd14f5
# coding: utf-8 from __future__ import division, unicode_literals """ Created on Jul 30, 2012 """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Jul 30, 2012" import unittest import os from pymatgen.io.smart import read_structure, read_mol, write_structure, \ write_mol from pymatgen.core.structure import Structure, Molecule from pymatgen.analysis.structure_matcher import StructureMatcher try: import openbabel as ob except ImportError: ob = None class MethodsTest(unittest.TestCase): def test_read_structure(self): test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') for fname in ("Li2O.cif", "vasprun.xml", "vasprun_Si_bands.xml", "Si.cssr"): filename = os.path.join(test_dir, fname) struct = read_structure(filename) self.assertIsInstance(struct, Structure) prim = read_structure(filename, primitive=True) self.assertLessEqual(len(prim), len(struct)) sorted_s = read_structure(filename, sort=True) self.assertEqual(sorted_s, sorted_s.get_sorted_structure()) m = StructureMatcher() for ext in [".cif", ".json", ".cssr"]: fn = "smartio_structure_test" + ext write_structure(struct, fn) back = read_structure(fn) self.assertTrue(m.fit(back, struct)) os.remove(fn) def test_read_mol(self): test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files', "molecules") for fname in ("methane.log", "c60.xyz", "ethane.gjf"): filename = os.path.join(test_dir, fname) mol = read_mol(filename) self.assertIsInstance(mol, Molecule) for ext in [".xyz", ".json", ".gjf"]: fn = "smartio_mol_test" + ext write_mol(mol, fn) back = read_mol(fn) self.assertEqual(back, mol) os.remove(fn) @unittest.skipIf(ob is None, "No openbabel") def test_read_mol_babel(self): test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files', "molecules") for fname in ("ethane.mol", ): filename = os.path.join(test_dir, fname) mol = read_mol(filename) self.assertIsInstance(mol, Molecule) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
rousseab/pymatgen
pymatgen/io/tests/test_smart.py
Python
mit
2,673
[ "pymatgen" ]
13028b9b491e1e33569fdd988dada840cb8b6df92d2551af2583c7f8daf5ac1e
#!/usr/bin/python # # Simple script which convert the FITS headers associated to Brian McLean DSS images into simplified JSON files # Fabien Chereau fchereau@eso.org # import sys import os import subprocess def allDSS(): for i in range(1,895): str = "/home/fab1/prog/stellarium/util/dssheaderToJSON.py" + " S %i %i" % (i,i+1) print str try: retcode = subprocess.call(str, shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e if __name__ == "__main__": allDSS()
Stellarium/stellarium
util/runAllDSS.py
Python
gpl-2.0
649
[ "Brian" ]
70f6827352d5b612dd7a991ea4f8273bbb2172e083f59c77832d83ef7cdb42a3
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2016 Haggi Krey, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import logging import path import pprint import pymel.core as pm import os import shutil import subprocess import sys import xml.etree.cElementTree as ET import xml.dom.minidom as minidom SHADER_DICT = {} log = logging.getLogger("renderLogger") def getShaderInfo(shaderPath): osoFiles = getOSOFiles(shaderPath) return osoFiles def getOSODirs(): try: shaderDir = os.environ['APPLESEED_OSL_SHADERS_LOCATION'] except KeyError: shaderDir = path.path(__file__).parent.parent.parent + "/shaders" osoDirs = set() for root, dirname, files in os.walk(shaderDir): for filename in files: if filename.endswith(".oso"): osoDirs.add(root.replace("\\", "/")) return list(osoDirs) def getOSOFiles(): try: shaderDir = os.environ['APPLESEED_OSL_SHADERS_LOCATION'] except KeyError: shaderDir = path.path(__file__).parent.parent.parent + "/shaders" osoFiles = set() for root, dirname, files in os.walk(shaderDir): for filename in files: if filename.endswith(".oso"): osoFiles.add(os.path.join(root, filename).replace("\\", "/")) return list(osoFiles) def getOSLFiles(): try: shaderDir = os.environ['APPLESEED_OSL_SHADERS_LOCATION'] except KeyError: shaderDir = path.path(__file__).parent.parent.parent + "/shaders" osoFiles = set() for root, dirname, files in os.walk(shaderDir): for filename in files: if filename.endswith(".osl"): osoFiles.add(os.path.join(root, filename).replace("\\", "/")) return list(osoFiles) def reverseValidate(pname): if pname == "inMin": return "min" if pname == "inMax": return "max"; if pname == "inVector": return "vector"; if pname == "inMatrix": return "matrix"; if pname == "inDiffuse": return "diffuse"; if pname == "inColor": return "color"; if pname == "outOutput": return "output"; return pname; def analyzeContent(content): d = {} currentElement = None for line in content: if len(line) == 0: continue if line.startswith("shader") or line.startswith("surface"): d['name'] = line.split(" ")[1].replace("\"", "") d['mayaClassification'] = "" d['mayaId'] = 0 d['help'] = "" d['inputs'] = [] d['outputs'] = [] currentElement = d else: if line.startswith("Default value"): currentElement['default'] = line.split(" ")[-1].replace("\"", "") if currentElement.has_key("type"): if currentElement["type"] in ["color", "vector", "output vector"]: vector = line.split("[")[-1].split("]")[0] vector = vector.strip() currentElement['default'] = map(float, vector.split(" ")) if line.startswith("Unknown default value"): if currentElement.has_key("type"): if currentElement["type"] in ["color", "vector"]: currentElement['default'] = "[ 0.0, 0.0, 0.0 ]" if line.startswith("metadata"): if "options = " in line: currentElement['options'] = line.split(" ")[-1].replace("\"", "").split("|") if "hint = " in line: currentElement['hint'] = line.split(" ")[-1].replace("\"", "") if "compAttrArrayPath = " in line: currentElement['compAttrArrayPath'] = line.split(" ")[-1].replace("\"", "") if "isArrayPlug = " in line: currentElement['isArrayPlug'] = line.split(" ")[-1].replace("\"", "") if "min = " in line: currentElement['min'] = line.split(" ")[-1] if "max = " in line: currentElement['max'] = line.split(" ")[-1] if "help = " in line: currentElement['help'] = " ".join(line.split("=")[1:]).replace("\"", "").strip() if "mayaClassification = " in line: currentElement['mayaClassification'] = " ".join(line.split("=")[1:]).replace("\"", "").strip() if "mayaId = " in line: currentElement['mayaId'] = int(line.split("=")[-1]) if line.startswith("\""): # found a parameter currentElement = {} elementName = line.split(" ")[0].replace("\"", "") currentElement['name'] = reverseValidate(elementName) currentElement['type'] = " ".join(line.split(" ")[1:]).replace("\"", "") if "output" in line: d['outputs'].append(currentElement) currentElement = d['outputs'][-1] else: d['inputs'].append(currentElement) currentElement = d['inputs'][-1] return d def readShadersXMLDescription(): xmlFile = path.path(__file__).parent.parent.parent / "resources/shaderDefinitions.xml" if not xmlFile.exists(): return try: tree = ET.parse(xmlFile) except: return shaders = tree.getroot() shaderDict = {} for shader in shaders: shDict = {} shDict['name'] = shader.find('name').text shDict['mayaClassification'] = "" element = shader.find('mayaClassification') if element is not None: shDict['mayaClassification'] = element.text shDict['mayaId'] = 0 element = shader.find('mayaId') if element is not None: shDict['mayaId'] = int(element.text) shDict['help'] = "" element = shader.find('help') if element is not None: shDict['help'] = element.text shDict['inputs'] = [] shDict['outputs'] = [] for inp in shader.find('inputs'): inpp = {} inpp['name'] = inp.find('name').text inpp['type'] = inp.find('type').text inpp['help'] = "" inpp['hint'] = "" inpp['compAttrArrayPath'] = "" inpp['isArrayPlug'] = "" inpp['min'] = 0 inpp['max'] = 1 inpp['default'] = 0 findElement = inp.find('help') if findElement is not None: inpp['help'] = findElement.text findElement = inp.find('hint') if findElement is not None: inpp['hint'] = inp.find('hint').text findElement = inp.find('compAttrArrayPath') if findElement is not None: inpp['compAttrArrayPath'] = inp.find('compAttrArrayPath').text findElement = inp.find('isArrayPlug') if findElement is not None: inpp['isArrayPlug'] = True findElement = inp.find('min') if findElement is not None: inpp['min'] = inp.find('min').text findElement = inp.find('max') if findElement is not None: inpp['max'] = inp.find('max').text findElement = inp.find('default') if findElement is not None: inpp['default'] = inp.find('default').text findElement = inp.find('options') if findElement is not None: inpp['options'] = findElement.text shDict['inputs'].append(inpp) for inp in shader.find('outputs'): inpp = {} inpp['name'] = inp.find('name').text inpp['type'] = inp.find('type').text inpp['help'] = "" shDict['outputs'].append(inpp) shaderDict[shDict['name']] = shDict global SHADER_DICT SHADER_DICT = shaderDict return shaderDict def addSubElementList(listEntry, parentElement, subName="input"): for element in listEntry: inElement = ET.SubElement(parentElement, subName) for ikey, ivalue in element.iteritems(): subElement = ET.SubElement(inElement, ikey) subElement.text = str(ivalue) def writeXMLShaderDescription(shaderDict=None): global SHADER_DICT if shaderDict is None: shaderDict = SHADER_DICT xmlFile = path.path(__file__).parent.parent.parent / "resources/shaderdefinitions.xml" root = ET.Element('shaders') for shaderKey in shaderDict.keys(): shader = shaderDict[shaderKey] sh = ET.SubElement(root, "shader") for key, value in shader.iteritems(): if key == "inputs": ins = ET.SubElement(sh, "inputs") addSubElementList(value, ins, subName="input") elif key == "outputs": ins = ET.SubElement(sh, "outputs") addSubElementList(value, ins, subName="output") else: subElement = ET.SubElement(sh, key) subElement.text = str(value) tree = ET.ElementTree(root) tree.write(xmlFile) log.debug("Writing shader info file: {0}".format(xmlFile)) # just make it nice to read xml = minidom.parse(xmlFile) pretty_xml_as_string = xml.toprettyxml() root = ET.fromstring(pretty_xml_as_string) tree = ET.ElementTree(root) tree.write(xmlFile) def updateOSLShaderInfo(force=False, osoFiles=[]): pp = pprint.PrettyPrinter(indent=4) cmd = "oslinfo -v" infoDict = {} # if we have updates we need to update the xml file as well. # first read the xml file readShadersXMLDescription() global SHADER_DICT for osoFile in osoFiles: infoCmd = cmd + " " + osoFile shaderName = path.path(osoFile).basename().replace(".oso", "") process = subprocess.Popen(infoCmd, bufsize=1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) content = [] while 1: line = process.stdout.readline() line = line.strip() content.append(line) if not line: break infoDict[shaderName] = analyzeContent(content) SHADER_DICT[shaderName] = infoDict[shaderName] # pp.pprint(infoDict) writeXMLShaderDescription() return infoDict def compileAllShaders(): try: shaderDir = os.environ['APPLESEED_OSL_SHADERS_LOCATION'] except KeyError: # we expect this file in module/scripts so we can try to find the shaders in ../shaders log.error("Could not get path from APPLESEED_OSL_SHADERS_LOCATION. Trying to find the shaders dir relative to current file: {0}".format(__file__)) shaderDir = path.path(__file__).parent.parent.parent / "shaders" if shaderDir.exists(): log.info("Using found shaders directory {0}".format(shaderDir)) include_dir = os.path.join(shaderDir, "src/include") oslc_cmd = "oslc" failureDict = {} osoInfoShaders = [] for root, dirname, files in os.walk(shaderDir): for filename in files: if filename.endswith(".osl"): oslPath = os.path.join(root, filename) dest_dir = root.replace("\\", "/").replace("shaders/src", "shaders") + "/" if not os.path.exists(dest_dir): os.makedirs(dest_dir) osoOutputPath = dest_dir + filename.replace(".osl", ".oso") osoOutputFile = path.path(osoOutputPath) oslInputFile = path.path(oslPath) if osoOutputFile.exists(): if osoOutputFile.mtime > oslInputFile.mtime: continue else: osoOutputFile.remove() saved_wd = os.getcwd() os.chdir(root) compileCmd = oslc_cmd + " -v -I" + include_dir + ' -o ' + osoOutputPath + ' ' + oslInputFile process = subprocess.Popen(compileCmd, bufsize=1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) progress = [] fail = False while 1: line = process.stdout.readline() if not line: break log.debug(line) line.strip() progress.append(line) pm.mel.trace(line.strip()) if "error" in line: fail = True if fail: failureDict[osoOutputFile.basename()] = progress else: osoInfoShaders.append(osoOutputPath) os.chdir(saved_wd) if len(failureDict.keys()) > 0: log.info("\n\nShader compilation failed for:") for key, content in failureDict.iteritems(): log.info("Shader {0}\n{1}\n\n".format(key, "\n".join(content))) else: if len(osoInfoShaders) > 0: updateOSLShaderInfo(force=False, osoFiles=osoInfoShaders)
haggi/appleseed-maya
module/scripts/appleseed_maya/osltools.py
Python
mit
14,236
[ "VisIt" ]
741cf1326ac19d48b9f4a28f6f7f7a0359773857a2986d129a9281d388982026
# $HeadURL$ __RCSID__ = "$Id$" from DIRAC.AccountingSystem.Client.Types.BaseAccountingType import BaseAccountingType import DIRAC class DataOperation( BaseAccountingType ): def __init__( self ): BaseAccountingType.__init__( self ) self.definitionKeyFields = [ ( 'OperationType' , "VARCHAR(32)" ), ( 'User', "VARCHAR(32)" ), ( 'ExecutionSite', 'VARCHAR(32)' ), ( 'Source', 'VARCHAR(32)' ), ( 'Destination', 'VARCHAR(32)' ), ( 'Protocol', 'VARCHAR(32)' ), ( 'FinalStatus', 'VARCHAR(32)' ) ] self.definitionAccountingFields = [ ( 'TransferSize', 'BIGINT UNSIGNED' ), ( 'TransferTime', 'FLOAT' ), ( 'RegistrationTime', 'FLOAT' ), ( 'TransferOK', 'INT UNSIGNED' ), ( 'TransferTotal', 'INT UNSIGNED' ), ( 'RegistrationOK', 'INT UNSIGNED' ), ( 'RegistrationTotal', 'INT UNSIGNED' ) ] self.bucketsLength = [ ( 86400 * 3, 900 ), #<3d = 15m ( 86400 * 8, 3600 ), #<1w+1d = 1h ( 15552000, 86400 ), #>1w+1d <6m = 1d ( 31104000, 604800 ), #>6m = 1w ] self.checkType() self.setValueByKey( 'ExecutionSite', DIRAC.siteName() )
Sbalbp/DIRAC
AccountingSystem/Client/Types/DataOperation.py
Python
gpl-3.0
1,652
[ "DIRAC" ]
8b7f80e90a47156393b8388830d3c6e996f45774d9bc45985da83f245fbb908e
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Training to forget nuisance variables.""" import collections import os from absl import app from absl import flags from absl import logging import numpy as np import pandas as pd from scipy import sparse from six.moves import range from six.moves import zip import six.moves.cPickle as pickle import tensorflow.compat.v1 as tf from tensorflow.compat.v1 import gfile from correct_batch_effects_wdn import io_utils from correct_batch_effects_wdn import transform from tensorflow.python.ops import gen_linalg_ops # pylint: disable=g-direct-tensorflow-import INPUT_NAME = "inputs" OUTPUT_NAME = "outputs" DISCRIMINATOR_NAME = "discriminator" CLASSIFIER_NAME = "classifier" UNIT_GAUSS_NAME = "unit_gauss" CRITIC_LAYER_NAME = "critic_layer" POSSIBLE_LOSSES = (DISCRIMINATOR_NAME, CLASSIFIER_NAME, UNIT_GAUSS_NAME) INPUT_KEY_INDEX = 0 REGISTRY_NAME = "params_registry_python_3" WASSERSTEIN_NETWORK = "WassersteinNetwork" WASSERSTEIN_2_NETWORK = "Wasserstein2Network" MEAN_ONLY_NETWORK = "MeanOnlyNetwork" WASSERSTEIN_SQRD_NETWORK = "WassersteinSqrdNetwork" WASSERSTEIN_CUBED_NETWORK = "WassersteinCubedNetwork" POSSIBLE_NETWORKS = [ WASSERSTEIN_NETWORK, WASSERSTEIN_2_NETWORK, WASSERSTEIN_SQRD_NETWORK, WASSERSTEIN_CUBED_NETWORK, MEAN_ONLY_NETWORK ] FLAGS = flags.FLAGS flags.DEFINE_string("input_df", None, "Path to the embedding dataframe.") flags.DEFINE_string("save_dir", None, "location of file to save.") flags.DEFINE_integer("num_steps_pretrain", None, "Number of steps to pretrain.") flags.DEFINE_integer("num_steps", None, "Number of steps (after pretrain).") flags.DEFINE_integer("disc_steps_per_training_step", None, "Number critic steps" "to use per main training step.") flags.DEFINE_enum("network_type", "WassersteinNetwork", POSSIBLE_NETWORKS, "Network to use. Can be WassersteinNetwork.") flags.DEFINE_integer("batch_n", 10, "Number of points to use per minibatch" "for each loss.") flags.DEFINE_float("learning_rate", 1e-4, "Initial learning rate to use.") flags.DEFINE_float("epsilon", 0.01, "Regularization for covariance.") flags.DEFINE_integer("feature_dim", 192, "Number of feature dimensions.") flags.DEFINE_integer("checkpoint_interval", 4000, "Frequency to save to file.") flags.DEFINE_spaceseplist("target_levels", "compound", "dataframe target levels.") flags.DEFINE_spaceseplist("nuisance_levels", "batch", "dataframe nuisance levels.") flags.DEFINE_integer( "layer_width", 2, "Width of network to use for" "approximating the Wasserstein distance.") flags.DEFINE_integer( "num_layers", 2, "Number of layers to use for" "approximating the Wasserstein distance.") flags.DEFINE_string( "reg_dir", None, "Directory to registry file, or None to" "save in save_dir.") flags.DEFINE_float("lambda_mean", 0., "Penalty for the mean term of the affine" "transformation.") flags.DEFINE_float("lambda_cov", 0., "Penalty for the cov term of the affine" "transformation.") flags.DEFINE_integer("seed", 42, "Seed to use for numpy.") flags.DEFINE_integer("tf_seed", 42, "Seed to use for tensorflow.") flags.DEFINE_float( "cov_fix", 0.001, "Multiple of identity to add if using" "Wasserstein-2 distance.") ################################################################################ ##### Functions and classes for storing and retrieving data ################################################################################ def get_dense_arr(matrix): """Convert a sparse matrix to numpy array. Args: matrix (matrix, sparse matrix, or ndarray): input Returns: dense numpy array. """ if sparse.issparse(matrix): return matrix.toarray() else: return np.array(matrix) class DataShuffler(object): """Object to hold and shuffle data. Adapted from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py Attributes: inputs (ndarray): The inputs specified in __init__. outputs (ndarray): The outputs specified in __init__. """ def __init__(self, inputs, outputs, random_state): """Inits DataShuffler given inputs, outputs, and a random state. Args: inputs (ndarray): 2-dimensional array containing the inputs, where each row is an individual input. The columns represent the different dimensions of an individual entry. outputs (ndarray): 2-dimensional array containing the outputs, where each row is an individual output. random_state (None or int): seed to feed to numpy.random. """ assert inputs.shape[0] == outputs.shape[0] self.inputs = inputs self.outputs = outputs self._epochs_completed = -1 self._num_examples = inputs.shape[0] self._random_state = random_state self._next_indices = [] def next_batch(self, batch_size, shuffle=True): """Helper method for next_batch. Args: batch_size (int): Number of items to pick. shuffle (bool): whether to shuffle the data or not. Returns: A tuple of 2-dimensional ndarrays whose shape along the first axis is equal to batch_size. The rows in the first element correspond to inputs, and in the second element to the outputs. """ indices = [] while len(indices) < batch_size: if not self._next_indices: self._epochs_completed += 1 self._next_indices = list(reversed(list(range(self._num_examples)))) if shuffle: self._random_state.shuffle(self._next_indices) indices.append(self._next_indices.pop()) return (get_dense_arr(self.inputs[indices]), get_dense_arr(self.outputs[indices])) def _make_canonical_key(x): """Try to convert to a hashable type. First, if the input is a list of length 1, take its first component instead. Next, try to convert to a tuple if not hashable. Args: x (list, tuple, string, or None): input to convert to a key Returns: Hashable object """ if isinstance(x, list) and len(x) == 1: x = x[0] if not isinstance(x, collections.Hashable): return tuple(x) else: return x def split_df(df, columns_split): """Split a dataframe into two by column. Args: df (pandas dataframe): input dataframe to split. columns_split (int): Column at which to split the dataframes. Returns: df1, df2 (pandas dataframes): Split df into two dataframe based on column. The first has the first column_split-1 columns, and the second has columns columns_split onward. """ return df.iloc[:, :columns_split], df.iloc[:, columns_split:] def tuple_in_group_with_wildcards(needle, haystack): """Checks if needle is in haystack, allowing for wildcard components. Returns True if either needle or haystack is None, or needle is in haystack. Components in haystack are tuples. These tuples can have entries equal to None which serve as wildcard components. For example, if haystack = [(None, ...), ...], The first tuple in haystack has a wildcard for its first component. Args: needle (tuple): tuple to check if in group haystack (list): list of tuples of the same dimensions as tup. Returns: True if the tuple is in the group, False otherwise Raises: ValueError: Length of tup must match length of each tuple in group." """ if needle is None or haystack is None: return True if any(len(needle) != len(it_needle) for it_needle in haystack): raise ValueError("Length of tup must match length of each tuple in group.") for it_needle in haystack: if all(needle_comp == it_needle_comp or it_needle_comp is None for needle_comp, it_needle_comp in zip(needle, it_needle)): return True return False class DatasetHolder(object): """Object to hold datasets from which minibatches are sampled. Attributes: df_with_input_one_hot (pandas dataframe): Dataframe formatted as inputs including one-hot encoding for relevant categories. data_shufflers (instances of data_shuffler): The stored data shufflers. input_dim (int): Shape of original dataframe df used as an input. encoding_to_num (dict): Maps each encoding used to a unique integer. """ def __init__(self, df, input_category_level=None, batch_input_info=None, input_output_type=np.array, random_state=None): """Inits DatasetHolder given a pandas dataframe and specifications. Args: df (pandas dataframe): all the input points, labeled by index. input_category_level (int, level name, or sequence of such, or None): Same as level used by pandas groupby method. Granularity level for labels added to inputs, unless no_input_labels=True. In that case the original inputs are provided batch_input_info (string or None): Formatting for the inputs input_output_type (class or module to store input and output information): Currently supports sparse.lil_matrix and np.array. np.array is the default setting. random_state (np.random.RandomState): Instance of RandomState used for shuffling data. Raises: ValueError: input_output_type not implemented. Use np.array or sparse.lil_matrix. """ if input_output_type not in [np.array, sparse.lil_matrix]: raise ValueError("input_output_type not implemented. Use np.array or" "sparse.lil_matrix.") self._input_output_type = input_output_type if input_output_type == np.array: self._zeros_maker = np.zeros else: self._zeros_maker = sparse.lil_matrix self._input_category_level = input_category_level self._batch_input_info = batch_input_info self.data_shufflers = collections.OrderedDict() self.input_dim = df.shape[1] self._num_input_categories = len(df.columns) self.df_with_input_one_hot = self.categorize_one_hot( df, category_level=self._input_category_level, drop_original=False) input_one_hot = self.df_with_input_one_hot.drop( self.df_with_input_one_hot.columns[list(range(self.input_dim))], axis=1) keys = [tuple(row) for row in input_one_hot.values] unique_keys = list(collections.OrderedDict.fromkeys(keys)) self.encoding_to_num = {tuple(row): i for i, row in enumerate(unique_keys)} if random_state: self._random_state = random_state else: self._random_state = np.random.RandomState(seed=42) def get_random_state(self): """Get the random state. This is useful for testing. Returns: random_state (numpy random state). """ return self._random_state def add_shufflers(self, group_level=None, label_level=None, which_group_labels=None): """Add data_shuffler instances to the DatasetHolder. Args: group_level (int, level name, or sequence of such, or None): Same as level used by pandas groupby method, except when None. Indicates groups of inputs over which shufflers are created. label_level (int, level name, or sequence of such, or None): Same as level used by pandas groupby method, except when None. Indicates level to make distinct in outputs. which_group_labels (list or None): List to indicate which group_level values to use, or None to use all the possible ones. Returns: new_data_shufflers (dict): The newly added DataShuffler instances. """ if group_level is None: groups = [[None, self.df_with_input_one_hot]] else: groups = self.df_with_input_one_hot.groupby(level=group_level) new_data_shufflers = {} for group_label, df_piece in groups: if not tuple_in_group_with_wildcards(group_label, which_group_labels): continue label_level_key = _make_canonical_key(label_level) data_shuffler_key = (group_label, label_level_key) data_shuffler = self.make_data_shuffler( df_piece, output_category_level=label_level) new_data_shufflers[data_shuffler_key] = data_shuffler self.data_shufflers.update(new_data_shufflers) return new_data_shufflers def make_data_shuffler(self, df_with_input_one_hot, output_category_level=None): """Generate a data shuffler from a given dataframe. Args: df_with_input_one_hot(pandas dataframe): Rows are known points. output_category_level (int, level name, or sequence of such, or None): Same as level used by pandas groupby method, except when None. Returns: a data_shuffler instance. The shuffler maps entries in the given dataframe to a one hot encoding of the labels at the provided granularity level. Raises: ValueError: Unknown value for batch_input_info. """ input_df, input_one_hot = split_df(df_with_input_one_hot, self._num_input_categories) output_one_hot = self.categorize_one_hot( input_df, category_level=output_category_level) outputs = self._input_output_type(output_one_hot.values) if self._batch_input_info is not None: if self._batch_input_info == "multiplexed": inputs = self.encoding_to_multiplexed_encoding(input_df.values, input_one_hot.values) elif self._batch_input_info == "one_hot": inputs = self._input_output_type(df_with_input_one_hot.values) else: raise ValueError("unknown value for batch_input_info.") else: inputs = self._input_output_type(input_df.values) return DataShuffler(inputs, outputs, self._random_state) def categorize_one_hot(self, df, category_level=None, drop_original=True): """Generate one-hot encoding from a given dataframe and selected categories. Args: df (pandas dataframe): input dataframe. category_level (int, level name, or sequence of such, or None): Same as level used by pandas groupby method, except when None. Used to indicate which indices to use for one-hot encoding. drop_original (bool): whether or not to drop the original table, leaving only the one-hot encoding vector. Returns: A tuple (df_one_hot, num_columns) where df_one_hot is the generated dataframe and num_columns is the number of columns of the original input dataframe df. """ ## Ensure dataframe indices are strings index_names = df.index.names index = df.index.map(mapper=lambda x: tuple(str(v) for v in x)) index.names = index_names df.index = index num_columns = len(df.columns) ## convert category_level from index to row values df_reset_index = df.reset_index(category_level) ## convert non-embedding values to one-hot encoding df_with_one_hot = pd.get_dummies(df_reset_index) ## restore indices df_with_one_hot = pd.DataFrame(data=df_with_one_hot.values, index=df.index) if drop_original: _, one_hot_df = split_df(df_with_one_hot, num_columns) return one_hot_df else: return df_with_one_hot def encoding_to_multiplexed_encoding(self, arr, encoding): """Generate a multiplexed encoding. For each entry, we have a row from arr and a row from encoding, specifying the original inputs the encoding value. In the multiplexed encoding scheme, the new dimension is num_bins * (num_dim + 1), where num_dim is the dimension of the original arr, and num_bins is the number of unique encoding values. Almost all values are set to zero, except for the values in bin i, where i is an index corresponding to the encoding value. Bin i is populated by the original entry from arr, followed by a 1. Args: arr (ndarray): 2 dimensional numpy array representing the original inputs. The rows are the individual entries, and the columns are the various coorindates. encoding (ndarray): 2 dimensional numpy array whose rows represent encodings. Returns: multiplexed_encoding (ndarray): 2 dimensional array as described above. Raises: ValueError: First dimension of arr and encoding must match. """ if arr.shape[0] != encoding.shape[0]: raise ValueError("First dimension of arr and encoding must match.") num_points = arr.shape[0] num_dim = arr.shape[1] num_categories = len(self.encoding_to_num) ones = np.ones((num_points, 1)) values_with_ones = np.hstack((arr, ones)) ## TODO(tabakg): make this faster multiplexed_values = self._zeros_maker( (num_points, (num_dim + 1) * num_categories)) for row_idx, (value, enc) in enumerate(zip(values_with_ones, encoding)): bin_num = self.encoding_to_num[tuple(enc)] multiplexed_values[row_idx, bin_num * (num_dim + 1):(bin_num + 1) * (num_dim + 1)] = value return multiplexed_values ################################################################################ ##### Code for Neural Network ################################################################################ def reverse_gradient(tensor): return -tensor + tf.stop_gradient(2 * tensor) def make_tensor_dict(variable): """Returns a function that acts like a dictionary of tensors. Notice that the values provided to tf.case must be functions, which may have a particular scope. Since our input is a dictionary, we have to include its values in the scope of each of the functions provided to tf.case. Args: variable (dict): Input dictionary. Returns: f (function): A function mapping the keys from the given dictionary to its values in tensorflow. """ ## TODO(tabakg): consider using tf.HashTable as a possible alternative. def variable_func(x): return lambda: variable[x] def dict_func(x): return tf.case( {tf.reduce_all(tf.equal(x, k)): variable_func(k) for k in variable}) return dict_func def make_wb(input_dim, output_dim, name): w = tf.Variable( np.eye(max(input_dim, output_dim))[:input_dim, :output_dim], name="w_" + name, dtype=tf.float32) b = tf.Variable(np.zeros(output_dim), name="b_" + name, dtype=tf.float32) return w, b def make_discriminator_model(input_dim, activation, layer_width, num_layers): """Generates multi-layer model from the feature space to a scalar. Args: input_dim (int): Number of dimensions of the inputs. activation (function): activation layers to use. layer_width (int): Number of neurons per layer. num_layers (int): Number of layers not including the inputs. Returns: discriminator_model (function): Maps an input tensor to the output of the generated network. """ w = {} b = {} w[0], b[0] = make_wb(input_dim, layer_width, name=CRITIC_LAYER_NAME + "0") for i in range(1, num_layers): w[i], b[i] = make_wb( layer_width, layer_width, name=CRITIC_LAYER_NAME + str(i)) w[num_layers], b[num_layers] = make_wb( layer_width, 1, name=CRITIC_LAYER_NAME + str(num_layers)) def discriminator_model(x0): x = {0: x0} for i in range(num_layers): x[i + 1] = activation(tf.matmul(x[i], w[i]) + b[i]) return tf.matmul(x[num_layers], w[num_layers]) + b[num_layers] return discriminator_model def wasserstein_distance(x_, y_, layer_width, num_layers, batch_n, penalty_lambda=10., activation=tf.nn.softplus, seed=None): """Estimator of the Wasserstein-1 distance between two distributions. This is based on the loss used in the following paper: Gulrajani, Ishaan, et al. "Improved training of wasserstein gans." arXiv preprint arXiv:1704.00028 (2017). One important difference between the following implementation and the paper above is that we only use the gradient constraint from above. This seems to work better for our problem in practice. Args: x_ (tf.Tensor): Empirical sample from first distribution. Its dimensions should be [batch_n, input_dim] y_ (tf.Tensor): Empirical sample from second distribution. Its dimensions should be [batch_n, input_dim]. layer_width (int): Number of neurons to use for the discriminator model. num_layers (int): Number of layers to use for the discriminator model. batch_n (int): Number of elements per batch of x_ and y_. penalty_lambda (float): Penalty used to enforce the gradient condition. Specifically, the norm of discriminator_model should be no more than 1. activation (function): activation layers to use. seed (int): Used to randomly pick points where the gradient is evaluated. Using seed=None will seed differently each time the function is called. However, if using a global seed (tf.set_random_seed(seed)), this will reproduce the same results for each run. Returns: disc_loss (scalar tf.Tensor): The estimated Wasserstein-1 loss. gradient_penalty (scalalr tf.Tensor):: Value on the gradient penalty. discriminator_model (function): The function used to estimate the Wasserstein distance. """ ## Get the number of elements and input size _, input_dim = x_.get_shape().as_list() ## make discriminator discriminator_model = make_discriminator_model(input_dim, activation, layer_width, num_layers) ## random point for gradient penalty epsilon_rand = tf.random_uniform([batch_n, 1], minval=0, maxval=1, dtype=tf.float32, seed=seed) ## make this constant to test source of non-determinism. ## At least on desktop machine, this did not cause non-determinism. # epsilon_rand = tf.constant(0.5, shape=[batch_n, 1], dtype=tf.float32) x_hat = epsilon_rand * x_ + (1.0 - epsilon_rand) * y_ ## gradient penalty (gradient,) = tf.gradients(discriminator_model(x_hat), [x_hat]) gradient_penalty = penalty_lambda * tf.square( tf.maximum(0.0, tf.norm(gradient, ord=2) - 1.0)) ## calculate discriminator's loss disc_loss = ( tf.reduce_mean(discriminator_model(y_) - discriminator_model(x_)) + gradient_penalty) return disc_loss, gradient_penalty, discriminator_model def cov_tf(mean_x, x): """Compute the sample covariance matrix. Args: mean_x (tf.Tensor): Dimensions should be [1, input_dim] x (tf.Tensor): Dimensions should be [batch_n, input_dim] Returns: cov_xx (tf.Tensor): covariance of x. """ mean_centered_x = x - mean_x n = tf.cast(tf.shape(x)[0], tf.float32) ## number of points return tf.matmul(tf.transpose(mean_centered_x), mean_centered_x) / (n - 1) def mat_sqrt_tf(mat): """Compute the square root of a non-negative definite matrix.""" return gen_linalg_ops.matrix_square_root(mat) ### old version -- not sure if this would support gradients... # [e, v] = tf.self_adjoint_eig(mat) # return tf.matmul(tf.matmul(v, tf.diag(tf.sqrt(e))), tf.transpose(v)) def wasserstein_2_distance(x_, y_, mean_only=False): """Compute the wasserstein-2 distance squared between two distributions. This uses the closed form and assumes x_ and y_ are sampled from Gaussian distributions. Based on two_wasserstein_tf in research/biology/diagnose_a_well/analysis/distance.py Args: x_ (tf.Tensor): Empirical sample from first distribution. Its dimensions should be [batch_n, input_dim] y_ (tf.Tensor): Empirical sample from second distribution. Its dimensions should be [batch_n, input_dim]. mean_only (bool): Restrict to use only the mean part. Returns: wasserstein-2 distance between x_ and y_. """ mean_x_ = tf.reduce_mean(x_, axis=0, keep_dims=True) mean_y_ = tf.reduce_mean(y_, axis=0, keep_dims=True) if mean_only: return transform.sum_of_square(mean_x_ - mean_y_) ## If not using mean_only, compute the full W-2 distance metric: ## TESTING: adding identity to avoid error cov_x_ = cov_tf(mean_x_, x_) + FLAGS.cov_fix * tf.eye(FLAGS.feature_dim) cov_y_ = cov_tf(mean_y_, y_) + FLAGS.cov_fix * tf.eye(FLAGS.feature_dim) sqrt_cov_x_ = mat_sqrt_tf(cov_x_) prod = tf.matmul(tf.matmul(sqrt_cov_x_, cov_y_), sqrt_cov_x_) return transform.sum_of_square(mean_x_ - mean_y_) + tf.trace(cov_x_ + cov_y_ - 2.0 * mat_sqrt_tf(prod)) class Network(object): """Learns features that forget desired information. Since we may want different losses for different parts of the data, we use an instance of DatasetHolder containing instances of DataShuffler. They keys for the dictionary attributes are the same as the ones used for the DataShuffler instance, unless otherwise noted. There are several implementations, using ideas from the following paper to train a discriminator (critic), and worsen its performance during training: Ganin, Yaroslav, and Victor Lempitsky. "Unsupervised domain adaptation by backpropagation." International Conference on Machine Learning. 2015. This class has only the attributes common to all networks we will use for experiments. Inheriting networks will have additional components completing the network and implementaing train, predict, and evaluate. Atributes: holder (DatasetHolder): Holds the various DataShuffler instances to use. loss_specifiers (dict): Maps keys to loss types. losses (dict): Maps each loss type to a dictionary, which maps keys to the relevant tensorflow objects representing losses. input_dim_with_encoder (int): Total input size, including encoding. input_dim (int): Input size, not including encoding. encoding_dim (int): Input size of the encoding. """ def __init__(self, holder, feature_dim, batch_n): """Inits Network with a given instance of DatasetHolder and parameters. Args: holder (instance of DatasetHolder): Provides data to train model feature_dim (int): Dimension of feature space. Currently supports the same dimension as the input space only. The reason is that for now we wish to initialize the transformation to the identity. However, this could be extended in the future. batch_n (int): Number of points to use from each DataShuffler during training. Currently this is the same for each DataShuffler. Raises: ValueError: Currently only supporting feature_dim == input_dim. """ self.holder = holder self.losses = {loss: {} for loss in POSSIBLE_LOSSES} ## initialize useful dimensions and constants _, self._input_dim_with_encoder = holder.df_with_input_one_hot.shape self._input_dim = holder.input_dim self._encoding_dim = self._input_dim_with_encoder - self._input_dim self._feature_dim = feature_dim if self._input_dim != self._feature_dim: raise ValueError("Currently only supporting feature_dim == input_dim. " "But we have feature_dim = %s and input_dim = %s" % (feature_dim, holder.input_dim)) self._batch_n = batch_n def ensure_is_lst(z): """If a variable is not a list, return a list with only the variable. Args: z (object): input variable Returns: z if it is a list, otherwise [z] """ if isinstance(z, list): return z else: return [z] def get_filtered_key(input_key, indices): """Filter input keys to indices. Args: input_key (tuple): Contains input key information. indices: Which indices to select from the input key. Returns: filtered_key (tuple): The components of the input key designated by indices. """ return tuple([input_key[i] for i in indices]) def sum_of_square(a): """Sum of squared elements of Tensor a.""" return tf.reduce_sum(tf.square(a)) class WassersteinNetwork(Network): """Network with Wasserstein loss to forget batch effects. This network imposes only Wasserstein losses given a DatasetHolder containing instances of Datashuffler. The DataShuffler instances in the DatasetHolder are indexed by keys corresponding to input index levels for each DatasetHolder, as well as some specified output values. Here we only use the inputs (first component of each key, which we will call the input key). For example, this element might have form: (drug1, batch3). The arguments target_levels and nuisance_levels are used to specify the indices of the input key that will correspond to variables across which forgetting occurs, and variables that should be forgotten, respectively. That is, for each unique combination of target_levels, we consider the Wasserstein loss of each possible pairwise combination of nuisance_levels. For example, in the case when the input key has two elements (drug and batch in that order), specifying target_levels=[0] and nuisance_levels=[1] would construct the pairwise Wasserstein loss between all possible batches for each fixed individual drug. For this network, impose the condition that all DataShuffler instances have keys with matching input dimensionality. This ensures they all contain the necessary information to match distributions across some label categories but not others. The transformation from the inputs to the features is currently stored using the dictionaries w and b. This should be modified if a nonlinear function is used instead. Attributes: wass_loss_target (dict): Maps target keys to the sum of pairwise Wasserstine losses for the possible nuisance variables with the same target key. Note: The losses are the negative Wasserstein distances. grad_pen_target (dict): Maps target keys to the sum of pairwise gradient penalties for the possible nuisance variables with the same target key. w (dict): Mapping from keys to w tensorflow tensors going from inputs to features. b (dict): Mapping from keys to b tensorflow tensors going from inputs to features. ignore_disc (bool): If this is true, do not train a discriminator. This should be set to True when using a distance that does not need to be learned, e.g. the Wasserstein-2 distance. """ def __init__(self, holder, feature_dim, batch_n, target_levels, nuisance_levels, layer_width=2, num_layers=2, lambda_mean=0., lambda_cov=0., power=1., ignore_disc=False, mean_only=False): """Inits WassersteinNetwork. Args: holder (instance of DatasetHolder): Provides data to train model feature_dim (int): Dimension of feature space. Currently supports the same dimension as the input space only. batch_n (int): Number of points to use from each DataShuffler during training. Currently this is the same for each DataShuffler. target_levels (int or list of ints): Index or indices indicating which components of the input keys should have the property that for points sampled with the same values for these components the distributions should be indistinguishable. nuisance_levels (int or list of ints): Index or indices indicating which components of the input keys layer_width (int): number of neurons to use per layer for each function estimating a Wasserstein distance. num_layers (int): number of layers to use for estimating the Wasserstein loss (not including input). lambda_mean (float): penalty term for the mean term of the transformation. lambda_cov (float): penalty term for the cov term of the transformation. power (float): power of each pair-wise wasserstein distance to use. ignore_disc (bool): If this is true, do not train a discriminator. This should be set to True when using a distance that does not need to be learned, e.g. the Wasserstein-2 distance. mean_only (bool): Using the Wasserstein-2 distance, but only the mean component (i.e. no covariance dependence). This is for experimental purposes. Raises: ValueError: Keys must have the same input dimensionality. """ super(WassersteinNetwork, self).__init__(holder, feature_dim, batch_n) self._layer_width = layer_width self._num_layers = num_layers self._target_levels = ensure_is_lst(target_levels) self._nuisance_levels = ensure_is_lst(nuisance_levels) self._lambda_mean = lambda_mean self._lambda_cov = lambda_cov shufflers = holder.data_shufflers ## The first component of each key indicates which categories have been ## used for sampling (i.e. the input keys). input_key_lengths = [len(key[INPUT_KEY_INDEX]) for key in shufflers] if not all(length == input_key_lengths[0] for length in input_key_lengths): raise ValueError("Keys must have the same input dimensionality.") ## Generate all possible keys using only the components of the target ## or nuisance variables. self._unique_targets = sorted( list( set([ get_filtered_key(s[INPUT_KEY_INDEX], self._target_levels) for s in shufflers ]))) self._unique_nuisances = sorted( list( set([ get_filtered_key(s[INPUT_KEY_INDEX], self._nuisance_levels) for s in shufflers ]))) ## Map from each possible target key to all input keys that generated it. self._keys_for_targets = collections.defaultdict(list) for target in self._unique_targets: for s in shufflers: if target == get_filtered_key(s[INPUT_KEY_INDEX], self._target_levels): self._keys_for_targets[target].append(s) ## Generate input placeholders. self._x_inputs, self._x_vals = self.get_input_vals() ## Make features. self.w, self.b, self._features = self.add_input_to_feature_layer() ## Generate pairwise Wasserstein losses. if ignore_disc: self.wass_loss_target = self.pairwise_wasserstein_2(mean_only=mean_only) self.grad_pen_target = None self.ignore_disc = True else: self.wass_loss_target, self.grad_pen_target = self.pairwise_wasserstein( power=power) self.ignore_disc = False def get_input_vals(self): """Obtain the input values from a given dataframe. There might be additional encodings which we wish to strip away. The additional encodings have dimension _encoding_dim and appear first. The input values have dimension _input_dim and appear second. Returns: x_vals (dict): Maps input keys to placeholders for the input values. """ x_vals = {} x_inputs = {} for key in self.holder.data_shufflers: x_inputs[key] = tf.placeholder( tf.float32, [None, self._input_dim_with_encoder], name="x_" + INPUT_NAME) x_vals[key], _ = tf.split(x_inputs[key], [self._input_dim, self._encoding_dim], 1) return x_inputs, x_vals def add_input_to_feature_layer(self): """Add a layer from the inputs to features. The transformation for inputs with the same nuisance variables is fixed. Returns: features (dict): Maps each data_shuffler key to the feature tensor. """ w = {} b = {} features = {} for nuisance_key in self._unique_nuisances: w[nuisance_key], b[nuisance_key] = make_wb( self._input_dim, self._feature_dim, name=INPUT_NAME) for key in self.holder.data_shufflers: nuisance_key = get_filtered_key(key[INPUT_KEY_INDEX], self._nuisance_levels) features[key] = tf.matmul(self._x_vals[key], w[nuisance_key] + b[nuisance_key]) return w, b, features def pairwise_wasserstein(self, power=1.): """Generate pairwise Wasserstein losses. The pairs are the various nuisance variables (e.g. batch). This is done separately for each target variable (e.g. compound). Args: power (float): power of each pair-wise wasserstein distance to use. Returns: wass_loss_target (dict): Maps from target keys to sum of pairwise losses. grad_pen_target (dict): Maps from target keys to sum of pairwise gradient penalties. """ wass_loss_target = {} grad_pen_target = {} ## Gradient reversal if using a discriminator. grad_rev_features = { key: reverse_gradient(self._features[key]) for key in self._features } for target in self._unique_targets: num_per_target = len(self._keys_for_targets[target]) # When the target appears in multiple domains. if num_per_target > 1: normalization = num_per_target * (num_per_target - 1) / 2. wass_loss_target[target] = 0 grad_pen_target[target] = 0 ## Iterate through all pairs of nuisance for a given target for i in range(num_per_target): for j in range(i + 1, num_per_target): key_i = tuple(self._keys_for_targets[target][i]) key_j = tuple(self._keys_for_targets[target][j]) ## Generate W1 distance and gradient penalty. wass_dists, grad_pens, _ = wasserstein_distance( grad_rev_features[key_i], grad_rev_features[key_j], self._layer_width, self._num_layers, self._batch_n, seed=None) wass_loss_target[target] += tf.math.pow(wass_dists, power) / normalization grad_pen_target[target] += grad_pens / normalization return wass_loss_target, grad_pen_target def pairwise_wasserstein_2(self, mean_only=False): """Generate pairwise Wasserstein-2 squared losses. This uses the closed-form solution assuming Guassian distributions. The pairs are the various nuisance variables (e.g. batch). This is done separately for each target variable (e.g. compound). Args: mean_only (bool): Restrict to use only the mean part. Returns: wass_loss_target (dict): Maps from target keys to sum of pairwise losses. grad_pen_target (dict): Maps from target keys to sum of pairwise gradient penalties. """ wass_loss_target = {} for target in self._unique_targets: num_per_target = len(self._keys_for_targets[target]) # When the target appears in multiple domains. if num_per_target > 1: wass_loss_target[target] = 0 normalization = num_per_target * (num_per_target - 1) / 2. ## Iterate through all pairs of nuisance for a given target for i in range(num_per_target): for j in range(i + 1, num_per_target): key_i = tuple(self._keys_for_targets[target][i]) key_j = tuple(self._keys_for_targets[target][j]) ## Generate W2 distance and gradient penalty. wass_2_dists = wasserstein_2_distance( self._features[key_i], self._features[key_j], mean_only=mean_only) / normalization wass_loss_target[target] += wass_2_dists return wass_loss_target def penalty_term(self): """Penalty term on the affine transformation. This can be used to ensure that the affine transformation remains close to the identity transformation. Returns: loss_value (tensorflow float): Value of the penalty term to add. """ loss_value = 0. identity = tf.eye(self._input_dim, dtype=tf.float32) for nuisance_key in self._unique_nuisances: w = self.w[nuisance_key] b = self.b[nuisance_key] loss_value += ( self._lambda_mean * sum_of_square(b) + self._lambda_cov * sum_of_square(w - identity) / self._input_dim) return loss_value / len(self.w) def train(self, save_dir, num_steps_pretrain, num_steps, disc_steps_per_training_step, learning_rate, tf_optimizer=tf.train.RMSPropOptimizer, save_checkpoints=True, save_to_pickle=True): """Trains the network, saving checkpoints along the way. Args: save_dir (str): Directory to save pickle file num_steps_pretrain (int): Total steps for pre-training num_steps (int): Total step for main training loop. disc_steps_per_training_step (int): Number of training steps for the discriminator per training step for the features. learning_rate (float): Learning rate for the algorithm. tf_optimizer (tf Optimizer): Which optimizer to use save_checkpoints (bool): Whether or not to use tensorflow checkpoints. save_to_pickle (bool): Whether or not to save to a pickle file. This may be convenient for some purposes. """ ## Generate paths and names for saving results. input_df_name = os.path.basename(FLAGS.input_df) params = ( ("input_df", input_df_name), ("network_type", FLAGS.network_type), ("num_steps_pretrain", num_steps_pretrain), ("num_steps", num_steps), ("batch_n", self._batch_n), ("learning_rate", learning_rate), ("feature_dim", self._feature_dim), ("disc_steps_per_training_step", disc_steps_per_training_step), ("target_levels", tuple(FLAGS.target_levels)), ("nuisance_levels", tuple(FLAGS.nuisance_levels)), ("layer_width", self._layer_width), ("num_layers", self._num_layers), ("lambda_mean", self._lambda_mean), ("lambda_cov", self._lambda_cov), ("cov_fix", FLAGS.cov_fix), ) folder_name = str(params) folder_path = os.path.join(save_dir, folder_name) ## Not writing to registry... # if FLAGS.reg_dir is None: # reg_path = os.path.join(save_dir, REGISTRY_NAME + ".pkl") # else: # reg_path = os.path.join(FLAGS.reg_dir, REGISTRY_NAME + ".pkl") pickle_path = os.path.join(folder_path, "data.pkl") checkpoint_path = os.path.join(folder_path, "checkpoints") for p in [save_dir, folder_path, checkpoint_path]: if not gfile.Exists(p): gfile.MkDir(p) ## Tensorflow items used for training global_step = tf.Variable(0, trainable=False, name="global_step") increment_global_step_op = tf.assign(global_step, global_step + 1) sorted_wass_values = [ self.wass_loss_target[k] for k in self.wass_loss_target ] wasserstein_loss = tf.reduce_mean(sorted_wass_values) if self.ignore_disc: loss = wasserstein_loss else: loss = wasserstein_loss + self.penalty_term() grad_pen = tf.reduce_mean(list(self.grad_pen_target.values())) input_vars = [ var for var in tf.trainable_variables() if INPUT_NAME in var.name ] critic_vars = [ var for var in tf.trainable_variables() if CRITIC_LAYER_NAME in var.name ] optimizer = tf_optimizer(learning_rate) input_trainer = optimizer.minimize( loss, global_step=global_step, var_list=input_vars) if not self.ignore_disc: critic_trainer = optimizer.minimize( loss, global_step=global_step, var_list=critic_vars) tf.summary.scalar("loss", loss) if not self.ignore_disc: tf.summary.scalar("grad_pen", grad_pen) ## TODO(tabakg): Figure out why summary_op is not working. ## There currently seems to be an issue using summay_op, so it's set to None ## TODO(tabakg): There is also an issue with Supervisor when trying to load ## existing checkpoint files. _ = tf.summary.merge_all() ## Should be summary_op sv = tf.train.Supervisor(logdir=checkpoint_path, summary_op=None) ## Used for saving history to pickle file loss_hist = [] grad_pen_hist = [] ## still initialize when not using critic ## random history, used to monitor random seeds random_nums = [] def do_loss_without_step(): """Get losses and update loss_hist and gran_pen_hist, no training step.""" feed_dict = {} for key, shuffler in self.holder.data_shufflers.items(): input_mini, _ = shuffler.next_batch(self._batch_n) feed_dict[self._x_inputs[key]] = input_mini random_nums.append(self.holder.get_random_state().uniform( 0, 1)) ## Testing random seed if self.ignore_disc: loss_val = sess.run([loss], feed_dict=feed_dict)[0] grad_pen_val = None else: loss_val, grad_pen_val = sess.run([loss, grad_pen], feed_dict=feed_dict) loss_hist.append(loss_val) grad_pen_hist.append(grad_pen_val) def do_train_step(trainer, increment_global_step_op, train=True): """A single training step. Side effects: Updates loss_hist, grad_pen_hist Args: trainer (Tf Operation): Specifies how to update variables in each step. increment_global_step_op (tf op): used to increment step. train (boolean): Whether or not to train. If train is false, only step and record loss values without actually training. Returns: step (int): Current timestep. """ feed_dict = {} for key, shuffler in self.holder.data_shufflers.items(): input_mini, _ = shuffler.next_batch(self._batch_n) feed_dict[self._x_inputs[key]] = input_mini if train: if self.ignore_disc: _, loss_val = sess.run([trainer, loss], feed_dict=feed_dict) grad_pen_val = None else: _, loss_val, grad_pen_val = sess.run([trainer, loss, grad_pen], feed_dict=feed_dict) step = tf.train.global_step(sess, global_step) ## get updated step. else: if self.ignore_disc: loss_val = sess.run([loss], feed_dict=feed_dict)[0] grad_pen_val = None else: loss_val, grad_pen_val = sess.run([loss, grad_pen], feed_dict=feed_dict) ## if trainer is not ran, increment global step anyway. step = sess.run(increment_global_step_op) loss_hist.append(loss_val) grad_pen_hist.append(grad_pen_val) if (step % FLAGS.checkpoint_interval == 0 and step >= FLAGS.num_steps_pretrain): if save_checkpoints: sv.saver.save(sess, checkpoint_path, global_step) if save_to_pickle: w_val, b_val = sess.run([self.w, self.b], feed_dict=feed_dict) contents = { step: { "loss_hist": loss_hist, "grad_pen_hist": grad_pen_hist, "w_val": w_val, "b_val": b_val, "random_nums": random_nums, }, "params": dict(params) } add_contents_to_pickle(pickle_path, contents) # add_name_to_registry(reg_path, pickle_path) return step ## Tested as a potential cause for indeterminism. ## This did not cause indeterminism on the desktop. # config = tf.ConfigProto() # config.inter_op_parallelism_threads = 1 # config.intra_op_parallelism_threads = 1 # with sv.managed_session(config=config) as sess: with sv.managed_session() as sess: step = tf.train.global_step(sess, global_step) ## Get initial losses without stepping do_loss_without_step() ## Pre training to adjust Wasserstein function while step < num_steps_pretrain: if self.ignore_disc: break step = do_train_step(critic_trainer, increment_global_step_op) ## Main training part main_step = step - num_steps_pretrain while main_step < num_steps * (disc_steps_per_training_step + 1): ## Adjust critic disc_steps_per_training_step times if disc_steps_per_training_step != 0: while (main_step + 1) % disc_steps_per_training_step > 0: if self.ignore_disc: break step = do_train_step(critic_trainer, increment_global_step_op) main_step = step - num_steps_pretrain ## Train features if estimated distance is positive if self.ignore_disc: pos_dist = True ## if ignoring discriminator, this is not an issue else: pos_dist = (-loss_hist[-1] > 0) step = do_train_step( input_trainer, increment_global_step_op, train=pos_dist) main_step = step - num_steps_pretrain sv.stop() ################################################################################ ##### Functions for Saving to Pickle. ################################################################################ def read_pickle_helper(file_path, default=set): """Helper function to read data from a pickle file. If the file exists, load it. Otherwise, initialize the default type. Args: file_path (str): Path to pickle file. default (iterable): Python object stored in the pickle file. Returns: contents (iterable): The loaded contents or an empty default type. """ if gfile.Exists(file_path): with gfile.GFile(file_path, mode="r") as f: contents = pickle.loads(f.read()) else: contents = default() return contents def write_pickle_helper(file_path, contents): """Helper function to write contents to a pickle file. Args: file_path (str): Path to pickle file. contents (iterable): Contents to save to pickle file_path. """ with gfile.GFile(file_path, mode="w") as f: f.write(pickle.dumps(contents)) def add_name_to_registry(reg_path, pickle_path): """Adds the file_path to the set stored in the pickle file reg_path. The registry file contains a dictionary whose keys are possible datasets. The values for each dataset key is another dictionary, mapping from a trasformation name to a list of file paths. Each of these paths corresponds to a saved transformation file that was generated using different parameters. Args: reg_path (str): Registry path. pickle_path (str): Path to registered pickle file. """ if FLAGS.network_type == WASSERSTEIN_NETWORK: transform_name = "wasserstein_transform" elif FLAGS.network_type == WASSERSTEIN_2_NETWORK: transform_name = "wasserstein_2_transform" elif FLAGS.network_type == WASSERSTEIN_SQRD_NETWORK: transform_name = "wasserstein_squared_transform" elif FLAGS.network_type == WASSERSTEIN_CUBED_NETWORK: transform_name = "wasserstein_cubed_transform" elif FLAGS.network_type == MEAN_ONLY_NETWORK: transform_name = "mean_only_transform" else: raise ValueError("Unknown network type, please add...") reg = read_pickle_helper(reg_path, dict) if FLAGS.input_df not in reg: reg[FLAGS.input_df] = {} if transform_name not in reg[FLAGS.input_df]: reg[FLAGS.input_df][transform_name] = [] if pickle_path not in reg[FLAGS.input_df][transform_name]: reg[FLAGS.input_df][transform_name].append(pickle_path) write_pickle_helper(reg_path, reg) def add_contents_to_pickle(file_path, contents): """Adds contents to a pickle file. Args: file_path (str): Full path to the pickle file. contents (dict): Maps a timestep to parameters at that time. """ old_contents = read_pickle_helper(file_path, dict) contents.update(old_contents) write_pickle_helper(file_path, contents) def main(argv): del argv # Unused. if FLAGS.network_type not in POSSIBLE_NETWORKS: raise ValueError("Unknown network type.") tf.reset_default_graph() with tf.Graph().as_default(): tf.set_random_seed(FLAGS.tf_seed) ## Load embedding dataframe df = io_utils.read_dataframe_from_hdf5(FLAGS.input_df) ## TODO(tabakg): Add training routine for this network as well. ## This network did not seem to work as well, so this is secondary priority. using_w = WASSERSTEIN_NETWORK in FLAGS.network_type using_w_sqrd = WASSERSTEIN_SQRD_NETWORK in FLAGS.network_type using_w_cubed = WASSERSTEIN_CUBED_NETWORK in FLAGS.network_type using_w_1 = using_w or using_w_sqrd or using_w_cubed using_w_2 = WASSERSTEIN_2_NETWORK in FLAGS.network_type using_mean_only = MEAN_ONLY_NETWORK in FLAGS.network_type ## Script for initializing WassersteinNetwork if using_w_1 or using_w_2 or using_mean_only: if using_w: logging.info("using WASSERSTEIN_NETWORK.") power = 1. elif using_w_sqrd: logging.info("using WASSERSTEIN_SQRD_NETWORK.") power = 2. elif using_w_cubed: logging.info("using WASSERSTEIN_CUBED_NETWORK.") power = 3. ## TODO(tabakg): Possible bug when input_category_level=None. holder = DatasetHolder( df, input_category_level=FLAGS.nuisance_levels, batch_input_info="one_hot", random_state=np.random.RandomState(seed=FLAGS.seed)) ## Old holder.add_shufflers(FLAGS.nuisance_levels + FLAGS.target_levels, None) # holder.add_shufflers(FLAGS.nuisance_levels, None) nuisance_levels = list(range(len(FLAGS.nuisance_levels))) target_levels = list( range( len(FLAGS.nuisance_levels), len(FLAGS.nuisance_levels) + len(FLAGS.target_levels))) if using_w_1: network = WassersteinNetwork( holder, FLAGS.feature_dim, FLAGS.batch_n, target_levels, nuisance_levels, layer_width=FLAGS.layer_width, num_layers=FLAGS.num_layers, lambda_mean=FLAGS.lambda_mean, lambda_cov=FLAGS.lambda_cov, power=power) else: # using_w_2 or using_mean_only if using_mean_only: logging.info("using MEAN_ONLY_NETWORK.") mean_only = True else: logging.info("using WASSERSTEIN_2_NETWORK.") mean_only = False network = WassersteinNetwork( holder, FLAGS.feature_dim, FLAGS.batch_n, target_levels, nuisance_levels, layer_width=FLAGS.layer_width, num_layers=FLAGS.num_layers, lambda_mean=FLAGS.lambda_mean, lambda_cov=FLAGS.lambda_cov, ignore_disc=True, mean_only=mean_only) network.train(FLAGS.save_dir, FLAGS.num_steps_pretrain, FLAGS.num_steps, FLAGS.disc_steps_per_training_step, FLAGS.learning_rate) if __name__ == "__main__": app.run(main)
google-research/google-research
correct_batch_effects_wdn/forgetting_nuisance.py
Python
apache-2.0
55,433
[ "Gaussian" ]
73e74593a568ec89269c256a0d4346799094b4d7cb9476b5fe732a56f9fe69cc
# SimpleCV Cameras & Devices #load system libraries from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet, ColorSpace from SimpleCV.Display import Display from SimpleCV.Color import Color from collections import deque import time import ctypes as ct import subprocess import cv2 import numpy as np import traceback import sys #Globals _cameras = [] _camera_polling_thread = "" _index = [] class FrameBufferThread(threading.Thread): """ **SUMMARY** This is a helper thread which continually debuffers the camera frames. If you don't do this, cameras may constantly give you a frame behind, which causes problems at low sample rates. This makes sure the frames returned by your camera are fresh. """ def run(self): global _cameras while (1): for cam in _cameras: if cam.pygame_camera: cam.pygame_buffer = cam.capture.get_image(cam.pygame_buffer) else: cv.GrabFrame(cam.capture) cam._threadcapturetime = time.time() time.sleep(0.04) #max 25 fps, if you're lucky class FrameSource: """ **SUMMARY** An abstract Camera-type class, for handling multiple types of video input. Any sources of images inheirit from it """ _calibMat = "" #Intrinsic calibration matrix _distCoeff = "" #Distortion matrix _threadcapturetime = '' #when the last picture was taken capturetime = '' #timestamp of the last aquired image def __init__(self): return def getProperty(self, p): return None def getAllProperties(self): return {} def getImage(self): return None def calibrate(self, imageList, grid_sz=0.03, dimensions=(8, 5)): """ **SUMMARY** Camera calibration will help remove distortion and fisheye effects It is agnostic of the imagery source, and can be used with any camera The easiest way to run calibration is to run the calibrate.py file under the tools directory for SimpleCV. This will walk you through the calibration process. **PARAMETERS** * *imageList* - is a list of images of color calibration images. * *grid_sz* - is the actual grid size of the calibration grid, the unit used will be the calibration unit value (i.e. if in doubt use meters, or U.S. standard) * *dimensions* - is the the count of the *interior* corners in the calibration grid. So for a grid where there are 4x4 black grid squares has seven interior corners. **RETURNS** The camera's intrinsic matrix. **EXAMPLE** See :py:module:calibrate.py """ # This routine was adapted from code originally written by: # Abid. K -- abidrahman2@gmail.com # See: https://github.com/abidrahmank/OpenCV-Python/blob/master/Other_Examples/camera_calibration.py warn_thresh = 1 n_boards = 0 #no of boards board_w = int(dimensions[0]) # number of horizontal corners board_h = int(dimensions[1]) # number of vertical corners n_boards = int(len(imageList)) board_n = board_w * board_h # no of total corners board_sz = (board_w, board_h) #size of board if( n_boards < warn_thresh ): logger.warning("FrameSource.calibrate: We suggest using 20 or more images to perform camera calibration!" ) # creation of memory storages image_points = cv.CreateMat(n_boards * board_n, 2, cv.CV_32FC1) object_points = cv.CreateMat(n_boards * board_n, 3, cv.CV_32FC1) point_counts = cv.CreateMat(n_boards, 1, cv.CV_32SC1) intrinsic_matrix = cv.CreateMat(3, 3, cv.CV_32FC1) distortion_coefficient = cv.CreateMat(5, 1, cv.CV_32FC1) # capture frames of specified properties and modification of matrix values i = 0 z = 0 # to print number of frames successes = 0 imgIdx = 0 # capturing required number of views while(successes < n_boards): found = 0 img = imageList[imgIdx] (found, corners) = cv.FindChessboardCorners(img.getGrayscaleMatrix(), board_sz, cv.CV_CALIB_CB_ADAPTIVE_THRESH | cv.CV_CALIB_CB_FILTER_QUADS) corners = cv.FindCornerSubPix(img.getGrayscaleMatrix(), corners,(11, 11),(-1, -1), (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 30, 0.1)) # if got a good image,draw chess board if found == 1: corner_count = len(corners) z = z + 1 # if got a good image, add to matrix if len(corners) == board_n: step = successes * board_n k = step for j in range(board_n): cv.Set2D(image_points, k, 0, corners[j][0]) cv.Set2D(image_points, k, 1, corners[j][1]) cv.Set2D(object_points, k, 0, grid_sz*(float(j)/float(board_w))) cv.Set2D(object_points, k, 1, grid_sz*(float(j)%float(board_w))) cv.Set2D(object_points, k, 2, 0.0) k = k + 1 cv.Set2D(point_counts, successes, 0, board_n) successes = successes + 1 # now assigning new matrices according to view_count if( successes < warn_thresh ): logger.warning("FrameSource.calibrate: You have %s good images for calibration we recommend at least %s" % (successes, warn_thresh)) object_points2 = cv.CreateMat(successes * board_n, 3, cv.CV_32FC1) image_points2 = cv.CreateMat(successes * board_n, 2, cv.CV_32FC1) point_counts2 = cv.CreateMat(successes, 1, cv.CV_32SC1) for i in range(successes * board_n): cv.Set2D(image_points2, i, 0, cv.Get2D(image_points, i, 0)) cv.Set2D(image_points2, i, 1, cv.Get2D(image_points, i, 1)) cv.Set2D(object_points2, i, 0, cv.Get2D(object_points, i, 0)) cv.Set2D(object_points2, i, 1, cv.Get2D(object_points, i, 1)) cv.Set2D(object_points2, i, 2, cv.Get2D(object_points, i, 2)) for i in range(successes): cv.Set2D(point_counts2, i, 0, cv.Get2D(point_counts, i, 0)) cv.Set2D(intrinsic_matrix, 0, 0, 1.0) cv.Set2D(intrinsic_matrix, 1, 1, 1.0) rcv = cv.CreateMat(n_boards, 3, cv.CV_64FC1) tcv = cv.CreateMat(n_boards, 3, cv.CV_64FC1) # camera calibration cv.CalibrateCamera2(object_points2, image_points2, point_counts2, (img.width, img.height), intrinsic_matrix,distortion_coefficient, rcv, tcv, 0) self._calibMat = intrinsic_matrix self._distCoeff = distortion_coefficient return intrinsic_matrix def getCameraMatrix(self): """ **SUMMARY** This function returns a cvMat of the camera's intrinsic matrix. If there is no matrix defined the function returns None. """ return self._calibMat def undistort(self, image_or_2darray): """ **SUMMARY** If given an image, apply the undistortion given by the camera's matrix and return the result. If given a 1xN 2D cvmat or a 2xN numpy array, it will un-distort points of measurement and return them in the original coordinate system. **PARAMETERS** * *image_or_2darray* - an image or an ndarray. **RETURNS** The undistorted image or the undistorted points. If the camera is un-calibrated we return None. **EXAMPLE** >>> img = cam.getImage() >>> result = cam.undistort(img) """ if(type(self._calibMat) != cv.cvmat or type(self._distCoeff) != cv.cvmat ): logger.warning("FrameSource.undistort: This operation requires calibration, please load the calibration matrix") return None if (type(image_or_2darray) == InstanceType and image_or_2darray.__class__ == Image): inImg = image_or_2darray # we have an image retVal = inImg.getEmpty() cv.Undistort2(inImg.getBitmap(), retVal, self._calibMat, self._distCoeff) return Image(retVal) else: mat = '' if (type(image_or_2darray) == cv.cvmat): mat = image_or_2darray else: arr = cv.fromarray(np.array(image_or_2darray)) mat = cv.CreateMat(cv.GetSize(arr)[1], 1, cv.CV_64FC2) cv.Merge(arr[:, 0], arr[:, 1], None, None, mat) upoints = cv.CreateMat(cv.GetSize(mat)[1], 1, cv.CV_64FC2) cv.UndistortPoints(mat, upoints, self._calibMat, self._distCoeff) #undistorted.x = (x* focalX + principalX); #undistorted.y = (y* focalY + principalY); return (np.array(upoints[:, 0]) *\ [self.getCameraMatrix()[0, 0], self.getCameraMatrix()[1, 1]] +\ [self.getCameraMatrix()[0, 2], self.getCameraMatrix()[1, 2]])[:, 0] def getImageUndistort(self): """ **SUMMARY** Using the overridden getImage method we retrieve the image and apply the undistortion operation. **RETURNS** The latest image from the camera after applying undistortion. **EXAMPLE** >>> cam = Camera() >>> cam.loadCalibration("mycam.xml") >>> while True: >>> img = cam.getImageUndistort() >>> img.show() """ return self.undistort(self.getImage()) def saveCalibration(self, filename): """ **SUMMARY** Save the calibration matrices to file. The file name should be without the extension. The default extension is .xml. **PARAMETERS** * *filename* - The file name, without an extension, to which to save the calibration data. **RETURNS** Returns true if the file was saved , false otherwise. **EXAMPLE** See :py:module:calibrate.py """ if( type(self._calibMat) != cv.cvmat ): logger.warning("FrameSource.saveCalibration: No calibration matrix present, can't save.") else: intrFName = filename + "Intrinsic.xml" cv.Save(intrFName, self._calibMat) if( type(self._distCoeff) != cv.cvmat ): logger.warning("FrameSource.saveCalibration: No calibration distortion present, can't save.") else: distFName = filename + "Distortion.xml" cv.Save(distFName, self._distCoeff) return None def loadCalibration(self, filename): """ **SUMMARY** Load a calibration matrix from file. The filename should be the stem of the calibration files names. e.g. If the calibration files are MyWebcamIntrinsic.xml and MyWebcamDistortion.xml then load the calibration file "MyWebcam" **PARAMETERS** * *filename* - The file name, without an extension, to which to save the calibration data. **RETURNS** Returns true if the file was loaded , false otherwise. **EXAMPLE** See :py:module:calibrate.py """ retVal = False intrFName = filename + "Intrinsic.xml" self._calibMat = cv.Load(intrFName) distFName = filename + "Distortion.xml" self._distCoeff = cv.Load(distFName) if( type(self._distCoeff) == cv.cvmat and type(self._calibMat) == cv.cvmat): retVal = True return retVal def live(self): """ **SUMMARY** This shows a live view of the camera. **EXAMPLE** To use it's as simple as: >>> cam = Camera() >>> cam.live() Left click will show mouse coordinates and color Right click will kill the live image """ start_time = time.time() from SimpleCV.Display import Display i = self.getImage() d = Display(i.size()) i.save(d) col = Color.RED while d.isNotDone(): i = self.getImage() elapsed_time = time.time() - start_time if d.mouseLeft: txt = "coord: (" + str(d.mouseX) + "," + str(d.mouseY) + ")" i.dl().text(txt, (10,i.height / 2), color=col) txt = "color: " + str(i.getPixel(d.mouseX,d.mouseY)) i.dl().text(txt, (10,(i.height / 2) + 10), color=col) print "coord: (" + str(d.mouseX) + "," + str(d.mouseY) + "), color: " + str(i.getPixel(d.mouseX,d.mouseY)) if elapsed_time > 0 and elapsed_time < 5: i.dl().text("In live mode", (10,10), color=col) i.dl().text("Left click will show mouse coordinates and color", (10,20), color=col) i.dl().text("Right click will kill the live image", (10,30), color=col) i.save(d) if d.mouseRight: print "Closing Window" d.done = True pg.quit() class Camera(FrameSource): """ **SUMMARY** The Camera class is the class for managing input from a basic camera. Note that once the camera is initialized, it will be locked from being used by other processes. You can check manually if you have compatible devices on linux by looking for /dev/video* devices. This class wrappers OpenCV's cvCapture class and associated methods. Read up on OpenCV's CaptureFromCAM method for more details if you need finer control than just basic frame retrieval """ capture = "" #cvCapture object thread = "" pygame_camera = False pygame_buffer = "" prop_map = {"width": cv.CV_CAP_PROP_FRAME_WIDTH, "height": cv.CV_CAP_PROP_FRAME_HEIGHT, "brightness": cv.CV_CAP_PROP_BRIGHTNESS, "contrast": cv.CV_CAP_PROP_CONTRAST, "saturation": cv.CV_CAP_PROP_SATURATION, "hue": cv.CV_CAP_PROP_HUE, "gain": cv.CV_CAP_PROP_GAIN, "exposure": cv.CV_CAP_PROP_EXPOSURE} #human readable to CV constant property mapping def __init__(self, camera_index = -1, prop_set = {}, threaded = True, calibrationfile = ''): global _cameras global _camera_polling_thread global _index """ **SUMMARY** In the camera constructor, camera_index indicates which camera to connect to and props is a dictionary which can be used to set any camera attributes Supported props are currently: height, width, brightness, contrast, saturation, hue, gain, and exposure. You can also specify whether you want the FrameBufferThread to continuously debuffer the camera. If you specify True, the camera is essentially 'on' at all times. If you specify off, you will have to manage camera buffers. **PARAMETERS** * *camera_index* - The index of the camera, these go from 0 upward, and are system specific. * *prop_set* - The property set for the camera (i.e. a dict of camera properties). .. Warning:: For most web cameras only the width and height properties are supported. Support for all of the other parameters varies by camera and operating system. * *threaded* - If True we constantly debuffer the camera, otherwise the user must do this manually. * *calibrationfile* - A calibration file to load. """ self.index = None self.threaded = False self.capture = None if platform.system() == "Linux" and -1 in _index and camera_index != -1 and camera_index not in _index: process = subprocess.Popen(["lsof /dev/video"+str(camera_index)],shell=True,stdout=subprocess.PIPE) data = process.communicate() if data[0]: camera_index = -1 elif platform.system() == "Linux" and camera_index == -1 and -1 not in _index: process = subprocess.Popen(["lsof /dev/video*"],shell=True,stdout=subprocess.PIPE) data = process.communicate() if data[0]: camera_index = int(data[0].split("\n")[1].split()[-1][-1]) for cam in _cameras: if camera_index == cam.index: self.threaded = cam.threaded self.capture = cam.capture self.index = cam.index _cameras.append(self) return #This is to add support for XIMEA cameras. if isinstance(camera_index, str): if camera_index.lower() == 'ximea': camera_index = 1100 _index.append(camera_index) self.capture = cv.CaptureFromCAM(camera_index) #This fixes bug with opencv not being able to grab frames from webcams on linux self.index = camera_index if "delay" in prop_set: time.sleep(prop_set['delay']) if platform.system() == "Linux" and (prop_set.has_key("height") or cv.GrabFrame(self.capture) == False): import pygame.camera pygame.camera.init() threaded = True #pygame must be threaded if camera_index == -1: camera_index = 0 self.index = camera_index _index.append(camera_index) print _index if(prop_set.has_key("height") and prop_set.has_key("width")): self.capture = pygame.camera.Camera("/dev/video" + str(camera_index), (prop_set['width'], prop_set['height'])) else: self.capture = pygame.camera.Camera("/dev/video" + str(camera_index)) try: self.capture.start() except Exception as exc: msg = "caught exception: %r" % exc logger.warning(msg) logger.warning("SimpleCV can't seem to find a camera on your system, or the drivers do not work with SimpleCV.") return time.sleep(0) self.pygame_buffer = self.capture.get_image() self.pygame_camera = True else: _index.append(camera_index) self.threaded = False if (platform.system() == "Windows"): threaded = False if (not self.capture): return None #set any properties in the constructor for p in prop_set.keys(): if p in self.prop_map: cv.SetCaptureProperty(self.capture, self.prop_map[p], prop_set[p]) if (threaded): self.threaded = True _cameras.append(self) if (not _camera_polling_thread): _camera_polling_thread = FrameBufferThread() _camera_polling_thread.daemon = True _camera_polling_thread.start() time.sleep(0) #yield to thread if calibrationfile: self.loadCalibration(calibrationfile) #todo -- make these dynamic attributes of the Camera class def getProperty(self, prop): """ **SUMMARY** Retrieve the value of a given property, wrapper for cv.GetCaptureProperty .. Warning:: For most web cameras only the width and height properties are supported. Support for all of the other parameters varies by camera and operating system. **PARAMETERS** * *prop* - The property to retrive. **RETURNS** The specified property. If it can't be found the method returns False. **EXAMPLE** >>> cam = Camera() >>> prop = cam.getProperty("width") """ if self.pygame_camera: if prop.lower() == 'width': return self.capture.get_size()[0] elif prop.lower() == 'height': return self.capture.get_size()[1] else: return False if prop in self.prop_map: return cv.GetCaptureProperty(self.capture, self.prop_map[prop]) return False def getAllProperties(self): """ **SUMMARY** Return all properties from the camera. **RETURNS** A dict of all the camera properties. """ if self.pygame_camera: return False props = {} for p in self.prop_map: props[p] = self.getProperty(p) return props def getImage(self): """ **SUMMARY** Retrieve an Image-object from the camera. If you experience problems with stale frames from the camera's hardware buffer, increase the flushcache number to dequeue multiple frames before retrieval We're working on how to solve this problem. **RETURNS** A SimpleCV Image from the camera. **EXAMPLES** >>> cam = Camera() >>> while True: >>> cam.getImage().show() """ if self.pygame_camera: return Image(self.pygame_buffer.copy()) if (not self.threaded): cv.GrabFrame(self.capture) self.capturetime = time.time() else: self.capturetime = self._threadcapturetime frame = cv.RetrieveFrame(self.capture) newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3) cv.Copy(frame, newimg) return Image(newimg, self) class VirtualCamera(FrameSource): """ **SUMMARY** The virtual camera lets you test algorithms or functions by providing a Camera object which is not a physically connected device. Currently, VirtualCamera supports "image", "imageset" and "video" source types. **USAGE** * For image, pass the filename or URL to the image * For the video, the filename * For imageset, you can pass either a path or a list of [path, extension] * For directory you treat a directory to show the latest file, an example would be where a security camera logs images to the directory, calling .getImage() will get the latest in the directory """ source = "" sourcetype = "" lastmtime = 0 def __init__(self, s, st, start=1): """ **SUMMARY** The constructor takes a source, and source type. **PARAMETERS** * *s* - the source of the imagery. * *st* - the type of the virtual camera. Valid strings include: * *start* - the number of the frame that you want to start with. * "image" - a single still image. * "video" - a video file. * "imageset" - a SimpleCV image set. * "directory" - a VirtualCamera for loading a directory **EXAMPLE** >>> vc = VirtualCamera("img.jpg", "image") >>> vc = VirtualCamera("video.mpg", "video") >>> vc = VirtualCamera("./path_to_images/", "imageset") >>> vc = VirtualCamera("video.mpg", "video", 300) >>> vc = VirtualCamera("./imgs", "directory") """ self.source = s self.sourcetype = st self.counter = 0 if start==0: start=1 self.start = start if self.sourcetype not in ["video", "image", "imageset", "directory"]: print 'Error: In VirtualCamera(), Incorrect Source option. "%s" \nUsage:' % self.sourcetype print '\tVirtualCamera("filename","video")' print '\tVirtualCamera("filename","image")' print '\tVirtualCamera("./path_to_images","imageset")' print '\tVirtualCamera("./path_to_images","directory")' return None else: if isinstance(self.source,str) and not os.path.exists(self.source): print 'Error: In VirtualCamera()\n\t"%s" was not found.' % self.source return None if (self.sourcetype == "imageset"): if( isinstance(s,ImageSet) ): self.source = s elif( isinstance(s,(list,str)) ): self.source = ImageSet() if (isinstance(s,list)): self.source.load(*s) else: self.source.load(s) else: warnings.warn('Virtual Camera is unable to figure out the contents of your ImageSet, it must be a directory, list of directories, or an ImageSet object') elif (self.sourcetype == 'video'): self.capture = cv.CaptureFromFile(self.source) cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, self.start-1) elif (self.sourcetype == 'directory'): pass def getImage(self): """ **SUMMARY** Retrieve an Image-object from the virtual camera. **RETURNS** A SimpleCV Image from the camera. **EXAMPLES** >>> cam = VirtualCamera() >>> while True: >>> cam.getImage().show() """ if (self.sourcetype == 'image'): self.counter = self.counter + 1 return Image(self.source, self) elif (self.sourcetype == 'imageset'): print len(self.source) img = self.source[self.counter % len(self.source)] self.counter = self.counter + 1 return img elif (self.sourcetype == 'video'): # cv.QueryFrame returns None if the video is finished frame = cv.QueryFrame(self.capture) if frame: img = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3) cv.Copy(frame, img) return Image(img, self) else: return None elif (self.sourcetype == 'directory'): img = self.findLastestImage(self.source, 'bmp') self.counter = self.counter + 1 return Image(img, self) def rewind(self, start=None): """ **SUMMARY** Rewind the Video source back to the given frame. Available for only video sources. **PARAMETERS** start - the number of the frame that you want to rewind to. if not provided, the video source would be rewound to the starting frame number you provided or rewound to the beginning. **RETURNS** None **EXAMPLES** >>> cam = VirtualCamera("filename.avi", "video", 120) >>> i=0 >>> while i<60: ... cam.getImage().show() ... i+=1 >>> cam.rewind() """ if (self.sourcetype == 'video'): if not start: cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, self.start-1) else: if start==0: start=1 cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, start-1) else: self.counter = 0 def getFrame(self, frame): """ **SUMMARY** Get the provided numbered frame from the video source. Available for only video sources. **PARAMETERS** frame - the number of the frame **RETURNS** Image **EXAMPLES** >>> cam = VirtualCamera("filename.avi", "video", 120) >>> cam.getFrame(400).show() """ if (self.sourcetype == 'video'): number_frame = int(cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES)) cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, frame-1) img = self.getImage() cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, number_frame) return img elif (self.sourcetype == 'imageset'): img = None if( frame < len(self.source)): img = self.source[frame] return img else: return None def skipFrames(self, n): """ **SUMMARY** Skip n number of frames. Available for only video sources. **PARAMETERS** n - number of frames to be skipped. **RETURNS** None **EXAMPLES** >>> cam = VirtualCamera("filename.avi", "video", 120) >>> i=0 >>> while i<60: ... cam.getImage().show() ... i+=1 >>> cam.skipFrames(100) >>> cam.getImage().show() """ if (self.sourcetype == 'video'): number_frame = int(cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES)) cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES, number_frame + n - 1) elif (self.sourcetype == 'imageset'): self.counter = (self.counter + n) % len(self.source) else: self.counter = self.counter + n def getFrameNumber(self): """ **SUMMARY** Get the current frame number of the video source. Available for only video sources. **RETURNS** * *int* - number of the frame **EXAMPLES** >>> cam = VirtualCamera("filename.avi", "video", 120) >>> i=0 >>> while i<60: ... cam.getImage().show() ... i+=1 >>> cam.skipFrames(100) >>> cam.getFrameNumber() """ if (self.sourcetype == 'video'): number_frame = int(cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_FRAMES)) return number_frame else: return self.counter def getCurrentPlayTime(self): """ **SUMMARY** Get the current play time in milliseconds of the video source. Available for only video sources. **RETURNS** * *int* - milliseconds of time from beginning of file. **EXAMPLES** >>> cam = VirtualCamera("filename.avi", "video", 120) >>> i=0 >>> while i<60: ... cam.getImage().show() ... i+=1 >>> cam.skipFrames(100) >>> cam.getCurrentPlayTime() """ if (self.sourcetype == 'video'): milliseconds = int(cv.GetCaptureProperty(self.capture, cv.CV_CAP_PROP_POS_MSEC)) return milliseconds else: raise ValueError('sources other than video do not have play time property') def findLastestImage(self, directory='.', extension='png'): """ **SUMMARY** This function finds the latest file in a directory with a given extension. **PARAMETERS** directory - The directory you want to load images from (defaults to current directory) extension - The image extension you want to use (defaults to .png) **RETURNS** The filename of the latest image **USAGE** >>> cam = VirtualCamera('imgs/', 'png') #find all .png files in 'img' directory >>> cam.getImage() # Grab the latest image from that directory """ max_mtime = 0 max_dir = None max_file = None max_full_path = None for dirname,subdirs,files in os.walk(directory): for fname in files: if fname.split('.')[-1] == extension: full_path = os.path.join(dirname, fname) mtime = os.stat(full_path).st_mtime if mtime > max_mtime: max_mtime = mtime max_dir = dirname max_file = fname self.lastmtime = mtime max_full_path = os.path.abspath(os.path.join(dirname, fname)) #if file is being written, block until mtime is at least 100ms old while time.mktime(time.localtime()) - os.stat(max_full_path).st_mtime < 0.1: time.sleep(0) return max_full_path class Kinect(FrameSource): """ **SUMMARY** This is an experimental wrapper for the Freenect python libraries you can getImage() and getDepth() for separate channel images """ def __init__(self, device_number=0): """ **SUMMARY** In the kinect contructor, device_number indicates which kinect to connect to. It defaults to 0. **PARAMETERS** * *device_number* - The index of the kinect, these go from 0 upward. """ self.deviceNumber = device_number if not FREENECT_ENABLED: logger.warning("You don't seem to have the freenect library installed. This will make it hard to use a Kinect.") #this code was borrowed from #https://github.com/amiller/libfreenect-goodies def getImage(self): """ **SUMMARY** This method returns the Kinect camera image. **RETURNS** The Kinect's color camera image. **EXAMPLE** >>> k = Kinect() >>> while True: >>> k.getImage().show() """ video = freenect.sync_get_video(self.deviceNumber)[0] self.capturetime = time.time() #video = video[:, :, ::-1] # RGB -> BGR return Image(video.transpose([1,0,2]), self) #low bits in this depth are stripped so it fits in an 8-bit image channel def getDepth(self): """ **SUMMARY** This method returns the Kinect depth image. **RETURNS** The Kinect's depth camera image as a grayscale image. **EXAMPLE** >>> k = Kinect() >>> while True: >>> d = k.getDepth() >>> img = k.getImage() >>> result = img.sideBySide(d) >>> result.show() """ depth = freenect.sync_get_depth(self.deviceNumber)[0] self.capturetime = time.time() np.clip(depth, 0, 2**10 - 1, depth) depth >>= 2 depth = depth.astype(np.uint8).transpose() return Image(depth, self) #we're going to also support a higher-resolution (11-bit) depth matrix #if you want to actually do computations with the depth def getDepthMatrix(self): self.capturetime = time.time() return freenect.sync_get_depth(self.deviceNumber)[0] class JpegStreamReader(threading.Thread): """ **SUMMARY** A Threaded class for pulling down JPEG streams and breaking up the images. This is handy for reading the stream of images from a IP CAmera. """ url = "" currentframe = "" _threadcapturetime = "" def run(self): f = '' if re.search('@', self.url): authstuff = re.findall('//(\S+)@', self.url)[0] self.url = re.sub("//\S+@", "//", self.url) user, password = authstuff.split(":") #thank you missing urllib2 manual #http://www.voidspace.org.uk/python/articles/urllib2.shtml#id5 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, self.url, user, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) f = opener.open(self.url) else: f = urllib2.urlopen(self.url) headers = f.info() if (headers.has_key("content-type")): headers['Content-type'] = headers['content-type'] #force ucase first char if not headers.has_key("Content-type"): logger.warning("Tried to load a JpegStream from " + self.url + ", but didn't find a content-type header!") return (multipart, boundary) = headers['Content-type'].split("boundary=") if not re.search("multipart", multipart, re.I): logger.warning("Tried to load a JpegStream from " + self.url + ", but the content type header was " + multipart + " not multipart/replace!") return buff = '' data = f.readline().strip() length = 0 contenttype = "jpeg" #the first frame contains a boundarystring and some header info while (1): #print data if (re.search(boundary, data.strip()) and len(buff)): #we have a full jpeg in buffer. Convert to an image if contenttype == "jpeg": self.currentframe = buff self._threadcapturetime = time.time() buff = '' if (re.match("Content-Type", data, re.I)): #set the content type, if provided (default to jpeg) (header, typestring) = data.split(":") (junk, contenttype) = typestring.strip().split("/") if (re.match("Content-Length", data, re.I)): #once we have the content length, we know how far to go jfif (header, length) = data.split(":") length = int(length.strip()) if (re.search("JFIF", data, re.I) or re.search("\xff\xd8\xff\xdb", data) or len(data) > 55): # we have reached the start of the image buff = '' if length and length > len(data): buff += data + f.read(length - len(data)) #read the remainder of the image if contenttype == "jpeg": self.currentframe = buff self._threadcapturetime = time.time() else: while (not re.search(boundary, data)): buff += data data = f.readline() endimg, junk = data.split(boundary) buff += endimg data = boundary continue data = f.readline() #load the next (header) line time.sleep(0) #let the other threads go class JpegStreamCamera(FrameSource): """ **SUMMARY** The JpegStreamCamera takes a URL of a JPEG stream and treats it like a camera. The current frame can always be accessed with getImage() Requires the Python Imaging Library: http://www.pythonware.com/library/pil/handbook/index.htm **EXAMPLE** Using your Android Phone as a Camera. Softwares like IP Webcam can be used. >>> cam = JpegStreamCamera("http://192.168.65.101:8080/videofeed") # your IP may be different. >>> img = cam.getImage() >>> img.show() """ url = "" camthread = "" def __init__(self, url): if not PIL_ENABLED: logger.warning("You need the Python Image Library (PIL) to use the JpegStreamCamera") return if not url.startswith('http://'): url = "http://" + url self.url = url self.camthread = JpegStreamReader() self.camthread.url = self.url self.camthread.daemon = True self.camthread.start() def getImage(self): """ **SUMMARY** Return the current frame of the JpegStream being monitored """ if not self.camthread._threadcapturetime: now = time.time() while not self.camthread._threadcapturetime: if time.time() - now > 5: warnings.warn("Timeout fetching JpegStream at " + self.url) return time.sleep(0.1) self.capturetime = self.camthread._threadcapturetime return Image(pil.open(StringIO(self.camthread.currentframe)), self) _SANE_INIT = False class Scanner(FrameSource): """ **SUMMARY** The Scanner lets you use any supported SANE-compatable scanner as a SimpleCV camera List of supported devices: http://www.sane-project.org/sane-supported-devices.html Requires the PySANE wrapper for libsane. The sane scanner object is available for direct manipulation at Scanner.device This scanner object is heavily modified from https://bitbucket.org/DavidVilla/pysane Constructor takes an index (default 0) and a list of SANE options (default is color mode). **EXAMPLE** >>> scan = Scanner(0, { "mode": "gray" }) >>> preview = scan.getPreview() >>> stuff = preview.findBlobs(minsize = 1000) >>> topleft = (np.min(stuff.x()), np.min(stuff.y())) >>> bottomright = (np.max(stuff.x()), np.max(stuff.y())) >>> scan.setROI(topleft, bottomright) >>> scan.setProperty("resolution", 1200) #set high resolution >>> scan.setProperty("mode", "color") >>> img = scan.getImage() >>> scan.setROI() #reset region of interest >>> img.show() """ usbid = None manufacturer = None model = None kind = None device = None max_x = None max_y = None def __init__(self, id = 0, properties = { "mode": "color"}): global _SANE_INIT import sane if not _SANE_INIT: try: sane.init() _SANE_INIT = True except: warn("Initializing pysane failed, do you have pysane installed?") return devices = sane.get_devices() if not len(devices): warn("Did not find a sane-compatable device") return self.usbid, self.manufacturer, self.model, self.kind = devices[id] self.device = sane.open(self.usbid) self.max_x = self.device.br_x self.max_y = self.device.br_y #save our extents for later for k, v in properties.items(): setattr(self.device, k, v) def getImage(self): """ **SUMMARY** Retrieve an Image-object from the scanner. Any ROI set with setROI() is taken into account. **RETURNS** A SimpleCV Image. Note that whatever the scanner mode is, SimpleCV will return a 3-channel, 8-bit image. **EXAMPLES** >>> scan = Scanner() >>> scan.getImage().show() """ return Image(self.device.scan()) def getPreview(self): """ **SUMMARY** Retrieve a preview-quality Image-object from the scanner. **RETURNS** A SimpleCV Image. Note that whatever the scanner mode is, SimpleCV will return a 3-channel, 8-bit image. **EXAMPLES** >>> scan = Scanner() >>> scan.getPreview().show() """ self.preview = True img = Image(self.device.scan()) self.preview = False return img def getAllProperties(self): """ **SUMMARY** Return a list of all properties and values from the scanner **RETURNS** Dictionary of active options and values. Inactive options appear as "None" **EXAMPLES** >>> scan = Scanner() >>> print scan.getAllProperties() """ props = {} for prop in self.device.optlist: val = None if hasattr(self.device, prop): val = getattr(self.device, prop) props[prop] = val return props def printProperties(self): """ **SUMMARY** Print detailed information about the SANE device properties **RETURNS** Nothing **EXAMPLES** >>> scan = Scanner() >>> scan.printProperties() """ for prop in self.device.optlist: try: print self.device[prop] except: pass def getProperty(self, prop): """ **SUMMARY** Returns a single property value from the SANE device equivalent to Scanner.device.PROPERTY **RETURNS** Value for option or None if missing/inactive **EXAMPLES** >>> scan = Scanner() >>> print scan.getProperty('mode') color """ if hasattr(self.device, prop): return getattr(self.device, prop) return None def setROI(self, topleft = (0,0), bottomright = (-1,-1)): """ **SUMMARY** Sets an ROI for the scanner in the current resolution. The two parameters, topleft and bottomright, will default to the device extents, so the ROI can be reset by calling setROI with no parameters. The ROI is set by SANE in resolution independent units (default MM) so resolution can be changed after ROI has been set. **RETURNS** None **EXAMPLES** >>> scan = Scanner() >>> scan.setROI((50, 50), (100,100)) >>> scan.getImage().show() # a very small crop on the scanner """ self.device.tl_x = self.px2mm(topleft[0]) self.device.tl_y = self.px2mm(topleft[1]) if bottomright[0] == -1: self.device.br_x = self.max_x else: self.device.br_x = self.px2mm(bottomright[0]) if bottomright[1] == -1: self.device.br_y = self.max_y else: self.device.br_y = self.px2mm(bottomright[1]) def setProperty(self, prop, val): """ **SUMMARY** Assigns a property value from the SANE device equivalent to Scanner.device.PROPERTY = VALUE **RETURNS** None **EXAMPLES** >>> scan = Scanner() >>> print scan.getProperty('mode') color >>> scan.setProperty("mode") = "gray" """ setattr(self.device, prop, val) def px2mm(self, pixels = 1): """ **SUMMARY** Helper function to convert native scanner resolution to millimeter units **RETURNS** Float value **EXAMPLES** >>> scan = Scanner() >>> scan.px2mm(scan.device.resolution) #return DPI in DPMM """ return float(pixels * 25.4 / float(self.device.resolution)) class DigitalCamera(FrameSource): """ **SUMMARY** The DigitalCamera takes a point-and-shoot camera or high-end slr and uses it as a Camera. The current frame can always be accessed with getPreview() Requires the PiggyPhoto Library: https://github.com/alexdu/piggyphoto **EXAMPLE** >>> cam = DigitalCamera() >>> pre = cam.getPreview() >>> pre.findBlobs().show() >>> >>> img = cam.getImage() >>> img.show() """ camera = None usbid = None device = None def __init__(self, id = 0): try: import piggyphoto except: warn("Initializing piggyphoto failed, do you have piggyphoto installed?") return devices = piggyphoto.cameraList(autodetect=True).toList() if not len(devices): warn("No compatible digital cameras attached") return self.device, self.usbid = devices[id] self.camera = piggyphoto.camera() def getImage(self): """ **SUMMARY** Retrieve an Image-object from the camera with the highest quality possible. **RETURNS** A SimpleCV Image. **EXAMPLES** >>> cam = DigitalCamera() >>> cam.getImage().show() """ fd, path = tempfile.mkstemp() self.camera.capture_image(path) img = Image(path) os.close(fd) os.remove(path) return img def getPreview(self): """ **SUMMARY** Retrieve an Image-object from the camera with the preview quality from the camera. **RETURNS** A SimpleCV Image. **EXAMPLES** >>> cam = DigitalCamera() >>> cam.getPreview().show() """ fd, path = tempfile.mkstemp() self.camera.capture_preview(path) img = Image(path) os.close(fd) os.remove(path) return img class ScreenCamera(): """ **SUMMARY** ScreenCapture is a camera class would allow you to capture all or part of the screen and return it as a color image. Requires the pyscreenshot Library: https://github.com/vijaym123/pyscreenshot **EXAMPLE** >>> sc = ScreenCamera() >>> res = sc.getResolution() >>> print res >>> >>> img = sc.getImage() >>> img.show() """ _roi = None def __init__(self): if not PYSCREENSHOT_ENABLED: warn("Initializing pyscreenshot failed. Install pyscreenshot from https://github.com/vijaym123/pyscreenshot") return None def getResolution(self): """ **DESCRIPTION** returns the resolution of the screenshot of the screen. **PARAMETERS** None **RETURNS** returns the resolution. **EXAMPLE** >>> img = ScreenCamera() >>> res = img.getResolution() >>> print res """ return Image(pyscreenshot.grab()).size() def setROI(self,roi): """ **DESCRIPTION** To set the region of interest. **PARAMETERS** * *roi* - tuple - It is a tuple of size 4. where region of interest is to the center of the screen. **RETURNS** None **EXAMPLE** >>> sc = ScreenCamera() >>> res = sc.getResolution() >>> sc.setROI(res[0]/4,res[1]/4,res[0]/2,res[1]/2) >>> img = sc.getImage() >>> s.show() """ if isinstance(roi,tuple) and len(roi)==4: self._roi = roi return def getImage(self): """ **DESCRIPTION** getImage function returns a Image object capturing the current screenshot of the screen. **PARAMETERS** None **RETURNS** Returns the region of interest if setROI is used. else returns the original capture of the screenshot. **EXAMPLE** >>> sc = ScreenCamera() >>> img = sc.getImage() >>> img.show() """ img = Image(pyscreenshot.grab()) try : if self._roi : img = img.crop(self._roi,centered=True) except : print "Error croping the image. ROI specified is not correct." return None return img class StereoImage: """ **SUMMARY** This class is for binaculor Stereopsis. That is exactrating 3D information from two differing views of a scene(Image). By comparing the two images, the relative depth information can be obtained. - Fundamental Matrix : F : a 3 x 3 numpy matrix, is a relationship between any two images of the same scene that constrains where the projection of points from the scene can occur in both images. see : http://en.wikipedia.org/wiki/Fundamental_matrix_(computer_vision) - Homography Matrix : H : a 3 x 3 numpy matrix, - ptsLeft : The matched points on the left image. - ptsRight : The matched points on the right image. -findDisparityMap and findDepthMap - provides 3D information. for more information on stereo vision, visit : http://en.wikipedia.org/wiki/Computer_stereo_vision **EXAMPLE** >>> img1 = Image('sampleimages/stereo_view1.png') >>> img2 = Image('sampleimages/stereo_view2.png') >>> stereoImg = StereoImage(img1,img2) >>> stereoImg.findDisparityMap(method="BM",nDisparity=20).show() """ def __init__( self, imgLeft , imgRight ): self.ImageLeft = imgLeft self.ImageRight = imgRight if self.ImageLeft.size() != self.ImageRight.size(): logger.warning('Left and Right images should have the same size.') return None else: self.size = self.ImageLeft.size() def findFundamentalMat(self, thresh=500.00, minDist=0.15 ): """ **SUMMARY** This method returns the fundamental matrix F such that (P_2).T F P_1 = 0 **PARAMETERS** * *thresh* - The feature quality metric. This can be any value between about 300 and 500. Higher values should return fewer, but higher quality features. * *minDist* - The value below which the feature correspondence is considered a match. This is the distance between two feature vectors. Good values are between 0.05 and 0.3 **RETURNS** Return None if it fails. * *F* - Fundamental matrix as ndarray. * *matched_pts1* - the matched points (x, y) in img1 * *matched_pts2* - the matched points (x, y) in img2 **EXAMPLE** >>> img1 = Image("sampleimages/stereo_view1.png") >>> img2 = Image("sampleimages/stereo_view2.png") >>> stereoImg = StereoImage(img1,img2) >>> F,pts1,pts2 = stereoImg.findFundamentalMat() **NOTE** If you deal with the fundamental matrix F directly, be aware of (P_2).T F P_1 = 0 where P_2 and P_1 consist of (y, x, 1) """ (kpts1, desc1) = self.ImageLeft._getRawKeypoints(thresh) (kpts2, desc2) = self.ImageRight._getRawKeypoints(thresh) if desc1 == None or desc2 == None: logger.warning("We didn't get any descriptors. Image might be too uniform or blurry.") return None num_pts1 = desc1.shape[0] num_pts2 = desc2.shape[0] magic_ratio = 1.00 if num_pts1 > num_pts2: magic_ratio = float(num_pts1) / float(num_pts2) (idx, dist) = Image()._getFLANNMatches(desc1, desc2) p = dist.squeeze() result = p * magic_ratio < minDist try: import cv2 except: logger.warning("Can't use fundamental matrix without OpenCV >= 2.3.0") return None pts1 = np.array([kpt.pt for kpt in kpts1]) pts2 = np.array([kpt.pt for kpt in kpts2]) matched_pts1 = pts1[idx[result]].squeeze() matched_pts2 = pts2[result] (F, mask) = cv2.findFundamentalMat(matched_pts1, matched_pts2, method=cv.CV_FM_LMEDS) inlier_ind = mask.nonzero()[0] matched_pts1 = matched_pts1[inlier_ind, :] matched_pts2 = matched_pts2[inlier_ind, :] matched_pts1 = matched_pts1[:, ::-1.00] matched_pts2 = matched_pts2[:, ::-1.00] return (F, matched_pts1, matched_pts2) def findHomography( self, thresh=500.00, minDist=0.15): """ **SUMMARY** This method returns the homography H such that P2 ~ H P1 **PARAMETERS** * *thresh* - The feature quality metric. This can be any value between about 300 and 500. Higher values should return fewer, but higher quality features. * *minDist* - The value below which the feature correspondence is considered a match. This is the distance between two feature vectors. Good values are between 0.05 and 0.3 **RETURNS** Return None if it fails. * *H* - homography as ndarray. * *matched_pts1* - the matched points (x, y) in img1 * *matched_pts2* - the matched points (x, y) in img2 **EXAMPLE** >>> img1 = Image("sampleimages/stereo_view1.png") >>> img2 = Image("sampleimages/stereo_view2.png") >>> stereoImg = StereoImage(img1,img2) >>> H,pts1,pts2 = stereoImg.findHomography() **NOTE** If you deal with the homography H directly, be aware of P2 ~ H P1 where P2 and P1 consist of (y, x, 1) """ (kpts1, desc1) = self.ImageLeft._getRawKeypoints(thresh) (kpts2, desc2) = self.ImageRight._getRawKeypoints(thresh) if desc1 == None or desc2 == None: logger.warning("We didn't get any descriptors. Image might be too uniform or blurry.") return None num_pts1 = desc1.shape[0] num_pts2 = desc2.shape[0] magic_ratio = 1.00 if num_pts1 > num_pts2: magic_ratio = float(num_pts1) / float(num_pts2) (idx, dist) = Image()._getFLANNMatches(desc1, desc2) p = dist.squeeze() result = p * magic_ratio < minDist try: import cv2 except: logger.warning("Can't use homography without OpenCV >= 2.3.0") return None pts1 = np.array([kpt.pt for kpt in kpts1]) pts2 = np.array([kpt.pt for kpt in kpts2]) matched_pts1 = pts1[idx[result]].squeeze() matched_pts2 = pts2[result] (H, mask) = cv2.findHomography(matched_pts1, matched_pts2, method=cv.CV_LMEDS) inlier_ind = mask.nonzero()[0] matched_pts1 = matched_pts1[inlier_ind, :] matched_pts2 = matched_pts2[inlier_ind, :] matched_pts1 = matched_pts1[:, ::-1.00] matched_pts2 = matched_pts2[:, ::-1.00] return (H, matched_pts1, matched_pts2) def findDisparityMap( self, nDisparity=16 ,method='BM'): """ The method generates disparity map from set of stereo images. **PARAMETERS** * *method* : *BM* - Block Matching algorithm, this is a real time algorithm. *SGBM* - Semi Global Block Matching algorithm, this is not a real time algorithm. *GC* - Graph Cut algorithm, This is not a real time algorithm. * *nDisparity* - Maximum disparity value. This should be multiple of 16 * *scale* - Scale factor **RETURNS** Return None if it fails. Returns Disparity Map Image **EXAMPLE** >>> img1 = Image("sampleimages/stereo_view1.png") >>> img2 = Image("sampleimages/stereo_view2.png") >>> stereoImg = StereoImage(img1,img2) >>> disp = stereoImg.findDisparityMap(method="BM") """ gray_left = self.ImageLeft.getGrayscaleMatrix() gray_right = self.ImageRight.getGrayscaleMatrix() (r, c) = self.size scale = int(self.ImageLeft.depth) if nDisparity % 16 !=0 : if nDisparity < 16 : nDisparity = 16 nDisparity = (nDisparity/16)*16 try : if method == 'BM': disparity = cv.CreateMat(c, r, cv.CV_32F) state = cv.CreateStereoBMState() state.SADWindowSize = 41 state.preFilterType = 1 state.preFilterSize = 41 state.preFilterCap = 31 state.minDisparity = -8 state.numberOfDisparities = nDisparity state.textureThreshold = 10 #state.speckleRange = 32 #state.speckleWindowSize = 100 state.uniquenessRatio=15 cv.FindStereoCorrespondenceBM(gray_left, gray_right, disparity, state) disparity_visual = cv.CreateMat(c, r, cv.CV_8U) cv.Normalize( disparity, disparity_visual, 0, 256, cv.CV_MINMAX ) disparity_visual = Image(disparity_visual) return Image(disparity_visual.getBitmap(),colorSpace=ColorSpace.GRAY) elif method == 'GC': disparity_left = cv.CreateMat(c, r, cv.CV_32F) disparity_right = cv.CreateMat(c, r, cv.CV_32F) state = cv.CreateStereoGCState(nDisparity, 8) state.minDisparity = -8 cv.FindStereoCorrespondenceGC( gray_left, gray_right, disparity_left, disparity_right, state, 0) disparity_left_visual = cv.CreateMat(c, r, cv.CV_8U) cv.Normalize( disparity_left, disparity_left_visual, 0, 256, cv.CV_MINMAX ) #cv.Scale(disparity_left, disparity_left_visual, -scale) disparity_left_visual = Image(disparity_left_visual) return Image(disparity_left_visual.getBitmap(),colorSpace=ColorSpace.GRAY) elif method == 'SGBM': try: import cv2 ver = cv2.__version__ if ver.startswith("$Rev :"): logger.warning("Can't use SGBM without OpenCV >= 2.4.0") return None except: logger.warning("Can't use SGBM without OpenCV >= 2.4.0") return None state = cv2.StereoSGBM() state.SADWindowSize = 41 state.preFilterCap = 31 state.minDisparity = 0 state.numberOfDisparities = nDisparity #state.speckleRange = 32 #state.speckleWindowSize = 100 state.disp12MaxDiff = 1 state.fullDP=False state.P1 = 8 * 1 * 41 * 41 state.P2 = 32 * 1 * 41 * 41 state.uniquenessRatio=15 disparity=state.compute(self.ImageLeft.getGrayNumpy(),self.ImageRight.getGrayNumpy()) return Image(disparity) else : logger.warning("Unknown method. Choose one method amoung BM or SGBM or GC !") return None except : logger.warning("Error in computing the Disparity Map, may be due to the Images are stereo in nature.") return None def Eline (self, point, F, whichImage): """ **SUMMARY** This method returns, line feature object. **PARAMETERS** * *point* - Input point (x, y) * *F* - Fundamental matrix. * *whichImage* - Index of the image (1 or 2) that contains the point **RETURNS** epipolar line, in the form of line feature object. **EXAMPLE** >>> img1 = Image("sampleimages/stereo_view1.png") >>> img2 = Image("sampleimages/stereo_view2.png") >>> stereoImg = StereoImage(img1,img2) >>> F,pts1,pts2 = stereoImg.findFundamentalMat() >>> point = pts2[0] >>> epiline = mapper.Eline(point,F, 1) #find corresponding Epipolar line in the left image. """ from SimpleCV.Features.Detection import Line pts1 = (0,0) pts2 = self.size pt_cvmat = cv.CreateMat(1, 1, cv.CV_32FC2) pt_cvmat[0, 0] = (point[1], point[0]) # OpenCV seems to use (y, x) coordinate. line = cv.CreateMat(1, 1, cv.CV_32FC3) cv.ComputeCorrespondEpilines(pt_cvmat, whichImage, npArray2cvMat(F), line) line_npArray = np.array(line).squeeze() line_npArray = line_npArray[[1.00, 0, 2]] pts1 = (pts1[0],(-line_npArray[2]-line_npArray[0]*pts1[0])/line_npArray[1] ) pts2 = (pts2[0],(-line_npArray[2]-line_npArray[0]*pts2[0])/line_npArray[1] ) if whichImage == 1 : return Line(self.ImageLeft, [pts1,pts2]) elif whichImage == 2 : return Line(self.ImageRight, [pts1,pts2]) def projectPoint( self, point, H ,whichImage): """ **SUMMARY** This method returns the corresponding point (x, y) **PARAMETERS** * *point* - Input point (x, y) * *whichImage* - Index of the image (1 or 2) that contains the point * *H* - Homography that can be estimated using StereoCamera.findHomography() **RETURNS** Corresponding point (x, y) as tuple **EXAMPLE** >>> img1 = Image("sampleimages/stereo_view1.png") >>> img2 = Image("sampleimages/stereo_view2.png") >>> stereoImg = StereoImage(img1,img2) >>> F,pts1,pts2 = stereoImg.findFundamentalMat() >>> point = pts2[0] >>> projectPoint = stereoImg.projectPoint(point,H ,1) #finds corresponding point in the left image. """ H = np.matrix(H) point = np.matrix((point[1], point[0],1.00)) if whichImage == 1.00: corres_pt = H * point.T else: corres_pt = np.linalg.inv(H) * point.T corres_pt = corres_pt / corres_pt[2] return (float(corres_pt[1]), float(corres_pt[0])) def get3DImage(self, Q, method="BM", state=None): """ **SUMMARY** This method returns the 3D depth image using reprojectImageTo3D method. **PARAMETERS** * *Q* - reprojection Matrix (disparity to depth matrix) * *method* - Stereo Correspondonce method to be used. - "BM" - Stereo BM - "SGBM" - Stereo SGBM * *state* - dictionary corresponding to parameters of stereo correspondonce. SADWindowSize - odd int nDisparity - int minDisparity - int preFilterCap - int preFilterType - int (only BM) speckleRange - int speckleWindowSize - int P1 - int (only SGBM) P2 - int (only SGBM) fullDP - Bool (only SGBM) uniquenessRatio - int textureThreshold - int (only BM) **RETURNS** SimpleCV.Image representing 3D depth Image also StereoImage.Image3D gives OpenCV 3D Depth Image of CV_32F type. **EXAMPLE** >>> lImage = Image("l.jpg") >>> rImage = Image("r.jpg") >>> stereo = StereoImage(lImage, rImage) >>> Q = cv.Load("Q.yml") >>> stereo.get3DImage(Q).show() >>> state = {"SADWindowSize":9, "nDisparity":112, "minDisparity":-39} >>> stereo.get3DImage(Q, "BM", state).show() >>> stereo.get3DImage(Q, "SGBM", state).show() """ imgLeft = self.ImageLeft imgRight = self.ImageRight cv2flag = True try: import cv2 except ImportError: cv2flag = False import cv2.cv as cv (r, c) = self.size if method == "BM": sbm = cv.CreateStereoBMState() disparity = cv.CreateMat(c, r, cv.CV_32F) if state: SADWindowSize = state.get("SADWindowSize") preFilterCap = state.get("preFilterCap") minDisparity = state.get("minDisparity") numberOfDisparities = state.get("nDisparity") uniquenessRatio = state.get("uniquenessRatio") speckleRange = state.get("speckleRange") speckleWindowSize = state.get("speckleWindowSize") textureThreshold = state.get("textureThreshold") speckleRange = state.get("speckleRange") speckleWindowSize = state.get("speckleWindowSize") preFilterType = state.get("perFilterType") if SADWindowSize is not None: sbm.SADWindowSize = SADWindowSize if preFilterCap is not None: sbm.preFilterCap = preFilterCap if minDisparity is not None: sbm.minDisparity = minDisparity if numberOfDisparities is not None: sbm.numberOfDisparities = numberOfDisparities if uniquenessRatio is not None: sbm.uniquenessRatio = uniquenessRatio if speckleRange is not None: sbm.speckleRange = speckleRange if speckleWindowSize is not None: sbm.speckleWindowSize = speckleWindowSize if textureThreshold is not None: sbm.textureThreshold = textureThreshold if preFilterType is not None: sbm.preFilterType = preFilterType else: sbm.SADWindowSize = 9 sbm.preFilterType = 1 sbm.preFilterSize = 5 sbm.preFilterCap = 61 sbm.minDisparity = -39 sbm.numberOfDisparities = 112 sbm.textureThreshold = 507 sbm.uniquenessRatio= 0 sbm.speckleRange = 8 sbm.speckleWindowSize = 0 gray_left = imgLeft.getGrayscaleMatrix() gray_right = imgRight.getGrayscaleMatrix() cv.FindStereoCorrespondenceBM(gray_left, gray_right, disparity, sbm) disparity_visual = cv.CreateMat(c, r, cv.CV_8U) elif method == "SGBM": if not cv2flag: warnings.warn("Can't Use SGBM without OpenCV >= 2.4. Use SBM instead.") sbm = cv2.StereoSGBM() if state: SADWindowSize = state.get("SADWindowSize") preFilterCap = state.get("preFilterCap") minDisparity = state.get("minDisparity") numberOfDisparities = state.get("nDisparity") P1 = state.get("P1") P2 = state.get("P2") uniquenessRatio = state.get("uniquenessRatio") speckleRange = state.get("speckleRange") speckleWindowSize = state.get("speckleWindowSize") fullDP = state.get("fullDP") if SADWindowSize is not None: sbm.SADWindowSize = SADWindowSize if preFilterCap is not None: sbm.preFilterCap = preFilterCap if minDisparity is not None: sbm.minDisparity = minDisparity if numberOfDisparities is not None: sbm.numberOfDisparities = numberOfDisparities if P1 is not None: sbm.P1 = P1 if P2 is not None: sbm.P2 = P2 if uniquenessRatio is not None: sbm.uniquenessRatio = uniquenessRatio if speckleRange is not None: sbm.speckleRange = speckleRange if speckleWindowSize is not None: sbm.speckleWindowSize = speckleWindowSize if fullDP is not None: sbm.fullDP = fullDP else: sbm.SADWindowSize = 9; sbm.numberOfDisparities = 96; sbm.preFilterCap = 63; sbm.minDisparity = -21; sbm.uniquenessRatio = 7; sbm.speckleWindowSize = 0; sbm.speckleRange = 8; sbm.disp12MaxDiff = 1; sbm.fullDP = False; disparity = sbm.compute(imgLeft.getGrayNumpyCv2(), imgRight.getGrayNumpyCv2()) else: warnings.warn("Unknown method. Returning None") return None if cv2flag: if not isinstance(Q, np.ndarray): Q = np.array(Q) if not isinstance(disparity, np.ndarray): disparity = np.array(disparity) Image3D = cv2.reprojectImageTo3D(disparity, Q, ddepth=cv2.cv.CV_32F) Image3D_normalize = cv2.normalize(Image3D, alpha=0, beta=255, norm_type=cv2.cv.CV_MINMAX, dtype=cv2.cv.CV_8UC3) retVal = Image(Image3D_normalize, cv2image=True) else: Image3D = cv.CreateMat(self.LeftImage.size()[1], self.LeftImage.size()[0], cv2.cv.CV_32FC3) Image3D_normalize = cv.CreateMat(self.LeftImage.size()[1], self.LeftImage.size()[0], cv2.cv.CV_8UC3) cv.ReprojectImageTo3D(disparity, Image3D, Q) cv.Normalize(Image3D, Image3D_normalize, 0, 255, cv.CV_MINMAX, CV_8UC3) retVal = Image(Image3D_normalize) self.Image3D = Image3D return retVal def get3DImageFromDisparity(self, disparity, Q): """ **SUMMARY** This method returns the 3D depth image using reprojectImageTo3D method. **PARAMETERS** * *disparity* - Disparity Image * *Q* - reprojection Matrix (disparity to depth matrix) **RETURNS** SimpleCV.Image representing 3D depth Image also StereoCamera.Image3D gives OpenCV 3D Depth Image of CV_32F type. **EXAMPLE** >>> lImage = Image("l.jpg") >>> rImage = Image("r.jpg") >>> stereo = StereoCamera() >>> Q = cv.Load("Q.yml") >>> disp = stereo.findDisparityMap() >>> stereo.get3DImageFromDisparity(disp, Q) """ cv2flag = True try: import cv2 except ImportError: cv2flag = False import cv2.cv as cv if cv2flag: if not isinstance(Q, np.ndarray): Q = np.array(Q) disparity = disparity.getNumpyCv2() Image3D = cv2.reprojectImageTo3D(disparity, Q, ddepth=cv2.cv.CV_32F) Image3D_normalize = cv2.normalize(Image3D, alpha=0, beta=255, norm_type=cv2.cv.CV_MINMAX, dtype=cv2.cv.CV_8UC3) retVal = Image(Image3D_normalize, cv2image=True) else: disparity = disparity.getMatrix() Image3D = cv.CreateMat(self.LeftImage.size()[1], self.LeftImage.size()[0], cv2.cv.CV_32FC3) Image3D_normalize = cv.CreateMat(self.LeftImage.size()[1], self.LeftImage.size()[0], cv2.cv.CV_8UC3) cv.ReprojectImageTo3D(disparity, Image3D, Q) cv.Normalize(Image3D, Image3D_normalize, 0, 255, cv.CV_MINMAX, CV_8UC3) retVal = Image(Image3D_normalize) self.Image3D = Image3D return retVal class StereoCamera : """ Stereo Camera is a class dedicated for calibration stereo camera. It also has functionalites for rectification and getting undistorted Images. This class can be used to calculate various parameters related to both the camera's : -> Camera Matrix -> Distortion coefficients -> Rotation and Translation matrix -> Rectification transform (rotation matrix) -> Projection matrix in the new (rectified) coordinate systems -> Disparity-to-depth mapping matrix (Q) """ def __init__(self): return def stereoCalibration(self,camLeft, camRight, nboards=30, chessboard=(8, 5), gridsize=0.027, WinSize = (352,288)): """ **SUMMARY** Stereo Calibration is a way in which you obtain the parameters that will allow you to calculate 3D information of the scene. Once both the camera's are initialized. Press [Space] once chessboard is identified in both the camera's. Press [esc] key to exit the calibration process. **PARAMETERS** * camLeft - Left camera index. * camRight - Right camera index. * nboards - Number of samples or multiple views of the chessboard in different positions and orientations with your stereo camera. * chessboard - A tuple of Cols, Rows in the chessboard (used for calibration). * gridsize - chessboard grid size in real units * WinSize - This is the window resolution. **RETURNS** A tuple of the form (CM1, CM2, D1, D2, R, T, E, F) on success CM1 - Camera Matrix for left camera, CM2 - Camera Matrix for right camera, D1 - Vector of distortion coefficients for left camera, D2 - Vector of distortion coefficients for right camera, R - Rotation matrix between the left and the right camera coordinate systems, T - Translation vector between the left and the right coordinate systems of the cameras, E - Essential matrix, F - Fundamental matrix **EXAMPLE** >>> StereoCam = StereoCamera() >>> calibration = StereoCam.StereoCalibration(1,2,nboards=40) **Note** Press space to capture the images. """ count = 0 n1="Left" n2="Right" try : captureLeft = cv.CaptureFromCAM(camLeft) cv.SetCaptureProperty(captureLeft, cv.CV_CAP_PROP_FRAME_WIDTH, WinSize[0]) cv.SetCaptureProperty(captureLeft, cv.CV_CAP_PROP_FRAME_HEIGHT, WinSize[1]) frameLeft = cv.QueryFrame(captureLeft) cv.FindChessboardCorners(frameLeft, (chessboard)) captureRight = cv.CaptureFromCAM(camRight) cv.SetCaptureProperty(captureRight, cv.CV_CAP_PROP_FRAME_WIDTH, WinSize[0]) cv.SetCaptureProperty(captureRight, cv.CV_CAP_PROP_FRAME_HEIGHT, WinSize[1]) frameRight = cv.QueryFrame(captureRight) cv.FindChessboardCorners(frameRight, (chessboard)) except : print "Error Initialising the Left and Right camera" return None imagePoints1 = cv.CreateMat(1, nboards * chessboard[0] * chessboard[1], cv.CV_64FC2) imagePoints2 = cv.CreateMat(1, nboards * chessboard[0] * chessboard[1], cv.CV_64FC2) objectPoints = cv.CreateMat(1, chessboard[0] * chessboard[1] * nboards, cv.CV_64FC3) nPoints = cv.CreateMat(1, nboards, cv.CV_32S) # the intrinsic camera matrices CM1 = cv.CreateMat(3, 3, cv.CV_64F) CM2 = cv.CreateMat(3, 3, cv.CV_64F) # the distortion coefficients of both cameras D1 = cv.CreateMat(1, 5, cv.CV_64F) D2 = cv.CreateMat(1, 5, cv.CV_64F) # matrices governing the rotation and translation from camera 1 to camera 2 R = cv.CreateMat(3, 3, cv.CV_64F) T = cv.CreateMat(3, 1, cv.CV_64F) # the essential and fundamental matrices E = cv.CreateMat(3, 3, cv.CV_64F) F = cv.CreateMat(3, 3, cv.CV_64F) while True: frameLeft = cv.QueryFrame(captureLeft) cv.Flip(frameLeft, frameLeft, 1) frameRight = cv.QueryFrame(captureRight) cv.Flip(frameRight, frameRight, 1) k = cv.WaitKey(3) cor1 = cv.FindChessboardCorners(frameLeft, (chessboard)) if cor1[0] : cv.DrawChessboardCorners(frameLeft, (chessboard), cor1[1], cor1[0]) cv.ShowImage(n1, frameLeft) cor2 = cv.FindChessboardCorners(frameRight, (chessboard)) if cor2[0]: cv.DrawChessboardCorners(frameRight, (chessboard), cor2[1], cor2[0]) cv.ShowImage(n2, frameRight) if cor1[0] and cor2[0] and k==0x20: print count for i in range(0, len(cor1[1])): cv.Set1D(imagePoints1, count * chessboard[0] * chessboard[1] + i, cv.Scalar(cor1[1][i][0], cor1[1][i][1])) cv.Set1D(imagePoints2, count * chessboard[0] * chessboard[1] + i, cv.Scalar(cor2[1][i][0], cor2[1][i][1])) count += 1 if count == nboards: cv.DestroyAllWindows() for i in range(nboards): for j in range(chessboard[1]): for k in range(chessboard[0]): cv.Set1D(objectPoints, i * chessboard[1] * chessboard[0] + j * chessboard[0] + k, (k * gridsize, j * gridsize, 0)) for i in range(nboards): cv.Set1D(nPoints, i, chessboard[0] * chessboard[1]) cv.SetIdentity(CM1) cv.SetIdentity(CM2) cv.Zero(D1) cv.Zero(D2) print "Running stereo calibration..." del(camLeft) del(camRight) cv.StereoCalibrate(objectPoints, imagePoints1, imagePoints2, nPoints, CM1, D1, CM2, D2, WinSize, R, T, E, F, flags=cv.CV_CALIB_SAME_FOCAL_LENGTH | cv.CV_CALIB_ZERO_TANGENT_DIST) print "Done." return (CM1, CM2, D1, D2, R, T, E, F) cv.ShowImage(n1, frameLeft) cv.ShowImage(n2, frameRight) if k == 0x1b: print "ESC pressed. Exiting. WARNING: NOT ENOUGH CHESSBOARDS FOUND YET" cv.DestroyAllWindows() break def saveCalibration(self,calibration=None, fname="Stereo",cdir="."): """ **SUMMARY** saveCalibration is a method to save the StereoCalibration parameters such as CM1, CM2, D1, D2, R, T, E, F of stereo pair. This method returns True on success and saves the calibration in the following format. StereoCM1.txt StereoCM2.txt StereoD1.txt StereoD2.txt StereoR.txt StereoT.txt StereoE.txt StereoF.txt **PARAMETERS** calibration - is a tuple os the form (CM1, CM2, D1, D2, R, T, E, F) CM1 -> Camera Matrix for left camera, CM2 -> Camera Matrix for right camera, D1 -> Vector of distortion coefficients for left camera, D2 -> Vector of distortion coefficients for right camera, R -> Rotation matrix between the left and the right camera coordinate systems, T -> Translation vector between the left and the right coordinate systems of the cameras, E -> Essential matrix, F -> Fundamental matrix **RETURNS** return True on success and saves the calibration files. **EXAMPLE** >>> StereoCam = StereoCamera() >>> calibration = StereoCam.StereoCalibration(1,2,nboards=40) >>> StereoCam.saveCalibration(calibration,fname="Stereo1") """ filenames = (fname+"CM1.txt", fname+"CM2.txt", fname+"D1.txt", fname+"D2.txt", fname+"R.txt", fname+"T.txt", fname+"E.txt", fname+"F.txt") try : (CM1, CM2, D1, D2, R, T, E, F) = calibration cv.Save("{0}/{1}".format(cdir, filenames[0]), CM1) cv.Save("{0}/{1}".format(cdir, filenames[1]), CM2) cv.Save("{0}/{1}".format(cdir, filenames[2]), D1) cv.Save("{0}/{1}".format(cdir, filenames[3]), D2) cv.Save("{0}/{1}".format(cdir, filenames[4]), R) cv.Save("{0}/{1}".format(cdir, filenames[5]), T) cv.Save("{0}/{1}".format(cdir, filenames[6]), E) cv.Save("{0}/{1}".format(cdir, filenames[7]), F) print "Calibration parameters written to directory '{0}'.".format(cdir) return True except : return False def loadCalibration(self,fname="Stereo",dir="."): """ **SUMMARY** loadCalibration is a method to load the StereoCalibration parameters such as CM1, CM2, D1, D2, R, T, E, F of stereo pair. This method loads from calibration files and return calibration on success else return false. **PARAMETERS** fname - is the prefix of the calibration files. dir - is the directory in which files are present. **RETURNS** a tuple of the form (CM1, CM2, D1, D2, R, T, E, F) on success. CM1 - Camera Matrix for left camera CM2 - Camera Matrix for right camera D1 - Vector of distortion coefficients for left camera D2 - Vector of distortion coefficients for right camera R - Rotation matrix between the left and the right camera coordinate systems T - Translation vector between the left and the right coordinate systems of the cameras E - Essential matrix F - Fundamental matrix else returns false **EXAMPLE** >>> StereoCam = StereoCamera() >>> loadedCalibration = StereoCam.loadCalibration(fname="Stereo1") """ filenames = (fname+"CM1.txt", fname+"CM2.txt", fname+"D1.txt", fname+"D2.txt", fname+"R.txt", fname+"T.txt", fname+"E.txt", fname+"F.txt") try : CM1 = cv.Load("{0}/{1}".format(dir, filenames[0])) CM2 = cv.Load("{0}/{1}".format(dir, filenames[1])) D1 = cv.Load("{0}/{1}".format(dir, filenames[2])) D2 = cv.Load("{0}/{1}".format(dir, filenames[3])) R = cv.Load("{0}/{1}".format(dir, filenames[4])) T = cv.Load("{0}/{1}".format(dir, filenames[5])) E = cv.Load("{0}/{1}".format(dir, filenames[6])) F = cv.Load("{0}/{1}".format(dir, filenames[7])) print "Calibration files loaded from dir '{0}'.".format(dir) return (CM1, CM2, D1, D2, R, T, E, F) except : return False def stereoRectify(self,calib=None,WinSize=(352,288)): """ **SUMMARY** Computes rectification transforms for each head of a calibrated stereo camera. **PARAMETERS** calibration - is a tuple os the form (CM1, CM2, D1, D2, R, T, E, F) CM1 - Camera Matrix for left camera, CM2 - Camera Matrix for right camera, D1 - Vector of distortion coefficients for left camera, D2 - Vector of distortion coefficients for right camera, R - Rotation matrix between the left and the right camera coordinate systems, T - Translation vector between the left and the right coordinate systems of the cameras, E - Essential matrix, F - Fundamental matrix **RETURNS** On success returns a a tuple of the format -> (R1, R2, P1, P2, Q, roi) R1 - Rectification transform (rotation matrix) for the left camera. R2 - Rectification transform (rotation matrix) for the right camera. P1 - Projection matrix in the new (rectified) coordinate systems for the left camera. P2 - Projection matrix in the new (rectified) coordinate systems for the right camera. Q - disparity-to-depth mapping matrix. **EXAMPLE** >>> StereoCam = StereoCamera() >>> calibration = StereoCam.loadCalibration(fname="Stereo1") >>> rectification = StereoCam.stereoRectify(calibration) """ (CM1, CM2, D1, D2, R, T, E, F) = calib R1 = cv.CreateMat(3, 3, cv.CV_64F) R2 = cv.CreateMat(3, 3, cv.CV_64F) P1 = cv.CreateMat(3, 4, cv.CV_64F) P2 = cv.CreateMat(3, 4, cv.CV_64F) Q = cv.CreateMat(4, 4, cv.CV_64F) print "Running stereo rectification..." (leftroi, rightroi) = cv.StereoRectify(CM1, CM2, D1, D2, WinSize, R, T, R1, R2, P1, P2, Q) roi = [] roi.append(max(leftroi[0], rightroi[0])) roi.append(max(leftroi[1], rightroi[1])) roi.append(min(leftroi[2], rightroi[2])) roi.append(min(leftroi[3], rightroi[3])) print "Done." return (R1, R2, P1, P2, Q, roi) def getImagesUndistort(self,imgLeft, imgRight, calibration, rectification, WinSize=(352,288)): """ **SUMMARY** Rectify two images from the calibration and rectification parameters. **PARAMETERS** * *imgLeft* - Image captured from left camera and needs to be rectified. * *imgRight* - Image captures from right camera and need to be rectified. * *calibration* - A calibration tuple of the format (CM1, CM2, D1, D2, R, T, E, F) * *rectification* - A rectification tuple of the format (R1, R2, P1, P2, Q, roi) **RETURNS** returns rectified images in a tuple -> (imgLeft,imgRight) >>> StereoCam = StereoCamera() >>> calibration = StereoCam.loadCalibration(fname="Stereo1") >>> rectification = StereoCam.stereoRectify(loadedCalibration) >>> imgLeft = camLeft.getImage() >>> imgRight = camRight.getImage() >>> rectLeft,rectRight = StereoCam.getImagesUndistort(imgLeft,imgRight,calibration,rectification) """ imgLeft = imgLeft.getMatrix() imgRight = imgRight.getMatrix() (CM1, CM2, D1, D2, R, T, E, F) = calibration (R1, R2, P1, P2, Q, roi) = rectification dst1 = cv.CloneMat(imgLeft) dst2 = cv.CloneMat(imgRight) map1x = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1) map2x = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1) map1y = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1) map2y = cv.CreateMat(WinSize[1], WinSize[0], cv.CV_32FC1) #print "Rectifying images..." cv.InitUndistortRectifyMap(CM1, D1, R1, P1, map1x, map1y) cv.InitUndistortRectifyMap(CM2, D2, R2, P2, map2x, map2y) cv.Remap(imgLeft, dst1, map1x, map1y) cv.Remap(imgRight, dst2, map2x, map2y) return Image(dst1), Image(dst2) def get3DImage(self, leftIndex, rightIndex, Q, method="BM", state=None): """ **SUMMARY** This method returns the 3D depth image using reprojectImageTo3D method. **PARAMETERS** * *leftIndex* - Index of left camera * *rightIndex* - Index of right camera * *Q* - reprojection Matrix (disparity to depth matrix) * *method* - Stereo Correspondonce method to be used. - "BM" - Stereo BM - "SGBM" - Stereo SGBM * *state* - dictionary corresponding to parameters of stereo correspondonce. SADWindowSize - odd int nDisparity - int minDisparity - int preFilterCap - int preFilterType - int (only BM) speckleRange - int speckleWindowSize - int P1 - int (only SGBM) P2 - int (only SGBM) fullDP - Bool (only SGBM) uniquenessRatio - int textureThreshold - int (only BM) **RETURNS** SimpleCV.Image representing 3D depth Image also StereoCamera.Image3D gives OpenCV 3D Depth Image of CV_32F type. **EXAMPLE** >>> lImage = Image("l.jpg") >>> rImage = Image("r.jpg") >>> stereo = StereoCamera() >>> Q = cv.Load("Q.yml") >>> stereo.get3DImage(1, 2, Q).show() >>> state = {"SADWindowSize":9, "nDisparity":112, "minDisparity":-39} >>> stereo.get3DImage(1, 2, Q, "BM", state).show() >>> stereo.get3DImage(1, 2, Q, "SGBM", state).show() """ cv2flag = True try: import cv2 except ImportError: cv2flag = False import cv2.cv as cv if cv2flag: camLeft = cv2.VideoCapture(leftIndex) camRight = cv2.VideoCapture(rightIndex) if camLeft.isOpened(): _, imgLeft = camLeft.read() else: warnings.warn("Unable to open left camera") return None if camRight.isOpened(): _, imgRight = camRight.read() else: warnings.warn("Unable to open right camera") return None imgLeft = Image(imgLeft, cv2image=True) imgRight = Image(imgRight, cv2image=True) else: camLeft = cv.CaptureFromCAM(leftIndex) camRight = cv.CaptureFromCAM(rightIndex) imgLeft = cv.QueryFrame(camLeft) if imgLeft is None: warnings.warn("Unable to open left camera") return None imgRight = cv.QueryFrame(camRight) if imgRight is None: warnings.warn("Unable to open right camera") return None imgLeft = Image(imgLeft, cv2image=True) imgRight = Image(imgRight, cv2image=True) del camLeft del camRight stereoImages = StereoImage(imgLeft, imgRight) Image3D_normalize = stereoImages.get3DImage(Q, method, state) self.Image3D = stereoImages.Image3D return Image3D_normalize class AVTCameraThread(threading.Thread): camera = None run = True verbose = False lock = None logger = None framerate = 0 def __init__(self, camera): super(AVTCameraThread, self).__init__() self._stop = threading.Event() self.camera = camera self.lock = threading.Lock() self.name = 'Thread-Camera-ID-' + str(self.camera.uniqueid) def run(self): counter = 0 timestamp = time.time() while self.run: self.lock.acquire() self.camera.runCommand("AcquisitionStart") frame = self.camera._getFrame(1000) if frame: img = Image(pil.fromstring(self.camera.imgformat, (self.camera.width, self.camera.height), frame.ImageBuffer[:int(frame.ImageBufferSize)])) self.camera._buffer.appendleft(img) self.camera.runCommand("AcquisitionStop") self.lock.release() counter += 1 time.sleep(0.01) if time.time() - timestamp >= 1: self.camera.framerate = counter counter = 0 timestamp = time.time() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() AVTCameraErrors = [ ("ePvErrSuccess", "No error"), ("ePvErrCameraFault", "Unexpected camera fault"), ("ePvErrInternalFault", "Unexpected fault in PvApi or driver"), ("ePvErrBadHandle", "Camera handle is invalid"), ("ePvErrBadParameter", "Bad parameter to API call"), ("ePvErrBadSequence", "Sequence of API calls is incorrect"), ("ePvErrNotFound", "Camera or attribute not found"), ("ePvErrAccessDenied", "Camera cannot be opened in the specified mode"), ("ePvErrUnplugged", "Camera was unplugged"), ("ePvErrInvalidSetup", "Setup is invalid (an attribute is invalid)"), ("ePvErrResources", "System/network resources or memory not available"), ("ePvErrBandwidth", "1394 bandwidth not available"), ("ePvErrQueueFull", "Too many frames on queue"), ("ePvErrBufferTooSmall", "Frame buffer is too small"), ("ePvErrCancelled", "Frame cancelled by user"), ("ePvErrDataLost", "The data for the frame was lost"), ("ePvErrDataMissing", "Some data in the frame is missing"), ("ePvErrTimeout", "Timeout during wait"), ("ePvErrOutOfRange", "Attribute value is out of the expected range"), ("ePvErrWrongType", "Attribute is not this type (wrong access function)"), ("ePvErrForbidden", "Attribute write forbidden at this time"), ("ePvErrUnavailable", "Attribute is not available at this time"), ("ePvErrFirewall", "A firewall is blocking the traffic (Windows only)"), ] def pverr(errcode): if errcode: raise Exception(": ".join(AVTCameraErrors[errcode])) class AVTCamera(FrameSource): """ **SUMMARY** AVTCamera is a ctypes wrapper for the Prosilica/Allied Vision cameras, such as the "manta" series. These require the PvAVT binary driver from Allied Vision: http://www.alliedvisiontec.com/us/products/1108.html Note that as of time of writing the new VIMBA driver is not available for Mac/Linux - so this uses the legacy PvAVT drive Props to Cixelyn, whos py-avt-pvapi module showed how to get much of this working https://bitbucket.org/Cixelyn/py-avt-pvapi All camera properties are directly from the PvAVT manual -- if not specified it will default to whatever the camera state is. Cameras can either by **EXAMPLE** >>> cam = AVTCamera(0, {"width": 656, "height": 492}) >>> >>> img = cam.getImage() >>> img.show() """ _buffer = None # Buffer to store images _buffersize = 10 # Number of images to keep in the rolling image buffer for threads _lastimage = None # Last image loaded into memory _thread = None _framerate = 0 threaded = False _pvinfo = { } _properties = { "AcqEndTriggerEvent": ("Enum", "R/W"), "AcqEndTriggerMode": ("Enum", "R/W"), "AcqRecTriggerEvent": ("Enum", "R/W"), "AcqRecTriggerMode": ("Enum", "R/W"), "AcqStartTriggerEvent": ("Enum", "R/W"), "AcqStartTriggerMode": ("Enum", "R/W"), "FrameRate": ("Float32", "R/W"), "FrameStartTriggerDelay": ("Uint32", "R/W"), "FrameStartTriggerEvent": ("Enum", "R/W"), "FrameStartTriggerMode": ("Enum", "R/W"), "FrameStartTriggerOverlap": ("Enum", "R/W"), "AcquisitionFrameCount": ("Uint32", "R/W"), "AcquisitionMode": ("Enum", "R/W"), "RecorderPreEventCount": ("Uint32", "R/W"), "ConfigFileIndex": ("Enum", "R/W"), "ConfigFilePowerup": ("Enum", "R/W"), "DSPSubregionBottom": ("Uint32", "R/W"), "DSPSubregionLeft": ("Uint32", "R/W"), "DSPSubregionRight": ("Uint32", "R/W"), "DSPSubregionTop": ("Uint32", "R/W"), "DefectMaskColumnEnable": ("Enum", "R/W"), "ExposureAutoAdjustTol": ("Uint32", "R/W"), "ExposureAutoAlg": ("Enum", "R/W"), "ExposureAutoMax": ("Uint32", "R/W"), "ExposureAutoMin": ("Uint32", "R/W"), "ExposureAutoOutliers": ("Uint32", "R/W"), "ExposureAutoRate": ("Uint32", "R/W"), "ExposureAutoTarget": ("Uint32", "R/W"), "ExposureMode": ("Enum", "R/W"), "ExposureValue": ("Uint32", "R/W"), "GainAutoAdjustTol": ("Uint32", "R/W"), "GainAutoMax": ("Uint32", "R/W"), "GainAutoMin": ("Uint32", "R/W"), "GainAutoOutliers": ("Uint32", "R/W"), "GainAutoRate": ("Uint32", "R/W"), "GainAutoTarget": ("Uint32", "R/W"), "GainMode": ("Enum", "R/W"), "GainValue": ("Uint32", "R/W"), "LensDriveCommand": ("Enum", "R/W"), "LensDriveDuration": ("Uint32", "R/W"), "LensVoltage": ("Uint32", "R/V"), "LensVoltageControl": ("Uint32", "R/W"), "IrisAutoTarget": ("Uint32", "R/W"), "IrisMode": ("Enum", "R/W"), "IrisVideoLevel": ("Uint32", "R/W"), "IrisVideoLevelMax": ("Uint32", "R/W"), "IrisVideoLevelMin": ("Uint32", "R/W"), "VsubValue": ("Uint32", "R/C"), "WhitebalAutoAdjustTol": ("Uint32", "R/W"), "WhitebalAutoRate": ("Uint32", "R/W"), "WhitebalMode": ("Enum", "R/W"), "WhitebalValueRed": ("Uint32", "R/W"), "WhitebalValueBlue": ("Uint32", "R/W"), "EventAcquisitionStart": ("Uint32", "R/C 40000"), "EventAcquisitionEnd": ("Uint32", "R/C 40001"), "EventFrameTrigger": ("Uint32", "R/C 40002"), "EventExposureEnd": ("Uint32", "R/C 40003"), "EventAcquisitionRecordTrigger": ("Uint32", "R/C 40004"), "EventSyncIn1Rise": ("Uint32", "R/C 40010"), "EventSyncIn1Fall": ("Uint32", "R/C 40011"), "EventSyncIn2Rise": ("Uint32", "R/C 40012"), "EventSyncIn2Fall": ("Uint32", "R/C 40013"), "EventSyncIn3Rise": ("Uint32", "R/C 40014"), "EventSyncIn3Fall": ("Uint32", "R/C 40015"), "EventSyncIn4Rise": ("Uint32", "R/C 40016"), "EventSyncIn4Fall": ("Uint32", "R/C 40017"), "EventOverflow": ("Uint32", "R/C 65534"), "EventError": ("Uint32", "R/C"), "EventNotification": ("Enum", "R/W"), "EventSelector": ("Enum", "R/W"), "EventsEnable1": ("Uint32", "R/W"), "BandwidthCtrlMode": ("Enum", "R/W"), "ChunkModeActive": ("Boolean", "R/W"), "NonImagePayloadSize": ("Unit32", "R/V"), "PayloadSize": ("Unit32", "R/V"), "StreamBytesPerSecond": ("Uint32", "R/W"), "StreamFrameRateConstrain": ("Boolean", "R/W"), "StreamHoldCapacity": ("Uint32", "R/V"), "StreamHoldEnable": ("Enum", "R/W"), "TimeStampFrequency": ("Uint32", "R/C"), "TimeStampValueHi": ("Uint32", "R/V"), "TimeStampValueLo": ("Uint32", "R/V"), "Height": ("Uint32", "R/W"), "RegionX": ("Uint32", "R/W"), "RegionY": ("Uint32", "R/W"), "Width": ("Uint32", "R/W"), "PixelFormat": ("Enum", "R/W"), "TotalBytesPerFrame": ("Uint32", "R/V"), "BinningX": ("Uint32", "R/W"), "BinningY": ("Uint32", "R/W"), "CameraName": ("String", "R/W"), "DeviceFirmwareVersion": ("String", "R/C"), "DeviceModelName": ("String", "R/W"), "DevicePartNumber": ("String", "R/C"), "DeviceSerialNumber": ("String", "R/C"), "DeviceVendorName": ("String", "R/C"), "FirmwareVerBuild": ("Uint32", "R/C"), "FirmwareVerMajor": ("Uint32", "R/C"), "FirmwareVerMinor": ("Uint32", "R/C"), "PartClass": ("Uint32", "R/C"), "PartNumber": ("Uint32", "R/C"), "PartRevision": ("String", "R/C"), "PartVersion": ("String", "R/C"), "SerialNumber": ("String", "R/C"), "SensorBits": ("Uint32", "R/C"), "SensorHeight": ("Uint32", "R/C"), "SensorType": ("Enum", "R/C"), "SensorWidth": ("Uint32", "R/C"), "UniqueID": ("Uint32", "R/C"), "Strobe1ControlledDuration": ("Enum", "R/W"), "Strobe1Delay": ("Uint32", "R/W"), "Strobe1Duration": ("Uint32", "R/W"), "Strobe1Mode": ("Enum", "R/W"), "SyncIn1GlitchFilter": ("Uint32", "R/W"), "SyncInLevels": ("Uint32", "R/V"), "SyncOut1Invert": ("Enum", "R/W"), "SyncOut1Mode": ("Enum", "R/W"), "SyncOutGpoLevels": ("Uint32", "R/W"), "DeviceEthAddress": ("String", "R/C"), "HostEthAddress": ("String", "R/C"), "DeviceIPAddress": ("String", "R/C"), "HostIPAddress": ("String", "R/C"), "GvcpRetries": ("Uint32", "R/W"), "GvspLookbackWindow": ("Uint32", "R/W"), "GvspResentPercent": ("Float32", "R/W"), "GvspRetries": ("Uint32", "R/W"), "GvspSocketBufferCount": ("Enum", "R/W"), "GvspTimeout": ("Uint32", "R/W"), "HeartbeatInterval": ("Uint32", "R/W"), "HeartbeatTimeout": ("Uint32", "R/W"), "MulticastEnable": ("Enum", "R/W"), "MulticastIPAddress": ("String", "R/W"), "PacketSize": ("Uint32", "R/W"), "StatDriverType": ("Enum", "R/V"), "StatFilterVersion": ("String", "R/C"), "StatFrameRate": ("Float32", "R/V"), "StatFramesCompleted": ("Uint32", "R/V"), "StatFramesDropped": ("Uint32", "R/V"), "StatPacketsErroneous": ("Uint32", "R/V"), "StatPacketsMissed": ("Uint32", "R/V"), "StatPacketsReceived": ("Uint32", "R/V"), "StatPacketsRequested": ("Uint32", "R/V"), "StatPacketResent": ("Uint32", "R/V") } class AVTCameraInfo(ct.Structure): """ AVTCameraInfo is an internal ctypes.Structure-derived class which contains metadata about cameras on the local network. Properties include: * UniqueId * CameraName * ModelName * PartNumber * SerialNumber * FirmwareVersion * PermittedAccess * InterfaceId * InterfaceType """ _fields_ = [ ("StructVer", ct.c_ulong), ("UniqueId", ct.c_ulong), ("CameraName", ct.c_char*32), ("ModelName", ct.c_char*32), ("PartNumber", ct.c_char*32), ("SerialNumber", ct.c_char*32), ("FirmwareVersion", ct.c_char*32), ("PermittedAccess", ct.c_long), ("InterfaceId", ct.c_ulong), ("InterfaceType", ct.c_int) ] def __repr__(self): return "<SimpleCV.Camera.AVTCameraInfo - UniqueId: %s>" % (self.UniqueId) class AVTFrame(ct.Structure): _fields_ = [ ("ImageBuffer", ct.POINTER(ct.c_char)), ("ImageBufferSize", ct.c_ulong), ("AncillaryBuffer", ct.c_int), ("AncillaryBufferSize", ct.c_int), ("Context", ct.c_int*4), ("_reserved1", ct.c_ulong*8), ("Status", ct.c_int), ("ImageSize", ct.c_ulong), ("AncillarySize", ct.c_ulong), ("Width", ct.c_ulong), ("Height", ct.c_ulong), ("RegionX", ct.c_ulong), ("RegionY", ct.c_ulong), ("Format", ct.c_int), ("BitDepth", ct.c_ulong), ("BayerPattern", ct.c_int), ("FrameCount", ct.c_ulong), ("TimestampLo", ct.c_ulong), ("TimestampHi", ct.c_ulong), ("_reserved2", ct.c_ulong*32) ] def __init__(self, buffersize): self.ImageBuffer = ct.create_string_buffer(buffersize) self.ImageBufferSize = ct.c_ulong(buffersize) self.AncillaryBuffer = 0 self.AncillaryBufferSize = 0 self.img = None self.hasImage = False self.frame = None def __del__(self): #This function should disconnect from the AVT Camera pverr(self.dll.PvCameraClose(self.handle)) def __init__(self, camera_id = -1, properties = {}, threaded = False): #~ super(AVTCamera, self).__init__() import platform if platform.system() == "Windows": self.dll = ct.windll.LoadLibrary("PvAPI.dll") elif platform.system() == "Darwin": self.dll = ct.CDLL("libPvAPI.dylib", ct.RTLD_GLOBAL) else: self.dll = ct.CDLL("libPvAPI.so") if not self._pvinfo.get("initialized", False): self.dll.PvInitialize() self._pvinfo['initialized'] = True #initialize. Note that we rely on listAllCameras being the next #call, since it blocks on cameras initializing camlist = self.listAllCameras() if not len(camlist): raise Exception("Couldn't find any cameras with the PvAVT driver. Use SampleViewer to confirm you have one connected.") if camera_id < 9000: #camera was passed as an index reference if camera_id == -1: #accept -1 for "first camera" camera_id = 0 camera_id = camlist[camera_id].UniqueId camera_id = long(camera_id) self.handle = ct.c_uint() init_count = 0 while self.dll.PvCameraOpen(camera_id,0,ct.byref(self.handle)) != 0: #wait until camera is availble if init_count > 4: # Try to connect 5 times before giving up raise Exception('Could not connect to camera, please verify with SampleViewer you can connect') init_count += 1 time.sleep(1) # sleep and retry to connect to camera in a second pverr(self.dll.PvCaptureStart(self.handle)) self.uniqueid = camera_id self.setProperty("AcquisitionMode","SingleFrame") self.setProperty("FrameStartTriggerMode","Freerun") if properties.get("mode", "RGB") == 'gray': self.setProperty("PixelFormat", "Mono8") else: self.setProperty("PixelFormat", "Rgb24") #give some compatablity with other cameras if properties.get("mode", ""): properties.pop("mode") if properties.get("height", ""): properties["Height"] = properties["height"] properties.pop("height") if properties.get("width", ""): properties["Width"] = properties["width"] properties.pop("width") for p in properties: self.setProperty(p, properties[p]) if threaded: self._thread = AVTCameraThread(self) self._thread.daemon = True self._buffer = deque(maxlen=self._buffersize) self._thread.start() self.threaded = True self.frame = None self._refreshFrameStats() def restart(self): """ This tries to restart the camera thread """ self._thread.stop() self._thread = AVTCameraThread(self) self._thread.daemon = True self._buffer = deque(maxlen=self._buffersize) self._thread.start() def listAllCameras(self): """ **SUMMARY** List all cameras attached to the host **RETURNS** List of AVTCameraInfo objects, otherwise empty list """ camlist = (self.AVTCameraInfo*100)() starttime = time.time() while int(camlist[0].UniqueId) == 0 and time.time() - starttime < 10: self.dll.PvCameraListEx(ct.byref(camlist), 100, None, ct.sizeof(self.AVTCameraInfo)) time.sleep(0.1) #keep checking for cameras until timeout return [cam for cam in camlist if cam.UniqueId != 0] def runCommand(self,command): """ **SUMMARY** Runs a PvAVT Command on the camera Valid Commands include: * FrameStartTriggerSoftware * AcquisitionAbort * AcquisitionStart * AcquisitionStop * ConfigFileLoad * ConfigFileSave * TimeStampReset * TimeStampValueLatch **RETURNS** 0 on success **EXAMPLE** >>>c = AVTCamera() >>>c.runCommand("TimeStampReset") """ return self.dll.PvCommandRun(self.handle,command) def getProperty(self, name): """ **SUMMARY** This retrieves the value of the AVT Camera attribute There are around 140 properties for the AVT Camera, so reference the AVT Camera and Driver Attributes pdf that is provided with the driver for detailed information Note that the error codes are currently ignored, so empty values may be returned. **EXAMPLE** >>>c = AVTCamera() >>>print c.getProperty("ExposureValue") """ valtype, perm = self._properties.get(name, (None, None)) if not valtype: return None val = '' err = 0 if valtype == "Enum": val = ct.create_string_buffer(100) vallen = ct.c_long() err = self.dll.PvAttrEnumGet(self.handle, name, val, 100, ct.byref(vallen)) val = str(val[:vallen.value]) elif valtype == "Uint32": val = ct.c_uint() err = self.dll.PvAttrUint32Get(self.handle, name, ct.byref(val)) val = int(val.value) elif valtype == "Float32": val = ct.c_float() err = self.dll.PvAttrFloat32Get(self.handle, name, ct.byref(val)) val = float(val.value) elif valtype == "String": val = ct.create_string_buffer(100) vallen = ct.c_long() err = self.dll.PvAttrStringGet(self.handle, name, val, 100, ct.byref(vallen)) val = str(val[:vallen.value]) elif valtype == "Boolean": val = ct.c_bool() err = self.dll.PvAttrBooleanGet(self.handle, name, ct.byref(val)) val = bool(val.value) #TODO, handle error codes return val #TODO, implement the PvAttrRange* functions #def getPropertyRange(self, name) def getAllProperties(self): """ **SUMMARY** This returns a dict with the name and current value of the documented PvAVT attributes CAVEAT: it addresses each of the properties individually, so this may take time to run if there's network latency **EXAMPLE** >>>c = AVTCamera(0) >>>props = c.getAllProperties() >>>print props['ExposureValue'] """ props = {} for p in self._properties.keys(): props[p] = self.getProperty(p) return props def setProperty(self, name, value, skip_buffer_size_check=False): """ **SUMMARY** This sets the value of the AVT Camera attribute. There are around 140 properties for the AVT Camera, so reference the AVT Camera and Driver Attributes pdf that is provided with the driver for detailed information By default, we will also refresh the height/width and bytes per frame we're expecting -- you can manually bypass this if you want speed Returns the raw PvAVT error code (0 = success) **Example** >>>c = AVTCamera() >>>c.setProperty("ExposureValue", 30000) >>>c.getImage().show() """ valtype, perm = self._properties.get(name, (None, None)) if not valtype: return None if valtype == "Uint32": err = self.dll.PvAttrUint32Set(self.handle, name, ct.c_uint(int(value))) elif valtype == "Float32": err = self.dll.PvAttrFloat32Set(self.handle, name, ct.c_float(float(value))) elif valtype == "Enum": err = self.dll.PvAttrEnumSet(self.handle, name, str(value)) elif valtype == "String": err = self.dll.PvAttrStringSet(self.handle, name, str(value)) elif valtype == "Boolean": err = self.dll.PvAttrBooleanSet(self.handle, name, ct.c_bool(bool(value))) #just to be safe, re-cache the camera metadata if not skip_buffer_size_check: self._refreshFrameStats() return err def getImage(self, timeout = 5000): """ **SUMMARY** Extract an Image from the Camera, returning the value. No matter what the image characteristics on the camera, the Image returned will be RGB 8 bit depth, if camera is in greyscale mode it will be 3 identical channels. **EXAMPLE** >>>c = AVTCamera() >>>c.getImage().show() """ if self.frame != None: st = time.time() try: pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(self.frame), timeout) ) except Exception, e: print "Exception waiting for frame:", e print "Time taken:",time.time() - st self.frame = None raise(e) img = self.unbuffer() self.frame = None return img elif self.threaded: self._thread.lock.acquire() try: img = self._buffer.pop() self._lastimage = img except IndexError: img = self._lastimage self._thread.lock.release() else: self.runCommand("AcquisitionStart") frame = self._getFrame(timeout) img = Image(pil.fromstring(self.imgformat, (self.width, self.height), frame.ImageBuffer[:int(frame.ImageBufferSize)])) self.runCommand("AcquisitionStop") return img def setupASyncMode(self): self.setProperty('AcquisitionMode','SingleFrame') self.setProperty('FrameStartTriggerMode','Software') def setupSyncMode(self): self.setProperty('AcquisitionMode','Continuous') self.setProperty('FrameStartTriggerMode','FreeRun') def unbuffer(self): img = Image(pil.fromstring(self.imgformat, (self.width, self.height), self.frame.ImageBuffer[:int(self.frame.ImageBufferSize)])) return img def _refreshFrameStats(self): self.width = self.getProperty("Width") self.height = self.getProperty("Height") self.buffersize = self.getProperty("TotalBytesPerFrame") self.pixelformat = self.getProperty("PixelFormat") self.imgformat = 'RGB' if self.pixelformat == 'Mono8': self.imgformat = 'L' def _getFrame(self, timeout = 5000): #return the AVTFrame object from the camera, timeout in ms #need to multiply by bitdepth try: frame = self.AVTFrame(self.buffersize) pverr( self.dll.PvCaptureQueueFrame(self.handle, ct.byref(frame), None) ) st = time.time() try: pverr( self.dll.PvCaptureWaitForFrameDone(self.handle, ct.byref(frame), timeout) ) except Exception, e: print "Exception waiting for frame:", e print "Time taken:",time.time() - st raise(e) except Exception, e: print "Exception aquiring frame:", e raise(e) return frame def acquire(self): self.frame = self.AVTFrame(self.buffersize) try: self.runCommand("AcquisitionStart") pverr( self.dll.PvCaptureQueueFrame(self.handle, ct.byref(self.frame), None) ) self.runCommand("AcquisitionStop") except Exception, e: print "Exception aquiring frame:", e raise(e) class GigECamera(Camera): """ GigE Camera driver via Aravis """ def __init__(self, camera_id = None, properties = {}, threaded = False): try: from gi.repository import Aravis except: print "GigE is supported by the Aravis library, download and build from https://github.com/sightmachine/aravis" print "Note that you need to set GI_TYPELIB_PATH=$GI_TYPELIB_PATH:(PATH_TO_ARAVIS)/src for the GObject Introspection" sys.exit() self._cam = Aravis.Camera.new (None) self._pixel_mode = "RGB" if properties.get("mode", False): self._pixel_mode = properties.pop("mode") if self._pixel_mode == "gray": self._cam.set_pixel_format (Aravis.PIXEL_FORMAT_MONO_8) else: self._cam.set_pixel_format (Aravis.PIXEL_FORMAT_BAYER_BG_8) #we'll use bayer (basler cams) #TODO, deal with other pixel formats if properties.get("roi", False): roi = properties['roi'] self._cam.set_region(*roi) #TODO, check sensor size if properties.get("width", False): #TODO, set internal function to scale results of getimage pass if properties.get("framerate", False): self._cam.set_frame_rate(properties['framerate']) self._stream = self._cam.create_stream (None, None) payload = self._cam.get_payload() self._stream.push_buffer(Aravis.Buffer.new_allocate (payload)) [x,y,width,height] = self._cam.get_region () self._height, self._width = height, width def getImage(self): camera = self._cam camera.start_acquisition() buff = self._stream.pop_buffer() self.capturetime = buff.timestamp_ns / 1000000.0 img = np.fromstring(ct.string_at(buff.data_address(), buff.size), dtype = np.uint8).reshape(self._height, self._width) rgb = cv2.cvtColor(img, cv2.COLOR_BAYER_BG2BGR) self._stream.push_buffer(buff) camera.stop_acquisition() #TODO, we should handle software triggering (separate capture and get image events) return Image(rgb) def getPropertyList(self): l = [ 'available_pixel_formats', 'available_pixel_formats_as_display_names', 'available_pixel_formats_as_strings', 'binning', 'device_id', 'exposure_time', 'exposure_time_bounds', 'frame_rate', 'frame_rate_bounds', 'gain', 'gain_bounds', 'height_bounds', 'model_name', 'payload', 'pixel_format', 'pixel_format_as_string', 'region', 'sensor_size', 'trigger_source', 'vendor_name', 'width_bounds' ] return l def getProperty(self, name = None): ''' This function get's the properties availble to the camera Usage: > camera.getProperty('region') > (0, 0, 128, 128) Available Properties: see function camera.getPropertyList() ''' if name == None: print "You need to provide a property, available properties are:" print "" for p in self.getPropertyList(): print p return stringval = "get_{}".format(name) try: return getattr(self._cam, stringval)() except: print 'Property {} does not appear to exist'.format(name) return None def setProperty(self, name = None, *args): ''' This function sets the property available to the camera Usage: > camera.setProperty('region',(256,256)) Available Properties: see function camera.getPropertyList() ''' if name == None: print "You need to provide a property, available properties are:" print "" for p in self.getPropertyList(): print p return if len(args) <= 0: print "You must provide a value to set" return stringval = "set_{}".format(name) try: return getattr(self._cam, stringval)(*args) except: print 'Property {} does not appear to exist or value is not in correct format'.format(name) return None def getAllProperties(self): ''' This function just prints out all the properties available to the camera ''' for p in self.getPropertyList(): print "{}: {}".format(p,self.getProperty(p)) class VimbaCameraThread(threading.Thread): camera = None run = True verbose = False lock = None logger = None framerate = 0 def __init__(self, camera): super(VimbaCameraThread, self).__init__() self._stop = threading.Event() self.camera = camera self.lock = threading.Lock() self.name = 'Thread-Camera-ID-' + str(self.camera.uniqueid) def run(self): counter = 0 timestamp = time.time() while self.run: self.lock.acquire() img = self.camera._captureFrame(1000) self.camera._buffer.appendleft(img) self.lock.release() counter += 1 time.sleep(0.01) if time.time() - timestamp >= 1: self.camera.framerate = counter counter = 0 timestamp = time.time() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() class VimbaCamera(FrameSource): """ **SUMMARY** VimbaCamera is a wrapper for the Allied Vision cameras, such as the "manta" series. This requires the 1) Vimba SDK provided from Allied Vision http://www.alliedvisiontec.com/us/products/software/vimba-sdk.html 2) Pyvimba Python library TODO: <INSERT URL> Note that as of time of writing, the VIMBA driver is not available for Mac. All camera properties are directly from the Vimba SDK manual -- if not specified it will default to whatever the camera state is. Cameras can either by **EXAMPLE** >>> cam = VimbaCamera(0, {"width": 656, "height": 492}) >>> >>> img = cam.getImage() >>> img.show() """ def _setupVimba(self): from pymba import Vimba self._vimba = Vimba() self._vimba.startup() system = self._vimba.getSystem() if system.GeVTLIsPresent: system.runFeatureCommand("GeVDiscoveryAllOnce") time.sleep(0.2) def __del__(self): #This function should disconnect from the Vimba Camera if self._camera is not None: if self.threaded: self._thread.stop() time.sleep(0.2) if self._frame is not None: self._frame.revokeFrame() self._frame = None self._camera.closeCamera() self._vimba.shutdown() def shutdown(self): """You must call this function if you are using threaded=true when you are finished to prevent segmentation fault""" # REQUIRED TO PREVENT SEGMENTATION FAULT FOR THREADED=True if (self._camera): self._camera.closeCamera() self._vimba.shutdown() def __init__(self, camera_id = -1, properties = {}, threaded = False): if not VIMBA_ENABLED: raise Exception("You don't seem to have the pymba library installed. This will make it hard to use a AVT Vimba Camera.") self._vimba = None self._setupVimba() camlist = self.listAllCameras() self._camTable = {} self._frame = None self._buffer = None # Buffer to store images self._buffersize = 10 # Number of images to keep in the rolling image buffer for threads self._lastimage = None # Last image loaded into memory self._thread = None self._framerate = 0 self.threaded = False self._properties = {} self._camera = None i = 0 for cam in camlist: self._camTable[i] = {'id': cam.cameraIdString} i += 1 if not len(camlist): raise Exception("Couldn't find any cameras with the Vimba driver. Use VimbaViewer to confirm you have one connected.") if camera_id < 9000: #camera was passed as an index reference if camera_id == -1: #accept -1 for "first camera" camera_id = 0 if (camera_id > len(camlist)): raise Exception("Couldn't find camera at index %d." % camera_id) cam_guid = camlist[camera_id].cameraIdString else: raise Exception("Index %d is too large" % camera_id) self._camera = self._vimba.getCamera(cam_guid) self._camera.openCamera() self.uniqueid = cam_guid self.setProperty("AcquisitionMode","SingleFrame") self.setProperty("TriggerSource","Freerun") # TODO: FIX if properties.get("mode", "RGB") == 'gray': self.setProperty("PixelFormat", "Mono8") else: fmt = "RGB8Packed" # alternatively use BayerRG8 self.setProperty("PixelFormat", "BayerRG8") #give some compatablity with other cameras if properties.get("mode", ""): properties.pop("mode") if properties.get("height", ""): properties["Height"] = properties["height"] properties.pop("height") if properties.get("width", ""): properties["Width"] = properties["width"] properties.pop("width") for p in properties: self.setProperty(p, properties[p]) if threaded: self._thread = VimbaCameraThread(self) self._thread.daemon = True self._buffer = deque(maxlen=self._buffersize) self._thread.start() self.threaded = True self._refreshFrameStats() def restart(self): """ This tries to restart the camera thread """ self._thread.stop() self._thread = VimbaCameraThread(self) self._thread.daemon = True self._buffer = deque(maxlen=self._buffersize) self._thread.start() def listAllCameras(self): """ **SUMMARY** List all cameras attached to the host **RETURNS** List of VimbaCamera objects, otherwise empty list VimbaCamera objects are defined in the pymba module """ cameraIds = self._vimba.getCameraIds() ar = [] for cameraId in cameraIds: ar.append(self._vimba.getCamera(cameraId)) return ar def runCommand(self,command): """ **SUMMARY** Runs a Vimba Command on the camera Valid Commands include: * AcquisitionAbort * AcquisitionStart * AcquisitionStop **RETURNS** 0 on success **EXAMPLE** >>>c = VimbaCamera() >>>c.runCommand("TimeStampReset") """ return self._camera.runFeatureCommand(command) def getProperty(self, name): """ **SUMMARY** This retrieves the value of the Vimba Camera attribute There are around 140 properties for the Vimba Camera, so reference the Vimba Camera pdf that is provided with the SDK for detailed information Throws VimbaException if property is not found or not implemented yet. **EXAMPLE** >>>c = VimbaCamera() >>>print c.getProperty("ExposureMode") """ return self._camera.__getattr__(name) #TODO, implement the PvAttrRange* functions #def getPropertyRange(self, name) def getAllProperties(self): """ **SUMMARY** This returns a dict with the name and current value of the documented Vimba attributes CAVEAT: it addresses each of the properties individually, so this may take time to run if there's network latency **EXAMPLE** >>>c = VimbaCamera(0) >>>props = c.getAllProperties() >>>print props['ExposureMode'] """ from pymba import VimbaException # TODO ar = {} c = self._camera cameraFeatureNames = c.getFeatureNames() for name in cameraFeatureNames: try: ar[name] = c.__getattr__(name) except VimbaException: # Ignore features not yet implemented pass return ar def setProperty(self, name, value, skip_buffer_size_check=False): """ **SUMMARY** This sets the value of the Vimba Camera attribute. There are around 140 properties for the Vimba Camera, so reference the Vimba Camera pdf that is provided with the SDK for detailed information Throws VimbaException if property not found or not yet implemented **Example** >>>c = VimbaCamera() >>>c.setProperty("ExposureAutoRate", 200) >>>c.getImage().show() """ ret = self._camera.__setattr__(name, value) #just to be safe, re-cache the camera metadata if not skip_buffer_size_check: self._refreshFrameStats() return ret def getImage(self): """ **SUMMARY** Extract an Image from the Camera, returning the value. No matter what the image characteristics on the camera, the Image returned will be RGB 8 bit depth, if camera is in greyscale mode it will be 3 identical channels. **EXAMPLE** >>>c = VimbaCamera() >>>c.getImage().show() """ if self.threaded: self._thread.lock.acquire() try: img = self._buffer.pop() self._lastimage = img except IndexError: img = self._lastimage self._thread.lock.release() else: img = self._captureFrame() return img def setupASyncMode(self): self.setProperty('AcquisitionMode','SingleFrame') self.setProperty('TriggerSource','Software') def setupSyncMode(self): self.setProperty('AcquisitionMode','SingleFrame') self.setProperty('TriggerSource','Freerun') def _refreshFrameStats(self): self.width = self.getProperty("Width") self.height = self.getProperty("Height") self.pixelformat = self.getProperty("PixelFormat") self.imgformat = 'RGB' if self.pixelformat == 'Mono8': self.imgformat = 'L' def _getFrame(self): if not self._frame: self._frame = self._camera.getFrame() # creates a frame self._frame.announceFrame() return self._frame def _captureFrame(self, timeout = 5000): try: c = self._camera f = self._getFrame() colorSpace = ColorSpace.BGR if self.pixelformat == 'Mono8': colorSpace = ColorSpace.GRAY c.startCapture() f.queueFrameCapture() c.runFeatureCommand('AcquisitionStart') c.runFeatureCommand('AcquisitionStop') try: f.waitFrameCapture(timeout) except Exception, e: print "Exception waiting for frame: %s: %s" % (e, traceback.format_exc()) raise(e) imgData = f.getBufferByteData() moreUsefulImgData = np.ndarray(buffer = imgData, dtype = np.uint8, shape = (f.height, f.width, 1)) rgb = cv2.cvtColor(moreUsefulImgData, cv2.COLOR_BAYER_RG2RGB) c.endCapture() return Image(rgb, colorSpace=colorSpace, cv2image=imgData) except Exception, e: print "Exception acquiring frame: %s: %s" % (e, traceback.format_exc()) raise(e)
hurdlea/SimpleCV
SimpleCV/Camera.py
Python
bsd-3-clause
132,113
[ "VisIt" ]
4d44393c74a46b8c60d39fac0c1dcef248b587525d3ad69730357b5495a415b4
import sys sys.path.insert(1, "../../../") import h2o def weights_and_distributions(ip,port): htable = h2o.upload_file(h2o.locate("smalldata/gbm_test/moppe.csv")) htable["premiekl"] = htable["premiekl"].asfactor() htable["moptva"] = htable["moptva"].asfactor() htable["zon"] = htable["zon"] # gamma dl = h2o.deeplearning(x=htable[0:3],y=htable["medskad"],training_frame=htable,distribution="gamma",weights_column="antskad") predictions = dl.predict(htable) # gaussian dl = h2o.deeplearning(x=htable[0:3],y=htable["medskad"],training_frame=htable,distribution="gaussian",weights_column="antskad") predictions = dl.predict(htable) # poisson dl = h2o.deeplearning(x=htable[0:3],y=htable["medskad"],training_frame=htable,distribution="poisson",weights_column="antskad") predictions = dl.predict(htable) # tweedie dl = h2o.deeplearning(x=htable[0:3],y=htable["medskad"],training_frame=htable,distribution="tweedie",weights_column="antskad") predictions = dl.predict(htable) if __name__ == "__main__": h2o.run_test(sys.argv, weights_and_distributions)
weaver-viii/h2o-3
h2o-py/tests/testdir_algos/deeplearning/pyunit_weights_and_distributionsDeeplearning.py
Python
apache-2.0
1,122
[ "Gaussian" ]
5247a3d85bdd84884d9aae9cf05e3416b80acb8616979746c1bb4f74cd7638ed
# pycparser: c_lexer.py # # CLexer class: lexer for the C language # # Copyright (C) 2008-2011, Eli Bendersky # License: BSD #----------------------------------------------------------------- import re import sys from .ply import lex from .ply.lex import TOKEN class CLexer(object): """ A lexer for the C language. After building it, set the input text with input(), and call token() to get new tokens. The public attribute filename can be set to an initial filaneme, but the lexer will update it upon #line directives. """ def __init__(self, error_func, type_lookup_func): """ Create a new Lexer. error_func: An error function. Will be called with an error message, line and column as arguments, in case of an error during lexing. type_lookup_func: A type lookup function. Given a string, it must return True IFF this string is a name of a type that was defined with a typedef earlier. """ self.error_func = error_func self.type_lookup_func = type_lookup_func self.filename = '' # Allow either "# line" or "# <num>" to support GCC's # cpp output # self.line_pattern = re.compile('([ \t]*line\W)|([ \t]*\d+)') self.pragma_pattern = re.compile('[ \t]*pragma\W') def build(self, **kwargs): """ Builds the lexer from the specification. Must be called after the lexer object is created. This method exists separately, because the PLY manual warns against calling lex.lex inside __init__ """ self.lexer = lex.lex(object=self, **kwargs) def reset_lineno(self): """ Resets the internal line number counter of the lexer. """ self.lexer.lineno = 1 def input(self, text): self.lexer.input(text) def token(self): g = self.lexer.token() return g def find_tok_column(self, token): """ Find the column of the token in its line. """ last_cr = self.lexer.lexdata.rfind('\n', 0, token.lexpos) return token.lexpos - last_cr ######################-- PRIVATE --###################### ## ## Internal auxiliary methods ## def _error(self, msg, token): location = self._make_tok_location(token) self.error_func(msg, location[0], location[1]) self.lexer.skip(1) def _make_tok_location(self, token): return (token.lineno, self.find_tok_column(token)) ## ## Reserved keywords ## keywords = ( '_BOOL', '_COMPLEX', 'AUTO', 'BREAK', 'CASE', 'CHAR', 'CONST', 'CONTINUE', 'DEFAULT', 'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EXTERN', 'FLOAT', 'FOR', 'GOTO', 'IF', 'INLINE', 'INT', 'LONG', 'REGISTER', 'RESTRICT', 'RETURN', 'SHORT', 'SIGNED', 'SIZEOF', 'STATIC', 'STRUCT', 'SWITCH', 'TYPEDEF', 'UNION', 'UNSIGNED', 'VOID', 'VOLATILE', 'WHILE', ) keyword_map = {} for keyword in keywords: if keyword == '_BOOL': keyword_map['_Bool'] = keyword elif keyword == '_COMPLEX': keyword_map['_Complex'] = keyword else: keyword_map[keyword.lower()] = keyword ## ## All the tokens recognized by the lexer ## tokens = keywords + ( # Identifiers 'ID', # Type identifiers (identifiers previously defined as # types with typedef) 'TYPEID', # constants 'INT_CONST_DEC', 'INT_CONST_OCT', 'INT_CONST_HEX', 'FLOAT_CONST', 'HEX_FLOAT_CONST', 'CHAR_CONST', 'WCHAR_CONST', # String literals 'STRING_LITERAL', 'WSTRING_LITERAL', # Operators 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD', 'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT', 'LOR', 'LAND', 'LNOT', 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE', # Assignment 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL', 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL', # Increment/decrement 'PLUSPLUS', 'MINUSMINUS', # Structure dereference (->) 'ARROW', # Conditional operator (?) 'CONDOP', # Delimeters 'LPAREN', 'RPAREN', # ( ) 'LBRACKET', 'RBRACKET', # [ ] 'LBRACE', 'RBRACE', # { } 'COMMA', 'PERIOD', # . , 'SEMI', 'COLON', # ; : # Ellipsis (...) 'ELLIPSIS', # pre-processor 'PPHASH', # '#' ) ## ## Regexes for use in tokens ## ## # valid C identifiers (K&R2: A.2.3) identifier = r'[a-zA-Z_][0-9a-zA-Z_]*' hex_prefix = '0[xX]' hex_digits = '[0-9a-fA-F]+' # integer constants (K&R2: A.2.5.1) integer_suffix_opt = r'(u?ll|U?LL|([uU][lL])|([lL][uU])|[uU]|[lL])?' decimal_constant = '(0'+integer_suffix_opt+')|([1-9][0-9]*'+integer_suffix_opt+')' octal_constant = '0[0-7]*'+integer_suffix_opt hex_constant = hex_prefix+hex_digits+integer_suffix_opt bad_octal_constant = '0[0-7]*[89]' # character constants (K&R2: A.2.5.2) # Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line # directives with Windows paths as filenames (..\..\dir\file) # For the same reason, decimal_escape allows all digit sequences. We want to # parse all correct code, even if it means to sometimes parse incorrect # code. # simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])""" decimal_escape = r"""(\d+)""" hex_escape = r"""(x[0-9a-fA-F]+)""" bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])""" escape_sequence = r"""(\\("""+simple_escape+'|'+decimal_escape+'|'+hex_escape+'))' cconst_char = r"""([^'\\\n]|"""+escape_sequence+')' char_const = "'"+cconst_char+"'" wchar_const = 'L'+char_const unmatched_quote = "('"+cconst_char+"*\\n)|('"+cconst_char+"*$)" bad_char_const = r"""('"""+cconst_char+"""[^'\n]+')|('')|('"""+bad_escape+r"""[^'\n]*')""" # string literals (K&R2: A.2.6) string_char = r"""([^"\\\n]|"""+escape_sequence+')' string_literal = '"'+string_char+'*"' wstring_literal = 'L'+string_literal bad_string_literal = '"'+string_char+'*'+bad_escape+string_char+'*"' # floating constants (K&R2: A.2.5.3) exponent_part = r"""([eE][-+]?[0-9]+)""" fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)""" floating_constant = '(((('+fractional_constant+')'+exponent_part+'?)|([0-9]+'+exponent_part+'))[FfLl]?)' binary_exponent_part = r'''([pP][+-]?[0-9]+)''' hex_fractional_constant = '((('+hex_digits+r""")?\."""+hex_digits+')|('+hex_digits+r"""\.))""" hex_floating_constant = '('+hex_prefix+'('+hex_digits+'|'+hex_fractional_constant+')'+binary_exponent_part+'[FfLl]?)' ## ## Lexer states: used for preprocessor \n-terminated directives ## states = ( # ppline: preprocessor line directives # ('ppline', 'exclusive'), # pppragma: pragma # ('pppragma', 'exclusive'), ) def t_PPHASH(self, t): r'[ \t]*\#' if self.line_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos): t.lexer.begin('ppline') self.pp_line = self.pp_filename = None elif self.pragma_pattern.match(t.lexer.lexdata, pos=t.lexer.lexpos): t.lexer.begin('pppragma') else: t.type = 'PPHASH' return t ## ## Rules for the ppline state ## @TOKEN(string_literal) def t_ppline_FILENAME(self, t): if self.pp_line is None: self._error('filename before line number in #line', t) else: self.pp_filename = t.value.lstrip('"').rstrip('"') @TOKEN(decimal_constant) def t_ppline_LINE_NUMBER(self, t): if self.pp_line is None: self.pp_line = t.value else: # Ignore: GCC's cpp sometimes inserts a numeric flag # after the file name pass def t_ppline_NEWLINE(self, t): r'\n' if self.pp_line is None: self._error('line number missing in #line', t) else: self.lexer.lineno = int(self.pp_line) if self.pp_filename is not None: self.filename = self.pp_filename t.lexer.begin('INITIAL') def t_ppline_PPLINE(self, t): r'line' pass t_ppline_ignore = ' \t' def t_ppline_error(self, t): self._error('invalid #line directive', t) ## ## Rules for the pppragma state ## def t_pppragma_NEWLINE(self, t): r'\n' t.lexer.lineno += 1 t.lexer.begin('INITIAL') def t_pppragma_PPPRAGMA(self, t): r'pragma' pass t_pppragma_ignore = ' \t<>.-{}();+-*/$%@&^~!?:,0123456789' @TOKEN(string_literal) def t_pppragma_STR(self, t): pass @TOKEN(identifier) def t_pppragma_ID(self, t): pass def t_pppragma_error(self, t): self._error('invalid #pragma directive', t) ## ## Rules for the normal state ## t_ignore = ' \t' # Newlines def t_NEWLINE(self, t): r'\n+' t.lexer.lineno += t.value.count("\n") # Operators t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_MOD = r'%' t_OR = r'\|' t_AND = r'&' t_NOT = r'~' t_XOR = r'\^' t_LSHIFT = r'<<' t_RSHIFT = r'>>' t_LOR = r'\|\|' t_LAND = r'&&' t_LNOT = r'!' t_LT = r'<' t_GT = r'>' t_LE = r'<=' t_GE = r'>=' t_EQ = r'==' t_NE = r'!=' # Assignment operators t_EQUALS = r'=' t_TIMESEQUAL = r'\*=' t_DIVEQUAL = r'/=' t_MODEQUAL = r'%=' t_PLUSEQUAL = r'\+=' t_MINUSEQUAL = r'-=' t_LSHIFTEQUAL = r'<<=' t_RSHIFTEQUAL = r'>>=' t_ANDEQUAL = r'&=' t_OREQUAL = r'\|=' t_XOREQUAL = r'\^=' # Increment/decrement t_PLUSPLUS = r'\+\+' t_MINUSMINUS = r'--' # -> t_ARROW = r'->' # ? t_CONDOP = r'\?' # Delimeters t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACKET = r'\[' t_RBRACKET = r'\]' t_LBRACE = r'\{' t_RBRACE = r'\}' t_COMMA = r',' t_PERIOD = r'\.' t_SEMI = r';' t_COLON = r':' t_ELLIPSIS = r'\.\.\.' t_STRING_LITERAL = string_literal # The following floating and integer constants are defined as # functions to impose a strict order (otherwise, decimal # is placed before the others because its regex is longer, # and this is bad) # @TOKEN(floating_constant) def t_FLOAT_CONST(self, t): return t @TOKEN(hex_floating_constant) def t_HEX_FLOAT_CONST(self, t): return t @TOKEN(hex_constant) def t_INT_CONST_HEX(self, t): return t @TOKEN(bad_octal_constant) def t_BAD_CONST_OCT(self, t): msg = "Invalid octal constant" self._error(msg, t) @TOKEN(octal_constant) def t_INT_CONST_OCT(self, t): return t @TOKEN(decimal_constant) def t_INT_CONST_DEC(self, t): return t # Must come before bad_char_const, to prevent it from # catching valid char constants as invalid # @TOKEN(char_const) def t_CHAR_CONST(self, t): return t @TOKEN(wchar_const) def t_WCHAR_CONST(self, t): return t @TOKEN(unmatched_quote) def t_UNMATCHED_QUOTE(self, t): msg = "Unmatched '" self._error(msg, t) @TOKEN(bad_char_const) def t_BAD_CHAR_CONST(self, t): msg = "Invalid char constant %s" % t.value self._error(msg, t) @TOKEN(wstring_literal) def t_WSTRING_LITERAL(self, t): return t # unmatched string literals are caught by the preprocessor @TOKEN(bad_string_literal) def t_BAD_STRING_LITERAL(self, t): msg = "String contains invalid escape code" self._error(msg, t) @TOKEN(identifier) def t_ID(self, t): t.type = self.keyword_map.get(t.value, "ID") if t.type == 'ID' and self.type_lookup_func(t.value): t.type = "TYPEID" return t def t_error(self, t): msg = 'Illegal character %s' % repr(t.value[0]) self._error(msg, t) if __name__ == "__main__": filename = '../zp.c' text = open(filename).read() #~ text = '"'+r"""ka \p ka"""+'"' text = r""" 546 #line 66 "kwas\df.h" id 4 # 5 dsf """ def errfoo(msg, a, b): sys.write(msg + "\n") sys.exit() def typelookup(namd): return False clex = CLexer(errfoo, typelookup) clex.build() clex.input(text) while 1: tok = clex.token() if not tok: break printme([tok.value, tok.type, tok.lineno, clex.filename, tok.lexpos])
bussiere/pypyjs
website/demo/home/rfk/repos/pypy/lib_pypy/cffi/_pycparser/c_lexer.py
Python
mit
13,769
[ "NAMD" ]
b2342ccbda7b0e8a69a58e1479d09d0497556967cbe3008cc7954b5baeb320c5
""" Utilities for the MessageQueue package """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __RCSID__ = "$Id$" import queue from DIRAC import S_OK, S_ERROR, gConfig from DIRAC.ConfigurationSystem.Client.CSAPI import CSAPI def getMQParamsFromCS(mqURI): """Function gets parameters of a MQ destination (queue/topic) from the CS. Args: mqURI(str):Pseudo URI identifing the MQ service. It has the following format: mqConnection::DestinationType::DestinationName e.g. blabla.cern.ch::Queues::MyQueue1 mType(str): 'consumer' or 'producer' Returns: S_OK(param_dicts) or S_ERROR """ # API initialization is required to get an up-to-date configuration from the CS csAPI = CSAPI() csAPI.initialize() try: mqService, mqType, mqName = mqURI.split("::") except ValueError: return S_ERROR("Bad format of mqURI address:%s" % (mqURI)) result = gConfig.getConfigurationTree("/Resources/MQServices", mqService, mqType, mqName) if not result["OK"] or not result["Value"]: return S_ERROR("Requested destination not found in the CS: %s::%s::%s" % (mqService, mqType, mqName)) mqDestinationPath = None for path, value in result["Value"].items(): if not value and path.endswith(mqName): mqDestinationPath = path # set-up internal parameter depending on the destination type tmp = mqDestinationPath.split("Queues")[0].split("Topics") servicePath = tmp[0] serviceDict = {} if len(tmp) > 1: serviceDict["Topic"] = mqName else: serviceDict["Queue"] = mqName result = gConfig.getOptionsDict(servicePath) if not result["OK"]: return result serviceDict.update(result["Value"]) result = gConfig.getOptionsDict(mqDestinationPath) if not result["OK"]: return result serviceDict.update(result["Value"]) return S_OK(serviceDict) def getMQService(mqURI): return mqURI.split("::")[0] def getDestinationType(mqURI): return mqURI.split("::")[1] def getDestinationName(mqURI): return mqURI.split("::")[2] def getDestinationAddress(mqURI): mqType, mqName = mqURI.split("::")[-2:] # We remove the trailing 's to change from Queues to Queue mqType = mqType.rstrip("s") return "/" + mqType.lower() + "/" + mqName def generateDefaultCallback(): """Function generates a default callback that can be used to handle the messages in the MQConsumer clients. It contains the internal queue (as closure) for the incoming messages. The queue can be accessed by the callback.get() method. The callback.get() method returns the first message or raise the exception Queue.Empty. e.g. myCallback = generateDefaultCallback() try: print myCallback.get() except Queue.Empty: pass Args: mqURI(str):Pseudo URI identifing MQ connection. It has the following format mqConnection::DestinationType::DestinationName e.g. blabla.cern.ch::Queues::MyQueue1 Returns: object: callback function """ msgQueue = queue.Queue() def callback(headers, body): msgQueue.put(body) return S_OK() def get(): return msgQueue.get(block=False) callback.get = get return callback
ic-hep/DIRAC
src/DIRAC/Resources/MessageQueue/Utilities.py
Python
gpl-3.0
3,444
[ "DIRAC" ]
c34c38df2a38fb4d44abf4b85d33e01e972cdcdcf3db8ef35a3c83a9ccfb2e53
"""TransformationCleaningAgent cleans up finalised transformations. .. literalinclude:: ../ConfigTemplate.cfg :start-after: ##BEGIN TransformationCleaningAgent :end-before: ##END :dedent: 2 :caption: TransformationCleaningAgent options """ # # imports import re import ast import os import errno from datetime import datetime, timedelta # # from DIRAC from DIRAC import S_OK, S_ERROR from DIRAC.Core.Base.AgentModule import AgentModule from DIRAC.Core.Utilities.List import breakListIntoChunks from DIRAC.Core.Utilities.Proxy import executeWithUserProxy from DIRAC.Core.Utilities.DErrno import cmpError from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.ConfigurationSystem.Client.ConfigurationData import gConfigurationData from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.DataManagementSystem.Client.DataManager import DataManager from DIRAC.Resources.Catalog.FileCatalogClient import FileCatalogClient from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.RequestManagementSystem.Client.ReqClient import ReqClient from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient from DIRAC.WorkloadManagementSystem.Client.JobMonitoringClient import JobMonitoringClient from DIRAC.WorkloadManagementSystem.Client.WMSClient import WMSClient # # agent's name AGENT_NAME = "Transformation/TransformationCleaningAgent" class TransformationCleaningAgent(AgentModule): """ .. class:: TransformationCleaningAgent :param ~DIRAC.DataManagementSystem.Client.DataManager.DataManager dm: DataManager instance :param ~TransformationClient.TransformationClient transClient: TransformationClient instance :param ~FileCatalogClient.FileCatalogClient metadataClient: FileCatalogClient instance """ def __init__(self, *args, **kwargs): """c'tor""" AgentModule.__init__(self, *args, **kwargs) self.shifterProxy = None # # transformation client self.transClient = None # # wms client self.wmsClient = None # # request client self.reqClient = None # # file catalog client self.metadataClient = None # # transformations types self.transformationTypes = None # # directory locations self.directoryLocations = ["TransformationDB", "MetadataCatalog"] # # transformation metadata self.transfidmeta = "TransformationID" # # archive periof in days self.archiveAfter = 7 # # transformation log SEs self.logSE = "LogSE" # # enable/disable execution self.enableFlag = "True" self.dataProcTTypes = ["MCSimulation", "Merge"] self.dataManipTTypes = ["Replication", "Removal"] def initialize(self): """agent initialisation reading and setting config opts :param self: self reference """ # # shifter proxy # See cleanContent method: this proxy will be used ALSO when the file catalog used # is the DIRAC File Catalog (DFC). # This is possible because of unset of the "UseServerCertificate" option self.shifterProxy = self.am_getOption("shifterProxy", self.shifterProxy) # # transformations types self.dataProcTTypes = Operations().getValue("Transformations/DataProcessing", self.dataProcTTypes) self.dataManipTTypes = Operations().getValue("Transformations/DataManipulation", self.dataManipTTypes) agentTSTypes = self.am_getOption("TransformationTypes", []) if agentTSTypes: self.transformationTypes = sorted(agentTSTypes) else: self.transformationTypes = sorted(self.dataProcTTypes + self.dataManipTTypes) self.log.info("Will consider the following transformation types: %s" % str(self.transformationTypes)) # # directory locations self.directoryLocations = sorted(self.am_getOption("DirectoryLocations", self.directoryLocations)) self.log.info("Will search for directories in the following locations: %s" % str(self.directoryLocations)) # # transformation metadata self.transfidmeta = self.am_getOption("TransfIDMeta", self.transfidmeta) self.log.info("Will use %s as metadata tag name for TransformationID" % self.transfidmeta) # # archive periof in days self.archiveAfter = self.am_getOption("ArchiveAfter", self.archiveAfter) # days self.log.info("Will archive Completed transformations after %d days" % self.archiveAfter) # # transformation log SEs self.logSE = Operations().getValue("/LogStorage/LogSE", self.logSE) self.log.info("Will remove logs found on storage element: %s" % self.logSE) # # transformation client self.transClient = TransformationClient() # # wms client self.wmsClient = WMSClient() # # request client self.reqClient = ReqClient() # # file catalog client self.metadataClient = FileCatalogClient() # # job monitoring client self.jobMonitoringClient = JobMonitoringClient() return S_OK() ############################################################################# def execute(self): """execution in one agent's cycle :param self: self reference """ self.enableFlag = self.am_getOption("EnableFlag", self.enableFlag) if self.enableFlag != "True": self.log.info("TransformationCleaningAgent is disabled by configuration option EnableFlag") return S_OK("Disabled via CS flag") # Obtain the transformations in Cleaning status and remove any mention of the jobs/files res = self.transClient.getTransformations({"Status": "Cleaning", "Type": self.transformationTypes}) if res["OK"]: for transDict in res["Value"]: if self.shifterProxy: self._executeClean(transDict) else: self.log.info( "Cleaning transformation %(TransformationID)s with %(AuthorDN)s, %(AuthorGroup)s" % transDict ) executeWithUserProxy(self._executeClean)( transDict, proxyUserDN=transDict["AuthorDN"], proxyUserGroup=transDict["AuthorGroup"] ) else: self.log.error("Failed to get transformations", res["Message"]) # Obtain the transformations in RemovingFiles status and removes the output files res = self.transClient.getTransformations({"Status": "RemovingFiles", "Type": self.transformationTypes}) if res["OK"]: for transDict in res["Value"]: if self.shifterProxy: self._executeRemoval(transDict) else: self.log.info( "Removing files for transformation %(TransformationID)s with %(AuthorDN)s, %(AuthorGroup)s" % transDict ) executeWithUserProxy(self._executeRemoval)( transDict, proxyUserDN=transDict["AuthorDN"], proxyUserGroup=transDict["AuthorGroup"] ) else: self.log.error("Could not get the transformations", res["Message"]) # Obtain the transformations in Completed status and archive if inactive for X days olderThanTime = datetime.utcnow() - timedelta(days=self.archiveAfter) res = self.transClient.getTransformations( {"Status": "Completed", "Type": self.transformationTypes}, older=olderThanTime, timeStamp="LastUpdate" ) if res["OK"]: for transDict in res["Value"]: if self.shifterProxy: self._executeArchive(transDict) else: self.log.info( "Archiving files for transformation %(TransformationID)s with %(AuthorDN)s, %(AuthorGroup)s" % transDict ) executeWithUserProxy(self._executeArchive)( transDict, proxyUserDN=transDict["AuthorDN"], proxyUserGroup=transDict["AuthorGroup"] ) else: self.log.error("Could not get the transformations", res["Message"]) return S_OK() def finalize(self): """Only at finalization: will clean ancient transformations (remnants) 1) get the transformation IDs of jobs that are older than 1 year 2) find the status of those transformations. Those "Cleaned" and "Archived" will be cleaned and archived (again) Why doing this here? Basically, it's a race: 1) the production manager submits a transformation 2) the TransformationAgent, and a bit later the WorkflowTaskAgent, put such transformation in their internal queue, so eventually during their (long-ish) cycle they'll work on it. 3) 1 minute after creating the transformation, the production manager cleans it (by hand, for whatever reason). So, the status is changed to "Cleaning" 4) the TransformationCleaningAgent cleans what has been created (maybe, nothing), then sets the transformation status to "Cleaned" or "Archived" 5) a bit later the TransformationAgent, and later the WorkflowTaskAgent, kick in, creating tasks and jobs for a production that's effectively cleaned (but these 2 agents don't know yet). Of course, one could make one final check in TransformationAgent or WorkflowTaskAgent, but these 2 agents are already doing a lot of stuff, and are pretty heavy. So, we should just clean from time to time. What I added here is done only when the agent finalize, and it's quite light-ish operation anyway. """ res = self.jobMonitoringClient.getJobGroups(None, datetime.utcnow() - timedelta(days=365)) if not res["OK"]: self.log.error("Failed to get job groups", res["Message"]) return res transformationIDs = res["Value"] if transformationIDs: res = self.transClient.getTransformations({"TransformationID": transformationIDs}) if not res["OK"]: self.log.error("Failed to get transformations", res["Message"]) return res transformations = res["Value"] toClean = [] toArchive = [] for transDict in transformations: if transDict["Status"] == "Cleaned": toClean.append(transDict) if transDict["Status"] == "Archived": toArchive.append(transDict) for transDict in toClean: if self.shifterProxy: self._executeClean(transDict) else: self.log.info( "Cleaning transformation %(TransformationID)s with %(AuthorDN)s, %(AuthorGroup)s" % transDict ) executeWithUserProxy(self._executeClean)( transDict, proxyUserDN=transDict["AuthorDN"], proxyUserGroup=transDict["AuthorGroup"] ) for transDict in toArchive: if self.shifterProxy: self._executeArchive(transDict) else: self.log.info( "Archiving files for transformation %(TransformationID)s with %(AuthorDN)s, %(AuthorGroup)s" % transDict ) executeWithUserProxy(self._executeArchive)( transDict, proxyUserDN=transDict["AuthorDN"], proxyUserGroup=transDict["AuthorGroup"] ) # Remove JobIDs that were unknown to the TransformationSystem jobGroupsToCheck = [str(transDict["TransformationID"]).zfill(8) for transDict in toClean + toArchive] res = self.jobMonitoringClient.getJobs({"JobGroup": jobGroupsToCheck}) if not res["OK"]: return res jobIDsToRemove = [int(jobID) for jobID in res["Value"]] res = self.__removeWMSTasks(jobIDsToRemove) if not res["OK"]: return res return S_OK() def _executeClean(self, transDict): """Clean transformation.""" # if transformation is of type `Replication` or `Removal`, there is nothing to clean. # We just archive if transDict["Type"] in self.dataManipTTypes: res = self.archiveTransformation(transDict["TransformationID"]) if not res["OK"]: self.log.error( "Problems archiving transformation", "%s: %s" % (transDict["TransformationID"], res["Message"]) ) else: res = self.cleanTransformation(transDict["TransformationID"]) if not res["OK"]: self.log.error( "Problems cleaning transformation", "%s: %s" % (transDict["TransformationID"], res["Message"]) ) def _executeRemoval(self, transDict): """Remove files from given transformation.""" res = self.removeTransformationOutput(transDict["TransformationID"]) if not res["OK"]: self.log.error( "Problems removing transformation", "%s: %s" % (transDict["TransformationID"], res["Message"]) ) def _executeArchive(self, transDict): """Archive the given transformation.""" res = self.archiveTransformation(transDict["TransformationID"]) if not res["OK"]: self.log.error( "Problems archiving transformation", "%s: %s" % (transDict["TransformationID"], res["Message"]) ) return S_OK() ############################################################################# # # Get the transformation directories for checking # def getTransformationDirectories(self, transID): """get the directories for the supplied transformation from the transformation system. These directories are used by removeTransformationOutput and cleanTransformation for removing output. :param self: self reference :param int transID: transformation ID """ self.log.verbose("Cleaning Transformation directories of transformation %d" % transID) directories = [] if "TransformationDB" in self.directoryLocations: res = self.transClient.getTransformationParameters(transID, ["OutputDirectories"]) if not res["OK"]: self.log.error("Failed to obtain transformation directories", res["Message"]) return res transDirectories = [] if res["Value"]: if not isinstance(res["Value"], list): try: transDirectories = ast.literal_eval(res["Value"]) except Exception: # It can happen if the res['Value'] is '/a/b/c' instead of '["/a/b/c"]' transDirectories.append(res["Value"]) else: transDirectories = res["Value"] directories = self._addDirs(transID, transDirectories, directories) if "MetadataCatalog" in self.directoryLocations: res = self.metadataClient.findDirectoriesByMetadata({self.transfidmeta: transID}) if not res["OK"]: self.log.error("Failed to obtain metadata catalog directories", res["Message"]) return res transDirectories = res["Value"] directories = self._addDirs(transID, transDirectories, directories) if not directories: self.log.info("No output directories found") directories = sorted(directories) return S_OK(directories) @classmethod def _addDirs(cls, transID, newDirs, existingDirs): """append unique :newDirs: list to :existingDirs: list :param self: self reference :param int transID: transformationID :param list newDirs: src list of paths :param list existingDirs: dest list of paths """ for folder in newDirs: transStr = str(transID).zfill(8) if re.search(transStr, str(folder)): if folder not in existingDirs: existingDirs.append(os.path.normpath(folder)) return existingDirs ############################################################################# # # These are the methods for performing the cleaning of catalogs and storage # def cleanContent(self, directory): """wipe out everything from catalog under folder :directory: :param self: self reference :params str directory: folder name """ self.log.verbose("Cleaning Catalog contents") res = self.__getCatalogDirectoryContents([directory]) if not res["OK"]: return res filesFound = res["Value"] if not filesFound: self.log.info("No files are registered in the catalog directory %s" % directory) return S_OK() self.log.info("Attempting to remove possible remnants from the catalog and storage", "(n=%d)" % len(filesFound)) # Executing with shifter proxy gConfigurationData.setOptionInCFG("/DIRAC/Security/UseServerCertificate", "false") res = DataManager().removeFile(filesFound, force=True) gConfigurationData.setOptionInCFG("/DIRAC/Security/UseServerCertificate", "true") if not res["OK"]: return res realFailure = False for lfn, reason in res["Value"]["Failed"].items(): if "File does not exist" in str(reason): self.log.warn("File %s not found in some catalog: " % (lfn)) else: self.log.error("Failed to remove file found in the catalog", "%s %s" % (lfn, reason)) realFailure = True if realFailure: return S_ERROR("Failed to remove all files found in the catalog") return S_OK() def __getCatalogDirectoryContents(self, directories): """get catalog contents under paths :directories: :param self: self reference :param list directories: list of paths in catalog """ self.log.info("Obtaining the catalog contents for %d directories:" % len(directories)) for directory in directories: self.log.info(directory) activeDirs = directories allFiles = {} fc = FileCatalog() while activeDirs: currentDir = activeDirs[0] res = returnSingleResult(fc.listDirectory(currentDir)) activeDirs.remove(currentDir) if not res["OK"] and "Directory does not exist" in res["Message"]: # FIXME: DFC should return errno self.log.info("The supplied directory %s does not exist" % currentDir) elif not res["OK"]: if "No such file or directory" in res["Message"]: self.log.info("%s: %s" % (currentDir, res["Message"])) else: self.log.error("Failed to get directory %s content" % currentDir, res["Message"]) else: dirContents = res["Value"] activeDirs.extend(dirContents["SubDirs"]) allFiles.update(dirContents["Files"]) self.log.info("", "Found %d files" % len(allFiles)) return S_OK(list(allFiles)) def cleanTransformationLogFiles(self, directory): """clean up transformation logs from directory :directory: :param self: self reference :param str directory: folder name """ self.log.verbose("Removing log files found in the directory", directory) res = returnSingleResult(StorageElement(self.logSE).removeDirectory(directory, recursive=True)) if not res["OK"]: if cmpError(res, errno.ENOENT): # No such file or directory self.log.warn("Transformation log directory does not exist", directory) return S_OK() self.log.error("Failed to remove log files", res["Message"]) return res self.log.info("Successfully removed transformation log directory") return S_OK() ############################################################################# # # These are the functional methods for archiving and cleaning transformations # def removeTransformationOutput(self, transID): """This just removes any mention of the output data from the catalog and storage""" self.log.info("Removing output data for transformation %s" % transID) res = self.getTransformationDirectories(transID) if not res["OK"]: self.log.error("Problem obtaining directories for transformation", "%s with result '%s'" % (transID, res)) return S_OK() directories = res["Value"] for directory in directories: if not re.search("/LOG/", directory): res = self.cleanContent(directory) if not res["OK"]: return res self.log.info( "Removed %d directories from the catalog \ and its files from the storage for transformation %s" % (len(directories), transID) ) # Clean ALL the possible remnants found in the metadata catalog res = self.cleanMetadataCatalogFiles(transID) if not res["OK"]: return res self.log.info("Successfully removed output of transformation", transID) # Change the status of the transformation to RemovedFiles res = self.transClient.setTransformationParameter(transID, "Status", "RemovedFiles") if not res["OK"]: self.log.error("Failed to update status of transformation %s to RemovedFiles" % (transID), res["Message"]) return res self.log.info("Updated status of transformation %s to RemovedFiles" % (transID)) return S_OK() def archiveTransformation(self, transID): """This just removes job from the jobDB and the transformation DB :param self: self reference :param int transID: transformation ID """ self.log.info("Archiving transformation %s" % transID) # Clean the jobs in the WMS and any failover requests found res = self.cleanTransformationTasks(transID) if not res["OK"]: return res # Clean the transformation DB of the files and job information res = self.transClient.cleanTransformation(transID) if not res["OK"]: return res self.log.info("Successfully archived transformation %d" % transID) # Change the status of the transformation to archived res = self.transClient.setTransformationParameter(transID, "Status", "Archived") if not res["OK"]: self.log.error("Failed to update status of transformation %s to Archived" % (transID), res["Message"]) return res self.log.info("Updated status of transformation %s to Archived" % (transID)) return S_OK() def cleanTransformation(self, transID): """This removes what was produced by the supplied transformation, leaving only some info and log in the transformation DB. """ self.log.info("Cleaning transformation", transID) res = self.getTransformationDirectories(transID) if not res["OK"]: self.log.error( "Problem obtaining directories for transformation", "%s with result '%s'" % (transID, res["Message"]) ) return S_OK() directories = res["Value"] # Clean the jobs in the WMS and any failover requests found res = self.cleanTransformationTasks(transID) if not res["OK"]: return res # Clean the log files for the jobs for directory in directories: if re.search("/LOG/", directory): res = self.cleanTransformationLogFiles(directory) if not res["OK"]: return res res = self.cleanContent(directory) if not res["OK"]: return res # Clean ALL the possible remnants found res = self.cleanMetadataCatalogFiles(transID) if not res["OK"]: return res # Clean the transformation DB of the files and job information res = self.transClient.cleanTransformation(transID) if not res["OK"]: return res self.log.info("Successfully cleaned transformation", transID) res = self.transClient.setTransformationParameter(transID, "Status", "Cleaned") if not res["OK"]: self.log.error("Failed to update status of transformation %s to Cleaned" % (transID), res["Message"]) return res self.log.info("Updated status of transformation", "%s to Cleaned" % (transID)) return S_OK() def cleanMetadataCatalogFiles(self, transID): """wipe out files from catalog""" res = self.metadataClient.findFilesByMetadata({self.transfidmeta: transID}) if not res["OK"]: return res fileToRemove = res["Value"] if not fileToRemove: self.log.info("No files found for transID", transID) return S_OK() # Executing with shifter proxy gConfigurationData.setOptionInCFG("/DIRAC/Security/UseServerCertificate", "false") res = DataManager().removeFile(fileToRemove, force=True) gConfigurationData.setOptionInCFG("/DIRAC/Security/UseServerCertificate", "true") if not res["OK"]: return res for lfn, reason in res["Value"]["Failed"].items(): self.log.error("Failed to remove file found in metadata catalog", "%s %s" % (lfn, reason)) if res["Value"]["Failed"]: return S_ERROR("Failed to remove all files found in the metadata catalog") self.log.info("Successfully removed all files found in the DFC") return S_OK() ############################################################################# # # These are the methods for removing the jobs from the WMS and transformation DB # def cleanTransformationTasks(self, transID): """clean tasks from WMS, or from the RMS if it is a DataManipulation transformation""" self.log.verbose("Cleaning Transformation tasks of transformation", transID) res = self.__getTransformationExternalIDs(transID) if not res["OK"]: return res externalIDs = res["Value"] if externalIDs: res = self.transClient.getTransformationParameters(transID, ["Type"]) if not res["OK"]: self.log.error("Failed to determine transformation type") return res transType = res["Value"] if transType in self.dataProcTTypes: res = self.__removeWMSTasks(externalIDs) else: res = self.__removeRequests(externalIDs) if not res["OK"]: return res return S_OK() def __getTransformationExternalIDs(self, transID): """collect all ExternalIDs for transformation :transID: :param self: self reference :param int transID: transforamtion ID """ res = self.transClient.getTransformationTasks(condDict={"TransformationID": transID}) if not res["OK"]: self.log.error("Failed to get externalIDs for transformation %d" % transID, res["Message"]) return res externalIDs = [taskDict["ExternalID"] for taskDict in res["Value"]] self.log.info("Found %d tasks for transformation" % len(externalIDs)) return S_OK(externalIDs) def __removeRequests(self, requestIDs): """This will remove requests from the RMS system -""" rIDs = [int(int(j)) for j in requestIDs if int(j)] for reqID in rIDs: self.reqClient.cancelRequest(reqID) return S_OK() def __removeWMSTasks(self, transJobIDs): """delete jobs (mark their status as "JobStatus.DELETED") and their requests from the system :param self: self reference :param list trasnJobIDs: job IDs """ # Prevent 0 job IDs jobIDs = [int(j) for j in transJobIDs if int(j)] allRemove = True for jobList in breakListIntoChunks(jobIDs, 500): res = self.wmsClient.killJob(jobList) if res["OK"]: self.log.info("Successfully killed %d jobs from WMS" % len(jobList)) elif ("InvalidJobIDs" in res) and ("NonauthorizedJobIDs" not in res) and ("FailedJobIDs" not in res): self.log.info("Found jobs which did not exist in the WMS", "(n=%d)" % len(res["InvalidJobIDs"])) elif "NonauthorizedJobIDs" in res: self.log.error("Failed to kill jobs because not authorized", "(n=%d)" % len(res["NonauthorizedJobIDs"])) allRemove = False elif "FailedJobIDs" in res: self.log.error("Failed to kill jobs", "(n=%d)" % len(res["FailedJobIDs"])) allRemove = False res = self.wmsClient.deleteJob(jobList) if res["OK"]: self.log.info("Successfully deleted jobs from WMS", "(n=%d)" % len(jobList)) elif ("InvalidJobIDs" in res) and ("NonauthorizedJobIDs" not in res) and ("FailedJobIDs" not in res): self.log.info("Found jobs which did not exist in the WMS", "(n=%d)" % len(res["InvalidJobIDs"])) elif "NonauthorizedJobIDs" in res: self.log.error( "Failed to delete jobs because not authorized", "(n=%d)" % len(res["NonauthorizedJobIDs"]) ) allRemove = False elif "FailedJobIDs" in res: self.log.error("Failed to delete jobs", "(n=%d)" % len(res["FailedJobIDs"])) allRemove = False if not allRemove: return S_ERROR("Failed to delete all remnants from WMS") self.log.info("Successfully deleted all tasks from the WMS") if not jobIDs: self.log.info("JobIDs not present, unable to delete associated requests.") return S_OK() failed = 0 failoverRequests = {} res = self.reqClient.getRequestIDsForJobs(jobIDs) if not res["OK"]: self.log.error("Failed to get requestID for jobs.", res["Message"]) return res failoverRequests.update(res["Value"]["Successful"]) if not failoverRequests: return S_OK() for jobID, requestID in res["Value"]["Successful"].items(): # Put this check just in case, tasks must have associated jobs if jobID == 0 or jobID == "0": continue res = self.reqClient.cancelRequest(requestID) if not res["OK"]: self.log.error("Failed to remove request from RequestDB", res["Message"]) failed += 1 else: self.log.verbose("Removed request %s associated to job %d." % (requestID, jobID)) if failed: self.log.info("Successfully removed requests", "(n=%d)" % (len(failoverRequests) - failed)) self.log.info("Failed to remove requests", "(n=%d)" % failed) return S_ERROR("Failed to remove all the request from RequestDB") self.log.info("Successfully removed all the associated failover requests") return S_OK()
DIRACGrid/DIRAC
src/DIRAC/TransformationSystem/Agent/TransformationCleaningAgent.py
Python
gpl-3.0
31,943
[ "DIRAC" ]
0f0ba87763f725993d5d322b415d80d86168eeeaf891e2993efd488b688101c2
# -*- 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:`xml` module provides the XML functionality. The basic XML for storing the lyrics in the song database looks like this:: <?xml version="1.0" encoding="UTF-8"?> <song version="1.0"> <lyrics> <verse type="c" label="1" lang="en"> <![CDATA[Chorus optional split 1[---]Chorus optional split 2]]> </verse> </lyrics> </song> The XML of an `OpenLyrics <http://openlyrics.info/>`_ song looks like this:: <song xmlns="http://openlyrics.info/namespace/2009/song" version="0.7" createdIn="OpenLP 1.9.0" modifiedIn="ChangingSong 0.0.1" modifiedDate="2010-01-28T13:15:30+01:00"> <properties> <titles> <title>Amazing Grace</title> </titles> </properties> <lyrics> <verse name="v1"> <lines> <line>Amazing grace how sweet the sound</line> </lines> </verse> </lyrics> </song> """ import cgi import logging import re from lxml import etree, objectify from openlp.core.lib import FormattingTags, translate from openlp.plugins.songs.lib import VerseType, clean_song from openlp.plugins.songs.lib.db import Author, Book, Song, Topic from openlp.core.utils import get_application_version log = logging.getLogger(__name__) NAMESPACE = u'http://openlyrics.info/namespace/2009/song' NSMAP = '{' + NAMESPACE + '}' + '%s' class SongXML(object): """ This class builds and parses the XML used to describe songs. """ log.info(u'SongXML Loaded') def __init__(self): """ Set up the default variables. """ self.song_xml = objectify.fromstring(u'<song version="1.0" />') self.lyrics = etree.SubElement(self.song_xml, u'lyrics') def add_verse_to_lyrics(self, type, number, content, lang=None): """ Add a verse to the ``<lyrics>`` tag. ``type`` A string denoting the type of verse. Possible values are *v*, *c*, *b*, *p*, *i*, *e* and *o*. Any other type is **not** allowed, this also includes translated types. ``number`` An integer denoting the number of the item, for example: verse 1. ``content`` The actual text of the verse to be stored. ``lang`` The verse's language code (ISO-639). This is not required, but should be added if available. """ verse = etree.Element(u'verse', type=unicode(type), label=unicode(number)) if lang: verse.set(u'lang', lang) verse.text = etree.CDATA(content) self.lyrics.append(verse) def extract_xml(self): """ Extract our newly created XML song. """ return etree.tostring(self.song_xml, encoding=u'UTF-8', xml_declaration=True) def get_verses(self, xml): """ Iterates through the verses in the XML and returns a list of verses and their attributes. ``xml`` The XML of the song to be parsed. The returned list has the following format:: [[{'type': 'v', 'label': '1'}, u"optional slide split 1[---]optional slide split 2"], [{'lang': 'en', 'type': 'c', 'label': '1'}, u"English chorus"]] """ self.song_xml = None verse_list = [] if not xml.startswith(u'<?xml') and not xml.startswith(u'<song'): # This is an old style song, without XML. Let's handle it correctly # by iterating through the verses, and then recreating the internal # xml object as well. self.song_xml = objectify.fromstring(u'<song version="1.0" />') self.lyrics = etree.SubElement(self.song_xml, u'lyrics') verses = xml.split(u'\n\n') for count, verse in enumerate(verses): verse_list.append([{u'type': u'v', u'label': unicode(count)}, unicode(verse)]) self.add_verse_to_lyrics(u'v', unicode(count), verse) return verse_list elif xml.startswith(u'<?xml'): xml = xml[38:] try: self.song_xml = objectify.fromstring(xml) except etree.XMLSyntaxError: log.exception(u'Invalid xml %s', xml) xml_iter = self.song_xml.getiterator() for element in xml_iter: if element.tag == u'verse': if element.text is None: element.text = u'' verse_list.append([element.attrib, unicode(element.text)]) return verse_list def dump_xml(self): """ Debugging aid to dump XML so that we can see what we have. """ return etree.dump(self.song_xml) class OpenLyrics(object): """ This class represents the converter for OpenLyrics XML (version 0.8) to/from a song. As OpenLyrics has a rich set of different features, we cannot support them all. The following features are supported by the :class:`OpenLyrics` class: ``<authors>`` OpenLP does not support the attribute *type* and *lang*. ``<chord>`` This property is not supported. ``<comments>`` The ``<comments>`` property is fully supported. But comments in lyrics are not supported. ``<copyright>`` This property is fully supported. ``<customVersion>`` This property is not supported. ``<key>`` This property is not supported. ``<format>`` The custom formatting tags are fully supported. ``<keywords>`` This property is not supported. ``<lines>`` The attribute *part* is not supported. The *break* attribute is supported. ``<publisher>`` This property is not supported. ``<songbooks>`` As OpenLP does only support one songbook, we cannot consider more than one songbook. ``<tempo>`` This property is not supported. ``<themes>`` Topics, as they are called in OpenLP, are fully supported, whereby only the topic text (e. g. Grace) is considered, but neither the *id* nor *lang*. ``<transposition>`` This property is not supported. ``<variant>`` This property is not supported. ``<verse name="v1a" lang="he" translit="en">`` The attribute *translit* is not supported. Note, the attribute *lang* is considered, but there is not further functionality implemented yet. The following verse "types" are supported by OpenLP: * v * c * b * p * i * e * o The verse "types" stand for *Verse*, *Chorus*, *Bridge*, *Pre-Chorus*, *Intro*, *Ending* and *Other*. Any numeric value is allowed after the verse type. The complete verse name in OpenLP always consists of the verse type and the verse number. If not number is present *1* is assumed. OpenLP will merge verses which are split up by appending a letter to the verse name, such as *v1a*. ``<verseOrder>`` OpenLP supports this property. """ IMPLEMENTED_VERSION = u'0.8' START_TAGS_REGEX = re.compile(r'\{(\w+)\}') END_TAGS_REGEX = re.compile(r'\{\/(\w+)\}') VERSE_TAG_SPLITTER = re.compile(u'([a-zA-Z]+)([0-9]*)([a-zA-Z]?)') def __init__(self, manager): self.manager = manager def song_to_xml(self, song): """ Convert the song to OpenLyrics Format. """ sxml = SongXML() song_xml = objectify.fromstring(u'<song/>') # Append the necessary meta data to the song. song_xml.set(u'xmlns', NAMESPACE) song_xml.set(u'version', OpenLyrics.IMPLEMENTED_VERSION) application_name = u'OpenLP ' + get_application_version()[u'version'] song_xml.set(u'createdIn', application_name) song_xml.set(u'modifiedIn', application_name) # "Convert" 2012-08-27 11:49:15 to 2012-08-27T11:49:15. song_xml.set(u'modifiedDate', unicode(song.last_modified).replace(u' ', u'T')) properties = etree.SubElement(song_xml, u'properties') titles = etree.SubElement(properties, u'titles') self._add_text_to_element(u'title', titles, song.title) if song.alternate_title: self._add_text_to_element(u'title', titles, song.alternate_title) if song.comments: comments = etree.SubElement(properties, u'comments') self._add_text_to_element(u'comment', comments, song.comments) if song.copyright: self._add_text_to_element(u'copyright', properties, song.copyright) if song.verse_order: self._add_text_to_element( u'verseOrder', properties, song.verse_order.lower()) if song.ccli_number: self._add_text_to_element(u'ccliNo', properties, song.ccli_number) if song.authors: authors = etree.SubElement(properties, u'authors') for author in song.authors: self._add_text_to_element(u'author', authors, author.display_name) book = self.manager.get_object_filtered(Book, Book.id == song.song_book_id) if book is not None: book = book.name songbooks = etree.SubElement(properties, u'songbooks') element = self._add_text_to_element(u'songbook', songbooks, None, book) if song.song_number: element.set(u'entry', song.song_number) if song.topics: themes = etree.SubElement(properties, u'themes') for topic in song.topics: self._add_text_to_element(u'theme', themes, topic.name) # Process the formatting tags. # Have we any tags in song lyrics? tags_element = None match = re.search(u'\{/?\w+\}', song.lyrics, re.UNICODE) if match: # Named 'format_' - 'format' is built-in fuction in Python. format_ = etree.SubElement(song_xml, u'format') tags_element = etree.SubElement(format_, u'tags') tags_element.set(u'application', u'OpenLP') # Process the song's lyrics. lyrics = etree.SubElement(song_xml, u'lyrics') verse_list = sxml.get_verses(song.lyrics) # Add a suffix letter to each verse verse_tags = [] for verse in verse_list: verse_tag = verse[0][u'type'][0].lower() verse_number = verse[0][u'label'] verse_def = verse_tag + verse_number verse_tags.append(verse_def) # Create the letter from the number of duplicates verse[0][u'suffix'] = chr(96 + verse_tags.count(verse_def)) # If the verse tag is a duplicate use the suffix letter for verse in verse_list: verse_tag = verse[0][u'type'][0].lower() verse_number = verse[0][u'label'] verse_def = verse_tag + verse_number if verse_tags.count(verse_def) > 1: verse_def += verse[0][u'suffix'] verse_element = self._add_text_to_element(u'verse', lyrics, None, verse_def) if u'lang' in verse[0]: verse_element.set(u'lang', verse[0][u'lang']) # Create a list with all "optional" verses. optional_verses = cgi.escape(verse[1]) optional_verses = optional_verses.split(u'\n[---]\n') start_tags = u'' end_tags = u'' for index, optional_verse in enumerate(optional_verses): # Fix up missing end and start tags such as {r} or {/r}. optional_verse = start_tags + optional_verse start_tags, end_tags = self._get_missing_tags(optional_verse) optional_verse += end_tags # Add formatting tags to text lines_element = self._add_text_with_tags_to_lines(verse_element, optional_verse, tags_element) # Do not add the break attribute to the last lines element. if index < len(optional_verses) - 1: lines_element.set(u'break', u'optional') return self._extract_xml(song_xml) def _get_missing_tags(self, text): """ Tests the given text for not closed formatting tags and returns a tuple consisting of two unicode strings:: (u'{st}{r}', u'{/r}{/st}') The first unicode string are the start tags (for the next slide). The second unicode string are the end tags. ``text`` The text to test. The text must **not** contain html tags, only OpenLP formatting tags are allowed:: {st}{r}Text text text """ tags = [] for tag in FormattingTags.get_html_tags(): if tag[u'start tag'] == u'{br}': continue if text.count(tag[u'start tag']) != text.count(tag[u'end tag']): tags.append((text.find(tag[u'start tag']), tag[u'start tag'], tag[u'end tag'])) # Sort the lists, so that the tags which were opened first on the first # slide (the text we are checking) will be opened first on the next # slide as well. tags.sort(key=lambda tag: tag[0]) end_tags = [] start_tags = [] for tag in tags: start_tags.append(tag[1]) end_tags.append(tag[2]) end_tags.reverse() return u''.join(start_tags), u''.join(end_tags) def xml_to_song(self, xml, parse_and_temporary_save=False): """ Create and save a song from OpenLyrics format xml to the database. Since we also export XML from external sources (e. g. OpenLyrics import), we cannot ensure, that it completely conforms to the OpenLyrics standard. ``xml`` The XML to parse (unicode). ``parse_and_temporary_save`` Switch to skip processing the whole song and storing the songs in the database with a temporary flag. Defaults to ``False``. """ # No xml get out of here. if not xml: return None if xml[:5] == u'<?xml': xml = xml[38:] song_xml = objectify.fromstring(xml) if hasattr(song_xml, u'properties'): properties = song_xml.properties else: return None # Formatting tags are new in OpenLyrics 0.8 if float(song_xml.get(u'version')) > 0.7: self._process_formatting_tags(song_xml, parse_and_temporary_save) song = Song() # Values will be set when cleaning the song. song.search_lyrics = u'' song.verse_order = u'' song.search_title = u'' song.temporary = parse_and_temporary_save self._process_copyright(properties, song) self._process_cclinumber(properties, song) self._process_titles(properties, song) # The verse order is processed with the lyrics! self._process_lyrics(properties, song_xml, song) self._process_comments(properties, song) self._process_authors(properties, song) self._process_songbooks(properties, song) self._process_topics(properties, song) clean_song(self.manager, song) self.manager.save_object(song) return song def _add_text_to_element(self, tag, parent, text=None, label=None): if label: element = etree.Element(tag, name=unicode(label)) else: element = etree.Element(tag) if text: element.text = unicode(text) parent.append(element) return element def _add_tag_to_formatting(self, tag_name, tags_element): """ Add new formatting tag to the element ``<format>`` if the tag is not present yet. """ available_tags = FormattingTags.get_html_tags() start_tag = '{%s}' % tag_name for tag in available_tags: if tag[u'start tag'] == start_tag: # Create new formatting tag in openlyrics xml. element = self._add_text_to_element(u'tag', tags_element) element.set(u'name', tag_name) element_open = self._add_text_to_element(u'open', element) element_open.text = etree.CDATA(tag[u'start html']) # Check if formatting tag contains end tag. Some formatting # tags e.g. {br} has only start tag. If no end tag is present # <close> element has not to be in OpenLyrics xml. if tag['end tag']: element_close = self._add_text_to_element(u'close', element) element_close.text = etree.CDATA(tag[u'end html']) def _add_text_with_tags_to_lines(self, verse_element, text, tags_element): """ Convert text with formatting tags from OpenLP format to OpenLyrics format and append it to element ``<lines>``. """ start_tags = OpenLyrics.START_TAGS_REGEX.findall(text) end_tags = OpenLyrics.END_TAGS_REGEX.findall(text) # Replace start tags with xml syntax. for tag in start_tags: # Tags already converted to xml structure. xml_tags = tags_element.xpath(u'tag/attribute::name') # Some formatting tag has only starting part e.g. <br>. # Handle this case. if tag in end_tags: text = text.replace(u'{%s}' % tag, u'<tag name="%s">' % tag) else: text = text.replace(u'{%s}' % tag, u'<tag name="%s"/>' % tag) # Add tag to <format> element if tag not present. if tag not in xml_tags: self._add_tag_to_formatting(tag, tags_element) # Replace end tags. for tag in end_tags: text = text.replace(u'{/%s}' % tag, u'</tag>') # Replace \n with <br/>. text = text.replace(u'\n', u'<br/>') element = etree.XML(u'<lines>%s</lines>' % text) verse_element.append(element) return element def _extract_xml(self, xml): """ Extract our newly created XML song. """ return etree.tostring(xml, encoding=u'UTF-8', xml_declaration=True) def _text(self, element): """ This returns the text of an element as unicode string. ``element`` The element. """ if element.text is not None: return unicode(element.text) return u'' def _process_authors(self, properties, song): """ Adds the authors specified in the XML to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ authors = [] if hasattr(properties, u'authors'): for author in properties.authors.author: display_name = self._text(author) if display_name: authors.append(display_name) for display_name in authors: author = self.manager.get_object_filtered(Author, Author.display_name == display_name) if author is None: # We need to create a new author, as the author does not exist. author = Author.populate(display_name=display_name, last_name=display_name.split(u' ')[-1], first_name=u' '.join(display_name.split(u' ')[:-1])) song.authors.append(author) def _process_cclinumber(self, properties, song): """ Adds the CCLI number to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ if hasattr(properties, u'ccliNo'): song.ccli_number = self._text(properties.ccliNo) def _process_comments(self, properties, song): """ Joins the comments specified in the XML and add it to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ if hasattr(properties, u'comments'): comments_list = [] for comment in properties.comments.comment: comment_text = self._text(comment) if comment_text: comments_list.append(comment_text) song.comments = u'\n'.join(comments_list) def _process_copyright(self, properties, song): """ Adds the copyright to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ if hasattr(properties, u'copyright'): song.copyright = self._text(properties.copyright) def _process_formatting_tags(self, song_xml, temporary): """ Process the formatting tags from the song and either add missing tags temporary or permanently to the formatting tag list. """ if not hasattr(song_xml, u'format'): return found_tags = [] for tag in song_xml.format.tags.getchildren(): name = tag.get(u'name') if name is None: continue start_tag = u'{%s}' % name[:5] # Some tags have only start tag e.g. {br} end_tag = u'{/' + name[:5] + u'}' if hasattr(tag, 'close') else u'' openlp_tag = { u'desc': name, u'start tag': start_tag, u'end tag': end_tag, u'start html': tag.open.text, # Some tags have only start html e.g. {br} u'end html': tag.close.text if hasattr(tag, 'close') else u'', u'protected': False, } # Add 'temporary' key in case the formatting tag should not be # saved otherwise it is supposed that formatting tag is permanent. if temporary: openlp_tag[u'temporary'] = temporary found_tags.append(openlp_tag) existing_tag_ids = [tag[u'start tag'] for tag in FormattingTags.get_html_tags()] new_tags = [tag for tag in found_tags if tag[u'start tag'] not in existing_tag_ids] FormattingTags.add_html_tags(new_tags) FormattingTags.save_html_tags() def _process_lines_mixed_content(self, element, newlines=True): """ Converts the xml text with mixed content to OpenLP representation. Chords are skipped and formatting tags are converted. ``element`` The property object (lxml.etree.Element). ``newlines`` The switch to enable/disable processing of line breaks <br/>. The <br/> is used since OpenLyrics 0.8. """ text = u'' use_endtag = True # Skip <comment> elements - not yet supported. if element.tag == NSMAP % u'comment': if element.tail: # Append tail text at chord element. text += element.tail return text # Skip <chord> element - not yet supported. elif element.tag == NSMAP % u'chord': if element.tail: # Append tail text at chord element. text += element.tail return text # Convert line breaks <br/> to \n. elif newlines and element.tag == NSMAP % u'br': text += u'\n' if element.tail: text += element.tail return text # Start formatting tag. if element.tag == NSMAP % u'tag': text += u'{%s}' % element.get(u'name') # Some formattings may have only start tag. # Handle this case if element has no children and contains no text. if not element and not element.text: use_endtag = False # Append text from element. if element.text: text += element.text # Process nested formatting tags. for child in element: # Use recursion since nested formatting tags are allowed. text += self._process_lines_mixed_content(child, newlines) # Append text from tail and add formatting end tag. if element.tag == NSMAP % 'tag' and use_endtag: text += u'{/%s}' % element.get(u'name') # Append text from tail. if element.tail: text += element.tail return text def _process_verse_lines(self, lines, version): """ Converts lyrics lines to OpenLP representation. ``lines`` The lines object (lxml.objectify.ObjectifiedElement). """ text = u'' # Convert lxml.objectify to lxml.etree representation. lines = etree.tostring(lines) element = etree.XML(lines) # OpenLyrics 0.8 uses <br/> for new lines. # Append text from "lines" element to verse text. if version > '0.7': text = self._process_lines_mixed_content(element) # OpenLyrics version <= 0.7 contais <line> elements to represent lines. # First child element is tested. else: # Loop over the "line" elements removing comments and chords. for line in element: # Skip comment lines. if line.tag == NSMAP % u'comment': continue if text: text += u'\n' text += self._process_lines_mixed_content(line, newlines=False) return text def _process_lyrics(self, properties, song_xml, song_obj): """ Processes the verses and search_lyrics for the song. ``properties`` The properties object (lxml.objectify.ObjectifiedElement). ``song_xml`` The objectified song (lxml.objectify.ObjectifiedElement). ``song_obj`` The song object. """ sxml = SongXML() verses = {} verse_def_list = [] try: lyrics = song_xml.lyrics except AttributeError: raise OpenLyricsError(OpenLyricsError.LyricsError, '<lyrics> tag is missing.', translate('OpenLP.OpenLyricsImportError', '<lyrics> tag is missing.')) try: verse_list = lyrics.verse except AttributeError: raise OpenLyricsError(OpenLyricsError.VerseError, '<verse> tag is missing.', translate('OpenLP.OpenLyricsImportError', '<verse> tag is missing.')) # Loop over the "verse" elements. for verse in verse_list: text = u'' # Loop over the "lines" elements. for lines in verse.lines: if text: text += u'\n' # Append text from "lines" element to verse text. text += self._process_verse_lines(lines, version=song_xml.get(u'version')) # Add an optional split to the verse text. if lines.get(u'break') is not None: text += u'\n[---]' verse_def = verse.get(u'name', u' ').lower() verse_tag, verse_number, verse_part = OpenLyrics.VERSE_TAG_SPLITTER.search(verse_def).groups() if verse_tag not in VerseType.Tags: verse_tag = VerseType.Tags[VerseType.Other] # OpenLyrics allows e. g. "c", but we need "c1". However, this does # not correct the verse order. if not verse_number: verse_number = u'1' lang = verse.get(u'lang') translit = verse.get(u'translit') # In OpenLP 1.9.6 we used v1a, v1b ... to represent visual slide # breaks. In OpenLyrics 0.7 an attribute has been added. if song_xml.get(u'modifiedIn') in (u'1.9.6', u'OpenLP 1.9.6') and \ song_xml.get(u'version') == u'0.7' and (verse_tag, verse_number, lang, translit) in verses: verses[(verse_tag, verse_number, lang, translit, None)] += u'\n[---]\n' + text # Merge v1a, v1b, .... to v1. elif (verse_tag, verse_number, lang, translit, verse_part) in verses: verses[(verse_tag, verse_number, lang, translit, verse_part)] += u'\n' + text else: verses[(verse_tag, verse_number, lang, translit, verse_part)] = text verse_def_list.append((verse_tag, verse_number, lang, translit, verse_part)) # We have to use a list to keep the order, as dicts are not sorted. for verse in verse_def_list: sxml.add_verse_to_lyrics(verse[0], verse[1], verses[verse], verse[2]) song_obj.lyrics = unicode(sxml.extract_xml(), u'utf-8') # Process verse order if hasattr(properties, u'verseOrder'): song_obj.verse_order = self._text(properties.verseOrder) def _process_songbooks(self, properties, song): """ Adds the song book and song number specified in the XML to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ song.song_book_id = None song.song_number = u'' if hasattr(properties, u'songbooks'): for songbook in properties.songbooks.songbook: book_name = songbook.get(u'name', u'') if book_name: book = self.manager.get_object_filtered(Book, Book.name == book_name) if book is None: # We need to create a book, because it does not exist. book = Book.populate(name=book_name, publisher=u'') self.manager.save_object(book) song.song_book_id = book.id song.song_number = songbook.get(u'entry', u'') # We only support one song book, so take the first one. break def _process_titles(self, properties, song): """ Processes the titles specified in the song's XML. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ for title in properties.titles.title: if not song.title: song.title = self._text(title) song.alternate_title = u'' else: song.alternate_title = self._text(title) def _process_topics(self, properties, song): """ Adds the topics to the song. ``properties`` The property object (lxml.objectify.ObjectifiedElement). ``song`` The song object. """ if hasattr(properties, u'themes'): for topic_text in properties.themes.theme: topic_text = self._text(topic_text) if topic_text: topic = self.manager.get_object_filtered(Topic, Topic.name == topic_text) if topic is None: # We need to create a topic, because it does not exist. topic = Topic.populate(name=topic_text) self.manager.save_object(topic) song.topics.append(topic) def _dump_xml(self, xml): """ Debugging aid to dump XML so that we can see what we have. """ return etree.tostring(xml, encoding=u'UTF-8', xml_declaration=True, pretty_print=True) class OpenLyricsError(Exception): # XML tree is missing the lyrics tag LyricsError = 1 # XML tree has no verse tags VerseError = 2 def __init__(self, type, log_message, display_message): Exception.__init__(self) self.type = type self.log_message = log_message self.display_message = display_message
marmyshev/transitions
openlp/plugins/songs/lib/xml.py
Python
gpl-2.0
34,187
[ "Brian" ]
fdd5586746e20204289b6125f4cbff41d6c8045060bfa94c1c56b0b9bf4ea8bc
# -*- coding: utf-8 -*- """ equip.bytecode.utils ~~~~~~~~~~~~~~~~~~~~ Utilities for bytecode interaction. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ import opcode import types import dis from ..utils.log import logger def iter_decl(decl): """ Yield declarations that are nested under the given declaration. :param decl: The root ``Declaration`` to visit. """ try: worklist = [decl] while worklist: decl = worklist.pop(0) yield decl children = decl.children for child in children: worklist.insert(0, child) except StopIteration, ex: pass # Look into the main_co if we get orignal_co, if so we replace it with new_co def update_nested_code_object(main_co, original_co, new_co): if not main_co: return logger.debug("Looking in main %s, replace by %s" % (original_co, new_co)) main_co_consts = main_co.co_consts co_index = -1 for co_const in main_co_consts: if not isinstance(co_const, types.CodeType): continue if co_const == original_co: co_index = main_co_consts.index(co_const) break if co_index < 0: logger.debug("Cannot find %s in main_co: %s" % (original_co, main_co_consts)) return main_co new_co_consts = main_co.co_consts[:co_index] + (new_co,) + main_co.co_consts[co_index + 1:] main_co = types.CodeType(main_co.co_argcount, main_co.co_nlocals, main_co.co_stacksize, main_co.co_flags, main_co.co_code, new_co_consts, main_co.co_names, main_co.co_varnames, main_co.co_filename, main_co.co_name, main_co.co_firstlineno, main_co.co_lnotab, main_co.co_freevars, main_co.co_cellvars) logger.debug("Created new CO: %s" % main_co) return main_co def show_bytecode(bytecode, start=0, end=2**32): from ..analysis.python.effects import get_stack_effect if bytecode is None: return '' buffer = [] j = start end = min(end, len(bytecode) - 1) while j <= end: index, lineno, op, arg, _, co = bytecode[j] uid = hex(id(co))[-5:] pop_push_str = '' try: pop, push = get_stack_effect(op, arg) pop_push_str = ' (-%d +%d) ' % (pop, push) except ValueError, ex: pop_push_str = ' ' if op >= opcode.HAVE_ARGUMENT: rts = repr(arg) if len(rts) > 40: rts = rts[:40] + '[...]' jump_target = '' if op in opcode.hasjrel or op in opcode.hasjabs: jump_address = arg if op in opcode.hasjabs else index + arg + 3 jump_target = ' -------------> (%4d)' % jump_address buffer.append("[%5s]%4d(%4d) %20s(%3d)%s (%s)%s" % (uid, lineno, index, opcode.opname[op], op, pop_push_str, rts, jump_target)) else: buffer.append("[%5s]%4d(%4d) %20s(%3d)%s" % (uid, lineno, index, opcode.opname[op], op, pop_push_str)) j += 1 return '\n'.join(buffer) CO_FIELDS = ('co_argcount', 'co_cellvars', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames') def get_debug_code_object_info(code_object): buffer = [] for field in CO_FIELDS: field_name = field.replace('co_', '') val = getattr(code_object, field) buffer.append("%s := %s" % (field_name, val)) return '\n'.join(buffer) def get_debug_code_object_dict(code_object): dct = {} for field in CO_FIELDS: val = getattr(code_object, field) dct[field] = val return dct
neuroo/equip
equip/bytecode/utils.py
Python
apache-2.0
3,679
[ "VisIt" ]
147f72215614d86f6d4f2ec9037ca75a1e9ab09e82f443b219c31265daf95339
categorylookup = {'1': 'Planets', '1.1': 'Planets (Type)', '1.1.1': 'Terrestrial Planets', '1.1.2': 'Gas Giant Planets', '1.2': 'Planets (Feature)', '1.2.1': 'Planet Surfaces', '1.2.1.1': 'Mountains', '1.2.1.2': 'Canyons', '1.2.1.3': 'Volcanic Surfaces', '1.2.1.4': 'Surface Impacts', '1.2.1.5': 'Surface Erosion', '1.2.1.6': 'Surface Liquid', '1.2.1.7': 'Surface Ice', '1.2.2': 'Planetary Atmospheres', '1.2.2.1': 'Atmospheric Clouds', '1.2.2.2': 'Storms', '1.2.2.3': 'Atmospheric Belts', '1.2.2.4': 'Aurorae', '1.3': 'Planets (Special Cases)', '1.3.1': 'Transiting Planets', '1.3.2': 'Hot Jupiters', '1.3.3': 'Pulsar Planets', '1.4': 'Satellites', '1.4.1': 'Satellites (Feature)', '1.4.1.1': 'Satellite Surfaces', '1.4.1.1.1': 'Mountain', '1.4.1.1.2': 'Canyon', '1.4.1.1.3': 'Volcanic', '1.4.1.1.4': 'Impact', '1.4.1.1.5': 'Erosion', '1.4.1.1.6': 'Liquid', '1.4.1.1.7': 'Ice', '1.4.1.2': 'Satellite Atmospheres', '2': 'Interplanetary Bodies', '2.1': 'Dwarf Planets', '2.2': 'Comets', '2.2.1': 'Comet Nuclei', '2.2.2': 'Comet Coma', '2.2.3': 'Comet Tails', '2.2.3.1': 'Comets (Dust)', '2.2.3.2': 'Comets (Gas)', '2.3': 'Asteroids', '2.4': 'Meteoroids', '3': 'Stars', '3.1': 'Stars (Evolutionary Stage)', '3.1.1': 'Protostar', '3.1.2': 'Young Stellar Object', '3.1.3': 'Main Sequence Star', '3.1.4': 'Red Giants', '3.1.5': 'Red Supergiants', '3.1.6': 'Blue Supergiants', '3.1.7': 'White Dwarf Stars', '3.1.8': 'Supernovae', '3.1.9': 'Neutron Stars', '3.1.9.1': 'Pulsars', '3.1.9.2': 'Magnetars', '3.1.10': 'Black Holes', '3.2': 'Stars (Type)', '3.2.1': 'Variable Stars', '3.2.1.1': 'Pulsating Stars', '3.2.1.2': 'Irregular Stars', '3.2.1.3': 'Eclipsing Stars', '3.2.1.4': 'Flare Stars', '3.2.1.5': 'Novae', '3.2.1.6': 'X-Ray Binaries (Star)', '3.3': 'Stars with Spectral Types', '3.3.1': 'O Stars', '3.3.2': 'B Stars', '3.3.3': 'A Stars', '3.3.4': 'F Stars', '3.3.5': 'G Stars', '3.3.6': 'K Stars', '3.3.7': 'M Stars', '3.3.8': 'L Stars', '3.3.9': 'T Stars', '3.4': 'Stellar Populations', '3.4.1': 'Population I Stars', '3.4.2': 'Population II Stars', '3.4.3': 'Population III Stars', '3.5': 'Stellar feature', '3.5.1': 'Photosphere', '3.5.1.1': 'Granulation', '3.5.1.2': 'Sunspot', '3.5.2': 'Chromosphere', '3.5.2.1': 'Flare', '3.5.2.2': 'Facula', '3.5.3': 'Corona', '3.5.3.1': 'Prominence', '3.6': 'Group of Stars', '3.6.1': 'Binary Stars', '3.6.2': 'Triple Stars', '3.6.3': 'Multiple Stars', '3.6.4': 'Clusters of Stars', '3.6.4.1': 'Open Clusters', '3.6.4.2': 'Globular Clusters', '3.7': 'Circumstellar Material', '3.7.1': 'Planetary Systems', '3.7.2': 'Disks', '3.7.2.1': 'Protoplanetary Disks', '3.7.2.2': 'Accretion Disks', '3.7.2.3': 'Debris Disks', '3.7.3': 'Outflows', '3.7.3.1': 'Solar Winds', '3.7.3.2': 'Coronal Mass Ejection', '4': 'Nebulae', '4.1': 'Nebulae (Type)', '4.1.1': 'Interstellar Medium', '4.1.2': 'Star Formation', '4.1.3': 'Planetary Nebulae', '4.1.4': 'Supernova Remnants', '4.1.5': 'Jets', '4.2': 'Nebulae (Appearance)', '4.2.1': 'Emission Nebulae', '4.2.1.1': 'H II Regions', '4.2.2': 'Reflection Nebulae', '4.2.2.1': 'Light Echo', '4.2.3': 'Dark Nebulae', '4.2.3.1': 'Molecular Clouds', '4.2.3.2': 'Bok Globules', '4.2.3.3': 'Proplyds', '5': 'Galaxies', '5.1': 'Galaxies (Type)', '5.1.1': 'Spiral Galaxies', '5.1.2': 'Barred Galaxies', '5.1.3': 'Lenticular Galaxies', '5.1.4': 'Elliptical Galaxies', '5.1.5': 'Ring Galaxies', '5.1.6': 'Irregular Galaxies', '5.1.7': 'Interacting Galaxies', '5.2': 'Galaxies (Size)', '5.2.1': 'Giant Galaxies', '5.2.2': 'Dwarf Galaxies', '5.3': 'Galaxies (Activity)', '5.3.1': 'Galaxies with normal activity', '5.3.2': 'AGN', '5.3.2.1': 'Quasars', '5.3.2.2': 'Seyfert Galaxies', '5.3.2.3': 'Blazars', '5.3.2.4': 'Liner Galaxies', '5.3.3': 'Starburst Galaxies', '5.3.4': 'Ultraluminous Galaxies', '5.4': 'Galaxies (Component)', '5.4.1': 'Bulges', '5.4.2': 'Bars', '5.4.3': 'Disks', '5.4.4': 'Halos', '5.4.5': 'Rings', '5.4.6': 'Central Black Holes', '5.4.7': 'Spiral Arms', '5.4.8': 'Dust Lanes', '5.4.9': 'Center Cores', '5.5': 'Galaxies (Grouping)', '5.5.1': 'Pair of Galaxies', '5.5.2': 'Multiple Galaxies', '5.5.3': 'Galaxy Clusters', '5.5.4': 'Galaxy Superclusters', '6': 'Cosmology', '6.1': 'Cosmology (Morphology)', '6.1.1': 'Deep Field', '6.1.2': 'Large-scale Structure', '6.1.3': 'Cosmic Background', '6.2': 'Cosmology (Phenomenon)', '6.2.2': 'Gamma Ray Burst', '6.2.3': 'Dark Matter', '7': 'Sky Phenomenon', '7.1': 'Night Sky', '7.1.1': 'Constellations', '7.1.2': 'Asterisms', '7.1.3': 'Milky Way', '7.1.4': 'Trails', '7.1.4.1': 'Meteor Trails', '7.1.4.2': 'Star Trails', '7.1.4.3': 'Satellite Trails', '7.1.5': 'Zodiacal Light', '7.1.5.1': 'Gegenschein', '7.1.5.2': 'Night glow', } categories = [ {'link': "planets", 'name': 'Planets', 'avm': 1}, {'link': "interplanetarybodies", 'name': 'Interplanetary Bodies', 'avm': 2}, {'link': "stars", 'name': 'Stars', 'avm': 3}, {'link': "nebulae", 'name': 'Nebulae', 'avm': 4}, {'link': "galaxies", 'name': 'Galaxies', 'avm': 5}, {'link': "cosmology", 'name': 'Cosmology', 'avm': 6}, {'link': "sky", 'name': 'Sky Phenomenon', 'avm': 7}]
LCOGT/observations
app/images/lookups.py
Python
gpl-3.0
8,256
[ "Galaxy" ]
be8fa64efc5dd13222c9cf2b747588f72da850dd0d1d2de9b665687bdb1c17ee
from .fgir import * from .error import * # Optimization pass interfaces class Optimization(object): def visit(self, obj): pass class FlowgraphOptimization(Optimization): '''Called on each flowgraph in a FGIR. May modify the flowgraph by adding or removing nodes (return a new Flowgraph). If you modify nodes, make sure inputs, outputs, and variables are all updated. May NOT add or remove flowgraphs.''' pass class TopologicalFlowgraphOptimization(Optimization): '''Called on each flowgraph in a FGIR, in dependent order. Components which are used by other components will be called first.''' pass class NodeOptimization(Optimization): '''Called on each node in a FGIR. May modify the node (return a new Node object, and it will be assigned). May NOT remove or add nodes (use a component pass).''' pass class TopologicalNodeOptimization(NodeOptimization): pass # Optimization pass implementations class PrintIR(TopologicalNodeOptimization): 'A simple "optimization" pass which can be used to debug topological sorting' def visit(self, node): print(str(node)) class AssignmentEllision(FlowgraphOptimization): '''Eliminates all assignment nodes. Assignment nodes are useful for the programmer to reuse the output of an expression multiple times, and the lowering transformation generates explicit flowgraph nodes for these expressions. However, they are not necessary for execution, as they simply forward their value. This removes them and connects their pre- and post-dependencies.''' def visit(self, flowgraph): nodes = flowgraph.nodes nodestoremove = [] for n in nodes: if nodes[n].type == FGNodeType.assignment: inputs = nodes[n].inputs[0] for varname, varnode in flowgraph.variables.items(): if varnode == n: flowgraph.variables[varname] = inputs for nf in nodes: if (len(nodes[nf].inputs) > 0) and (n in nodes[nf].inputs): nodes[nf].inputs.remove(n) nodes[nf].inputs.append(inputs) nodestoremove.append(n) for n in nodestoremove: del nodes[n] return flowgraph class DeadCodeElimination(FlowgraphOptimization): '''Eliminates unreachable expression statements. Statements which never affect any output are effectively useless, and we call these "dead code" blocks. This optimization removes any expressions which can be shown not to affect the output. NOTE: input statements *cannot* safely be removed, since doing so would change the call signature of the component. For example, it might seem that the input x could be removed: { component1 (input x y) (output y) } but imagine this component1 was in a file alongside this one: { component2 (input a b) (:= c (component1 a b)) (output c) } By removing x from component1, it could no longer accept two arguments. So in this instance, component1 will end up unmodified after DCE.''' def visit(self, flowgraph): # TODO: implement this outputs = flowgraph.outputs inputs = flowgraph.inputs keep_vars = [] keep_ids = [] lose_vars = [] lose_ids = [] for inpt in inputs: keep_ids.append(inpt) for output in outputs: keep_ids.append(output) self.search(flowgraph,output,keep_ids) for iden in keep_ids: var = [key for key, value in flowgraph.variables.items() if value == iden] if var: var = var[0] keep_vars.append(var) for var in flowgraph.variables: if var not in keep_vars: lose_vars.append(var) for var in lose_vars: del flowgraph.variables[var] for iden in flowgraph.nodes: if iden not in keep_ids: lose_ids.append(iden) for iden in lose_ids: del flowgraph.nodes[iden] return flowgraph def search(self,flowgraph,nodeid,keep_ids): node = flowgraph.nodes[nodeid] for nodeid2 in node.inputs: keep_ids.append(nodeid2) self.search(flowgraph,nodeid2,keep_ids) class InlineComponents(TopologicalFlowgraphOptimization): '''Replaces every component invocation with a copy of that component's flowgraph. Topological order guarantees that we inline components before they are invoked.''' def __init__(self): self.component_cache = {} def visit(self, flowgraph): for (cnode_id, cnode) in [(nid,n) for (nid,n) in flowgraph.nodes.items() if n.type==FGNodeType.component]: target = self.component_cache[cnode.ref] # Add a copy of every node in target flowgraph id_map = {} # maps node id's in the target to node id's in our flowgraph for tnode in target.nodes.values(): if tnode.type==FGNodeType.input or tnode.type==FGNodeType.output: newtype = FGNodeType.forward else: newtype = tnode.type n = flowgraph.new_node(newtype, ref=tnode.ref) id_map[tnode.nodeid] = n.nodeid # Connect all copies together for tid,tnode in target.nodes.items(): flowgraph.nodes[id_map[tid]].inputs = [id_map[i] for i in tnode.inputs] # Link inputs of cnode to inputs of target flowgraph for cnode_input,targ_input in zip(cnode.inputs, target.inputs): flowgraph.nodes[id_map[targ_input]].inputs = [cnode_input] # Link output of target flowgraph to outputs of cnode for oid,onode in flowgraph.nodes.items(): if cnode_id in onode.inputs: onode.inputs[onode.inputs.index(cnode_id)] = id_map[target.outputs[0]] # Remove all other references to cnode in flowgraph del flowgraph.nodes[cnode_id] victims = [s for s,nid in flowgraph.variables.items() if nid==cnode_id] for v in victims: del flowgraph.variables[v] self.component_cache[flowgraph.name] = flowgraph return flowgraph
Planet-Nine/cs207project
pype/optimize.py
Python
mit
5,807
[ "VisIt" ]
57e93eceb9d7fad0f54914e1edacbb7bc418aa10f8c054f7fea73d2a298dca30
######################################################################## # File: FTSManagerHandler.py # Author: Krzysztof.Ciba@NOSPAMgmail.com # Date: 2013/04/08 14:24:08 ######################################################################## """ :mod: FTSManagerHandler .. module: FTSManagerHandler :synopsis: handler for FTSDB using DISET .. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com Service handler for FTSDB using DISET """ __RCSID__ = "$Id$" # # # @file FTSManagerHandler.py # @author Krzysztof.Ciba@NOSPAMgmail.com # @date 2013/04/08 14:24:30 # @brief Definition of FTSManagerHandler class. # # imports from types import DictType, LongType, ListType, IntType, StringTypes, NoneType # # from DIRAC from DIRAC import S_OK, S_ERROR, gLogger from DIRAC.Core.DISET.RequestHandler import RequestHandler from DIRAC.ConfigurationSystem.Client.PathFinder import getServiceSection from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler # # from DMS from DIRAC.DataManagementSystem.Client.FTSJob import FTSJob from DIRAC.DataManagementSystem.Client.FTSFile import FTSFile # # for FTS scheduling from DIRAC.DataManagementSystem.private.FTSPlacement import FTSPlacement # # for FTS objects validation from DIRAC.DataManagementSystem.private.FTSValidator import FTSValidator # # FTS DB from DIRAC.DataManagementSystem.DB.FTSDB import FTSDB # # for proxy from DIRAC.Core.Utilities.Shifter import setupShifterProxyInEnv ######################################################################## class FTSManagerHandler( RequestHandler ): """ .. class:: FTSManagerHandler """ ftsDB = None ftsValidator = None ftsPlacement = None @classmethod def initializeHandler( cls, serviceInfoDict ): """ initialize handler """ try: cls.ftsDB = FTSDB() except RuntimeError, error: gLogger.exception( error ) return S_ERROR( error ) cls.ftsValidator = FTSValidator() # # create tables for empty db getTables = cls.ftsDB.getTables() if not getTables['OK']: gLogger.error( getTables['Message'] ) return getTables getTables = getTables['Value'] toCreate = [ tab for tab in cls.ftsDB.getTableMeta().keys() if tab not in getTables ] if toCreate: createTables = cls.ftsDB.createTables( toCreate ) if not createTables['OK']: gLogger.error( createTables['Message'] ) return createTables # # always re-create views createViews = cls.ftsDB.createViews( True ) if not createViews['OK']: return createViews # # connect connect = cls.ftsDB._connect() if not connect['OK']: gLogger.error( connect['Message'] ) return connect # # get ftsPlacement cls.ftsPlacement = cls.getFTSPlacement() # # put DataManager proxy to env dmProxy = cls.refreshProxy() if not dmProxy['OK']: return dmProxy # # every 10 minutes update RW access in FTSGraph gThreadScheduler.addPeriodicTask( 600, cls.refreshFTSPlacement ) # # every 6 hours refresh DataManager proxy gThreadScheduler.addPeriodicTask( 21600, cls.refreshProxy ) return S_OK() # @classmethod # def getFtsStrategy( self ): # """ fts strategy getter """ # csPath = getServiceSection( "DataManagement/FTSManager" ) # csPath = "%s/%s" % ( csPath, "FTSStrategy" ) # # ftsHistory = self.ftsDB.getFTSHistory() # if not ftsHistory['OK']: # gLogger.warn( "unable to get FTSHistory for FTSStrategy: %s" % ftsHistory['Message'] ) # ftsHistory['Value'] = [] # ftsHistory = ftsHistory['Value'] # # return FTSStrategy( csPath, None, ftsHistory ) @classmethod def getFTSPlacement( cls ): """ fts placement getter """ ftsHistory = cls.ftsDB.getFTSHistory() if not ftsHistory['OK']: gLogger.warn( "unable to get FTSHistory for FTSPlacement: %s" % ftsHistory['Message'] ) ftsHistory['Value'] = [] ftsHistory = ftsHistory['Value'] return FTSPlacement( ftsHistoryViews = ftsHistory ) @staticmethod def refreshProxy(): """ setup DataManager shifter proxy in env """ gLogger.info( "refreshProxy: getting proxy for DataManager..." ) proxy = setupShifterProxyInEnv( "DataManager" ) if not proxy['OK']: gLogger.error( "refreshProxy: %s" % proxy['Message'] ) return proxy @classmethod def refreshFTSPlacement( cls ): """ Refresh the FTSPlacement """ ftsHistory = cls.ftsDB.getFTSHistory() if not ftsHistory['OK']: gLogger.warn( "unable to get FTSHistory for FTSPlacement: %s" % ftsHistory['Message'] ) ftsHistory['Value'] = [] ftsHistory = ftsHistory['Value'] return cls.ftsPlacement.refresh( ftsHistoryViews = ftsHistory ) types_getReplicationTree = [ListType, ListType, ( IntType, LongType )] def export_getReplicationTree( self, sourceSEs, targetSEs, size ): """ return a replication tree with an up-to-date replication strategy """ return self.ftsPlacement.getReplicationTree( sourceSEs, targetSEs, size ) types_setFTSFilesWaiting = [ ( IntType, LongType ), StringTypes, ( NoneType, ListType ) ] def export_setFTSFilesWaiting( self, operationID, sourceSE, opFileIDList ): """ update states for waiting replications """ try: update = self.ftsDB.setFTSFilesWaiting( operationID, sourceSE, opFileIDList ) if not update['OK']: gLogger.error( "setFTSFilesWaiting: %s" % update['Message'] ) return update except Exception, error: gLogger.exception( error ) return S_ERROR( str( error ) ) types_deleteFTSFiles = [ ( IntType, LongType ), ( NoneType, ListType ) ] def export_deleteFTSFiles( self, operationID, opFileIDList = None ): """ cleanup FTSFiles for rescheduling """ opFileIDList = opFileIDList if opFileIDList else [] try: self.log.warn( "Removing %s FTSFiles for OperationID = %s" % ( ( 'All' if not opFileIDList else opFileIDList ), operationID ) ) delete = self.ftsDB.deleteFTSFiles( operationID, opFileIDList ) if not delete['OK']: gLogger.error( "deleteFTSFiles: %s" % delete['Message'] ) return delete except Exception, error: gLogger.exception( error ) return S_ERROR( str( error ) ) types_cleanUpFTSFiles = [ ( IntType, LongType ), ListType ] def export_cleanUpFTSFiles( self, requestID, fileIDs ): """ Clean up FTS files, starting from RequestID """ return self.ftsDB.cleanUpFTSFiles( requestID, fileIDs ) types_putFTSFileList = [ ListType ] def export_putFTSFileList( self, ftsFilesJSONList ): """ put FTS files list """ ftsFiles = [] for ftsFileJSON in ftsFilesJSONList: ftsFiles.append( FTSFile( ftsFileJSON ) ) return self.ftsDB.putFTSFileList( ftsFiles ) types_getFTSFile = [ [IntType, LongType] ] @classmethod def export_getFTSFile( self, ftsFileID ): """ get FTSFile from FTSDB """ try: getFile = self.ftsDB.getFTSFile( ftsFileID ) except Exception, error: gLogger.exception( error ) return S_ERROR( error ) if not getFile['OK']: gLogger.error( "getFTSFile: %s" % getFile['Message'] ) return getFile # # serialize if getFile['Value']: getFile = getFile['Value'].toJSON() if not getFile['OK']: gLogger.error( getFile['Message'] ) return getFile types_peekFTSFile = [ [IntType, LongType] ] @classmethod def export_peekFTSFile( self, ftsFileID ): """ peek FTSFile given FTSFileID """ try: peekFile = self.ftsDB.peekFTSFile( ftsFileID ) except Exception, error: gLogger.exception( error ) return S_ERROR( error ) if not peekFile['OK']: gLogger.error( "peekFTSFile: %s" % peekFile['Message'] ) return peekFile # # serialize if peekFile['Value']: peekFile = peekFile['Value'].toJSON() if not peekFile['OK']: gLogger.error( peekFile['Message'] ) return peekFile types_putFTSJob = [ DictType ] @classmethod def export_putFTSJob( self, ftsJobJSON ): """ put FTSJob (serialized in JSON into FTSDB """ ftsFiles = [] if "FTSFiles" in ftsJobJSON: ftsFiles = ftsJobJSON.get( "FTSFiles", [] ) del ftsJobJSON["FTSFiles"] try: ftsJob = FTSJob( ftsJobJSON ) for ftsFile in ftsFiles: ftsJob.addFile( FTSFile( ftsFile ) ) except Exception, error: gLogger.exception( error ) return S_ERROR( error ) isValid = self.ftsValidator.validate( ftsJob ) if not isValid['OK']: gLogger.error( isValid['Message'] ) return isValid try: put = self.ftsDB.putFTSJob( ftsJob ) if not put['OK']: return S_ERROR( put['Message'] ) return S_OK() except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getFTSJob = [ [IntType, LongType] ] @classmethod def export_getFTSJob( self, ftsJobID ): """ read FTSJob for processing given FTSJobID """ try: getFTSJob = self.ftsDB.getFTSJob( ftsJobID ) if not getFTSJob['OK']: gLogger.error( getFTSJob['Message'] ) return getFTSJob getFTSJob = getFTSJob['Value'] if not getFTSJob: return S_OK() toJSON = getFTSJob.toJSON() if not toJSON['OK']: gLogger.error( toJSON['Message'] ) return toJSON except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_setFTSJobStatus = [[IntType, LongType], StringTypes] @classmethod def export_setFTSJobStatus( self, ftsJobID, status ): """ set FTSJob status """ return self.ftsDB.setFTSJobStatus( ftsJobID, status ) types_deleteFTSJob = [ [IntType, LongType] ] @classmethod def export_deleteFTSJob( self, ftsJobID ): """ delete FTSJob given FTSJobID """ try: deleteFTSJob = self.ftsDB.deleteFTSJob( ftsJobID ) if not deleteFTSJob['OK']: gLogger.error( deleteFTSJob['Message'] ) return deleteFTSJob except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getFTSJobIDs = [ ListType ] @classmethod def export_getFTSJobIDs( self, statusList = None ): """ get FTSJobIDs for a given status list """ statusList = statusList if statusList else list( FTSJob.INITSTATES + FTSJob.TRANSSTATES ) try: getFTSJobIDs = self.ftsDB.getFTSJobIDs( statusList ) if not getFTSJobIDs['OK']: gLogger.error( getFTSJobIDs['Message'] ) return getFTSJobIDs except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getFTSFileIDs = [ ListType ] @classmethod def export_getFTSFileIDs( self, statusList = None ): """ get FTSFilesIDs for a given status list """ statusList = statusList if statusList else [ "Waiting" ] try: getFTSFileIDs = self.ftsDB.getFTSFileIDs( statusList ) if not getFTSFileIDs['OK']: gLogger.error( getFTSFileIDs['Message'] ) return getFTSFileIDs except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getFTSFileList = [ ListType, IntType ] @classmethod def export_getFTSFileList( self, statusList = None, limit = None ): """ get FTSFiles with status in :statusList: """ statusList = statusList if statusList else [ "Waiting" ] limit = limit if limit else 1000 try: getFTSFileList = self.ftsDB.getFTSFileList( statusList, limit ) if not getFTSFileList['OK']: gLogger.error( getFTSFileList[ 'Message' ] ) return getFTSFileList fileList = [] for ftsFile in getFTSFileList['Value']: fileJSON = ftsFile.toJSON() if not fileJSON['OK']: gLogger.error( "getFTSFileList: %s" % fileJSON['Message'] ) return fileJSON fileList.append( fileJSON['Value'] ) return S_OK( fileList ) except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getFTSJobList = [ ListType, IntType ] @classmethod def export_getFTSJobList( self, statusList = None, limit = 500 ): """ get FTSJobs with statuses in :statusList: """ statusList = statusList if statusList else list( FTSJob.INITSTATES + FTSJob.TRANSSTATES ) try: ftsJobs = self.ftsDB.getFTSJobList( statusList, limit ) if not ftsJobs['OK']: gLogger.error( "getFTSJobList: %s" % ftsJobs['Message'] ) return ftsJobs ftsJobsJSON = [] for ftsJob in ftsJobs['Value']: ftsJobJSON = ftsJob.toJSON() if not ftsJobJSON['OK']: gLogger.error( "getFTSJobList: %s" % ftsJobJSON['Message'] ) return ftsJobJSON ftsJobsJSON.append( ftsJobJSON['Value'] ) return S_OK( ftsJobsJSON ) except Exception, error: gLogger.exception( str( error ) ) return S_ERROR( str( error ) ) types_getFTSJobsForRequest = [ ( IntType, LongType ), ListType ] @classmethod def export_getFTSJobsForRequest( self, requestID, statusList = None ): """ get list of FTSJobs for request given its :requestID: and statues in :statusList: :param int requestID: ReqDB.Request.RequestID :param list statusList: FTSJobs status list """ statusList = statusList if statusList else list( FTSJob.INITSTATES + FTSJob.TRANSSTATES ) try: requestID = int( requestID ) ftsJobs = self.ftsDB.getFTSJobsForRequest( requestID, statusList ) if not ftsJobs['OK']: gLogger.error( "getFTSJobsForRequest: %s" % ftsJobs['Message'] ) return ftsJobs ftsJobsList = [] for ftsJob in ftsJobs['Value']: ftsJobJSON = ftsJob.toJSON() if not ftsJobJSON['OK']: gLogger.error( "getFTSJobsForRequest: %s" % ftsJobJSON['Message'] ) return ftsJobJSON ftsJobsList.append( ftsJobJSON['Value'] ) return S_OK( ftsJobsList ) except Exception, error: gLogger.exception( error ) return S_ERROR( str( error ) ) types_getFTSFilesForRequest = [ ( IntType, LongType ), ( NoneType, ListType ) ] @classmethod def export_getFTSFilesForRequest( self, requestID, statusList = None ): """ get list of FTSFiles with statuses in :statusList: given :requestID: """ statusList = statusList if statusList else [ "Waiting" ] try: requestID = int( requestID ) ftsFiles = self.ftsDB.getFTSFilesForRequest( requestID, statusList ) if not ftsFiles['OK']: gLogger.error( "getFTSFilesForRequest: %s" % ftsFiles['Message'] ) return ftsFiles ftsFilesList = [] for ftsFile in ftsFiles['Value']: ftsFileJSON = ftsFile.toJSON() if not ftsFileJSON['OK']: gLogger.error( "getFTSFilesForRequest: %s" % ftsFileJSON['Message'] ) return ftsFileJSON ftsFilesList.append( ftsFileJSON['Value'] ) return S_OK( ftsFilesList ) except Exception, error: gLogger.exception( str( error ) ) return S_ERROR( str( error ) ) types_getAllFTSFilesForRequest = [ ( IntType, LongType ) ] @classmethod def export_getAllFTSFilesForRequest( self, requestID ): """ get list of FTSFiles with statuses in :statusList: given :requestID: """ try: requestID = int( requestID ) ftsFiles = self.ftsDB.getAllFTSFilesForRequest( requestID ) if not ftsFiles['OK']: gLogger.error( "getFTSFilesForRequest: %s" % ftsFiles['Message'] ) return ftsFiles ftsFilesList = [] for ftsFile in ftsFiles['Value']: ftsFileJSON = ftsFile.toJSON() if not ftsFileJSON['OK']: gLogger.error( "getFTSFilesForRequest: %s" % ftsFileJSON['Message'] ) return ftsFileJSON ftsFilesList.append( ftsFileJSON['Value'] ) return S_OK( ftsFilesList ) except Exception, error: gLogger.exception( str( error ) ) return S_ERROR( str( error ) ) types_getFTSHistory = [] @classmethod def export_getFTSHistory( self ): """ get last hour FTS history snapshot """ try: ftsHistory = self.ftsDB.getFTSHistory() if not ftsHistory['OK']: gLogger.error( ftsHistory['Message'] ) return ftsHistory ftsHistory = ftsHistory['Value'] history = [] for ftsHistory in ftsHistory: ftsHistoryJSON = ftsHistory.toJSON() if not ftsHistoryJSON['OK']: return ftsHistoryJSON history.append( ftsHistoryJSON['Value'] ) return S_OK( history ) except Exception, error: gLogger.exception( error ) return S_ERROR( error ) types_getDBSummary = [] @classmethod def export_getDBSummary( self ): """ get FTSDB summary """ try: dbSummary = self.ftsDB.getDBSummary() if not dbSummary['OK']: gLogger.error( "getDBSummary: %s" % dbSummary['Message'] ) return dbSummary except Exception, error: gLogger.exception( error ) return S_ERROR( str( error ) ) @staticmethod def _ancestorSortKeys( tree, aKey = "Ancestor" ): """ sorting keys of replicationTree by its hopAncestor value replicationTree is a dict ( channelID : { ... }, (...) } :param self: self reference :param dict tree: replication tree to sort :param str aKey: a key in value dict used to sort """ if False in [ bool( aKey in v ) for v in tree.values() ]: return S_ERROR( "ancestorSortKeys: %s key in not present in all values" % aKey ) # # put parents of all parents sortedKeys = [ k for k in tree if aKey in tree[k] and not tree[k][aKey] ] # # get children pairs = dict( [ ( k, v[aKey] ) for k, v in tree.items() if v[aKey] ] ) while pairs: for key, ancestor in dict( pairs ).items(): if key not in sortedKeys and ancestor in sortedKeys: sortedKeys.insert( sortedKeys.index( ancestor ), key ) del pairs[key] # # need to reverse this one, as we're inserting child before its parent sortedKeys.reverse() if sorted( sortedKeys ) != sorted( tree.keys() ): return S_ERROR( "ancestorSortKeys: cannot sort, some keys are missing!" ) return S_OK( sortedKeys )
miloszz/DIRAC
DataManagementSystem/Service/FTSManagerHandler.py
Python
gpl-3.0
18,190
[ "DIRAC" ]
c65d93591470f682b4d9dacba57beb9c3b730de02836d83fa2354abb416ab719
#!/usr/bin/env python ######################################## # to modify the NetCDF files ######################################## #First import the netcdf4 library from netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/ import numpy as np import sys,getopt import math import datetime as DT import netcdftime from netcdftime import utime from datetime import datetime from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange, date2num, num2date from dateutil.relativedelta import relativedelta from numpy import arange import numpy as np import pylab as pl import parser import pandas as pd from pandas import * import os from datetime import timedelta import Scientific.IO.NetCDF as IO import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.ticker as mtick import matplotlib.lines as lines import matplotlib.dates as dates from matplotlib.dates import YEARLY, DateFormatter, rrulewrapper, RRuleLocator, drange from matplotlib.colors import LinearSegmentedColormap import textwrap pl.close('all') #=================================================== get opts input file def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o," "--ofile"): outputfile = arg print 'INputfile:', inputfile print 'Outputfile:', outputfile if __name__ == "__main__": main(sys.argv[1:]) #=================================================== GCMvar='psl' RELYvar='msl' GCMinputf='psl_6hrPlev_HadGEM2-ES_historical_r1i1p1_198412010600-198512010000.nc' #GCMinputf='psl_6hrPlev_HadGEM2-ES_historical_r1i1p1_198412010600-198512010000.standard.nc' RELYinputf='msl_EIN75.198412010000-198512010000.nc.remap.nc.360.nc' #RELYinputf='msl_EIN75.198412010000-198512010000.nc.remap.nc' #=================================================== ########################### units of time #=================================================== #=================================================== to read # Read en existing NetCDF file and create a new one # f is going to be the existing NetCDF file from where we want to import data GCMf=Dataset(GCMinputf,'r+') # r is for read only RELYf=Dataset(RELYinputf,'r') # r is for read only # Extract data from NetCDF file print GCMf.variables.keys() print GCMf.dimensions.keys() GCMvar3D=GCMf.variables[GCMvar][:,:,:] RELYvar3D=RELYf.variables[RELYvar][:,:,:] LATITUDE=len(GCMvar3D[0,:,0]) LONGITUDE=len(GCMvar3D[0,0,:]) TIME=len(GCMvar3D[:,0,0]) TIME2=len(RELYvar3D[:,0,0]) #print Latitude,Longitude,Timesize #=================================================== set up variables to use GCMvar2D=GCMvar3D.reshape(TIME,-1) RELYvar2D=RELYvar3D.reshape(TIME2,-1) # create a 3D variable to hold the Mean bias as GCMvar3D in size. #MeanBias=GCMvar3D # NOTE: this method leading to error: when create the second GCMdf in the loop # (t=2) GCMvar3D changes their value of first month to that of MonthlyMeanBias # really bizarre. So, create it as 3D zeros array and then reshape it MeanBias=np.zeros(TIME*LATITUDE*LONGITUDE).reshape(TIME,LATITUDE,LONGITUDE) print MeanBias.shape #--------------------------------------------------- # to test the reshap is working well or not print '======== 3D :=======' print RELYvar3D print '======== 2D :=======' print RELYvar2D print '======== 2D reshape:=======' RELYvar2DT=RELYvar2D.reshape(TIME2,LATITUDE,LONGITUDE) print RELYvar2DT if (RELYvar3D.all()==RELYvar2DT.all()): print 'OKOKOKOK' #quit() #--------------------------------------------------- #quit() #=================================================== to datetime GCMtime=netcdftime.num2date(GCMf.variables['time'][:],GCMf.variables['time'].units,calendar='360_day') #GCMtime=netcdftime.num2date(GCMf.variables['time'][:],GCMf.variables['time'].units) #print GCMtime[9].year print type(GCMtime) #print [str(i) for i in GCMtime[:]] #GCMindex=[DT.datetime.strptime(t,'%Y-%m-%d %H:%M:%S') for t in [str(i) for i in GCMtime[:]]] #print GCMindex #print DT.datetime.strptime('2002-02-30 4:00:09','%Y-%m-%d %H:%M:%S') # NOTE: this day donot exits in Python #=================================================== to datetime # NOTE: when I use the kew word 'calendar='360_day', it gives # wrong value for ONLY this netcdf file, GCMtime is quite OK. #cdftime = utime(RELYf.variables['time'].units,calendar='360_day') #cdftime = utime(RELYf.variables['time'].units) #RELYtime=[cdftime.num2date(t) for t in RELYf.variables['time'][:]] RELYtime=netcdftime.num2date(RELYf.variables['time'][:],RELYf.variables['time'].units,calendar='360_day') #RELYtime=netcdftime.num2date(RELYf.variables['time'][:],RELYf.variables['time'].units) #print type(RELYtime) #RELYindex=[DT.datetime.strptime(t,'%Y-%m-%d %H:%M:%S') for t in [str(i) for i in RELYtime[:]]] #print type(RELYindex) #d={'gcm':pd.Series(GCMvar2D,index=GCMtime),'rely':pd.Series(RELYvar2D,index=RELYtime)} #ddf=pd.DataFrame(d) # Series should be one dimension #quit() #for j in range(10,len(GCMvar3D[0,:,0])): #=================================================== to DataFrame #GCMdf=pd.DataFrame({'year':[t.year for t in GCMtime], #'month':[t.month for t in GCMtime], #'day':[t.day for t in GCMtime], #'hour':[t.hour for t in GCMtime], #'sdfj':GCMf.variables[GCMvar][:,j,:]}) # NOTE: this method is too time cosuming, about 7 hours to finish this code #GCMdf=pd.DataFrame(GCMf.variables[GCMvar][:,0,0],GCMindex) # NOTE: cannot convert 360_day np.arrary objects read from netcdf # to datetime objects #quit() #--------------------------------------------------- GCMdf=pd.DataFrame(GCMvar2D) GCMdf['year']=[t.year for t in GCMtime] GCMdf['month']=[t.month for t in GCMtime] GCMdf['day']=[t.day for t in GCMtime] GCMdf['hour']=[t.hour for t in GCMtime] #print GCMdf.dtypes #print GCMdf.loc[0:9,['year','month','day','hour']] #print 'GCMdf' #print GCMdf.iloc[0:60,:] #quit() #=================================================== to DataFrame #RELYdf=pd.DataFrame({'year':[t.year for t in RELYtime], #'month':[t.month for t in RELYtime], #'day':[t.day for t in RELYtime], #'hour':[t.hour for t in RELYtime], #RELYvar:RELYf.variables[RELYvar][:,j,:]}) # NOTE: this method is too time cosuming, about 7 hours to finish this code #RELYdf=pd.DataFrame(RELYf.variables[RELYvar][:,0,0],RELYindex) # NOTE: cannot convert 360_day np.arrary objects read from netcdf # to datetime objects RELYdf=pd.DataFrame(RELYvar2D,dtype='float32') RELYdf['year']=[t.year for t in RELYtime] RELYdf['month']=[t.month for t in RELYtime] RELYdf['day']=[t.day for t in RELYtime] RELYdf['hour']=[t.hour for t in RELYtime] #print 'RELYdf' #print RELYdf.iloc[2,:] #print GCMdf.loc[0:9,['year','month','day','hour']] #quit() #=================================================== calculate #print GCMdf.stack(0) #print RELYdf.asfreq('6H',method='pad',calendar='360_day') # NOTE: asfreq and stack are not satisfactory to this task. # for the fromer is because of 360_day calendar. print "---------" ##=================================================== for test calculation #print RELYdf.loc[0] ## get monthly msl value #print RELYdf.loc[0][:] ## get value of psl in the same year & month #print GCMdf[(GCMdf['year'] == RELYdf['year'][0]) & (GCMdf['month'] == RELYdf['month'][0])][:] ##quit() ## values = value #print GCMdf.dtypes #print RELYdf.dtypes #print RELYdf.iloc[0,:] #print RELYdf.iloc[0,0:LONGITUDE*LATITUDE].shape #196 ##quit() #print np.array(GCMdf[(GCMdf['year'] == RELYdf['year'][0]) #& (GCMdf['month'] == RELYdf['month'][0])]) #print np.array(GCMdf[(GCMdf['year'] == RELYdf['year'][0]) #& (GCMdf['month'] == RELYdf['month'][0])])[:,0:LONGITUDE*LATITUDE].shape # 119 ##quit() #--------------------------------------------------- ##print [t for t in np.array(GCMdf[(GCMdf['year'] == RELYdf['year'][0]) ##& (GCMdf['month'] == RELYdf['month'][0])][:])] #print np.array([np.subtract(t,RELYdf.iloc[0,0:LONGITUDE*LATITUDE]) #for t in np.array(GCMdf[(GCMdf['year'] == RELYdf['year'][0]) #& (GCMdf['month'] == RELYdf['month'][0])])[:,0:LONGITUDE*LATITUDE]]) #print np.array([np.subtract(t,RELYdf.iloc[0,0:LONGITUDE*LATITUDE]) #for t in np.array(GCMdf[(GCMdf['year'] == RELYdf['year'][0]) #& (GCMdf['month'] == RELYdf['month'][0])])[:,0:LONGITUDE*LATITUDE]]).shape #--------------------------------------------------- #print RELYdf.iloc[1,:LONGITUDE*LATITUDE] #print GCMdf.iloc[1,:LONGITUDE*LATITUDE] #quit() #=================================================== loop in time series: K=0 for t in RELYdf.index: #for t in [1,2]: #print RELYdf.index MonthlyMeanBias=np.array([np.subtract(x,RELYdf.iloc[t,0:LONGITUDE*LATITUDE]) for x in np.array(GCMdf[ (GCMdf['year'] == RELYdf['year'][t]) & (GCMdf['month'] == RELYdf['month'][t]) & (GCMdf['hour'] == RELYdf['hour'][t]) ])[:,0:LONGITUDE*LATITUDE]]) #--------------------------------------------------- #print "GCMvar3D2:" #print [x for x in GCMvar3D[0:30,:]] # right #print "GCMdf:wrong" #print GCMdf.iloc[0:60,:] # the first month is wrong #print GCMdf.values #--------------------------------------------------- petit test: #print " GCM values in this month =======121" #print np.array([x for x in np.array(GCMdf[ #(GCMdf['year'] == RELYdf['year'][t]) & #(GCMdf['month'] == RELYdf['month'][t]) & #(GCMdf['hour'] == RELYdf['hour'][t]) #])]).shape #print np.array([x for x in np.array(GCMdf[ #(GCMdf['year'] == RELYdf['year'][t]) & #(GCMdf['month'] == RELYdf['month'][t]) & #(GCMdf['hour'] == RELYdf['hour'][t]) #])]).shape #print " GCM values in this month =======212" #GCMvalue= np.array([x for x in np.array(GCMdf[ #(GCMdf['year'] == RELYdf['year'][t]) & #(GCMdf['month'] == RELYdf['month'][t]) & #(GCMdf['hour'] == RELYdf['hour'][t]) #])]) ##])[:,0:LONGITUDE*LATITUDE]]) #print GCMvalue #print GCMvalue.shape #--------------------------------------------------- ##quit() #print "RELY values in this month =======" #print np.array(RELYdf.iloc[t,0:LONGITUDE*LATITUDE]) #print np.array(RELYdf.iloc[t,:]) #print np.array(RELYdf.iloc[t,:]).shape #print "MonthlyMeanBias =======" #print MonthlyMeanBias print MonthlyMeanBias.shape #quit() #--------------------------------------------------- end of petit test: L=len(MonthlyMeanBias[:,0]) MeanBias[K:K+L,:]=MonthlyMeanBias.reshape(L,LATITUDE,LONGITUDE) #print " MeanBias =======" #print MeanBias[K:K+L,j,:] print " time = "+str(RELYtime[t])+" t= "+str(t)+", L= "+str(L)+", MeanBias len= "+str(len(MeanBias[K:K+L,0,0]))+" k= " +str(K)+", end= "+str(K+L) K=K+L # NOTE:needed to be reseted to zeros #quit() #=================================================== check the calculation #NOTE: this examination is running in time and Lat(j) dimensions. #print " NOTE: examination in Day (in month) and Latitude(j) dimensions." #dateindex1=np.random.randint(0,L/2) #lonindex1=np.random.randint(0,LONGITUDE*LATITUDE/2) #dateindex2=np.random.randint(L/2,L) #lonindex2=np.random.randint(L/2,LONGITUDE*LATITUDE) #print "random Day index = " +str(dateindex1) #print "random lonindex = " +str(lonindex1) #lonindex1=43 #GCMvalue=np.array(GCMdf[ #(GCMdf['year'] == RELYdf['year'][t]) & #(GCMdf['month'] == RELYdf['month'][t]) & #(GCMdf['hour'] == RELYdf['hour'][t]) #])[dateindex1:dateindex2,lonindex1:lonindex2] #])[:,lonindex1:lonindex1+20] #print GCMvalue.shape #MeanBiasValue=np.array([x for x in np.array(MonthlyMeanBias)] #)[:,lonindex1:lonindex1+20] #)[dateind,x1:dateindex2,lonindex1:lonindex2] #print '=============' #print '============= GCM values' #print GCMvalue[:,lonindex1:lonindex1+20] #print '=============' #print '============= MonthlyMeanBias' #print MonthlyMeanBias[:,lonindex1:lonindex1+20] #print '=============' #print '=============' #print "GCM value - MeanBiasValue = "+str(GCMvalue[:,0:LONGITUDE]-MonthlyMeanBias) #print "Defaule RELYvalue = "+str(RELYdf.iloc[t,lonindex1:lonindex1+20]) #for x in np.array(MonthlyMeanBias)[:,:]])[np.random.randint(0,L),np.random.randint(0,LONGITUDE*LATITUDE)] #=================================================== print results print "========================= GCM data:==========================" print GCMvar3D print "========================= Reanalysis Data:==========================" print RELYvar3D print "========================= montly Mean Bias:==========================" print MeanBias print "========================= Corrected GCM data:==========================" #=================================================== check before WRITING: print " GCMvar3D shape = " + str(GCMvar3D.shape) print " MeanBias shape = " + str(MeanBias.shape) #=================================================== Writing GCMf.variables[GCMvar][:,:,:] = MeanBias GCMf.close() RELYf.close() quit()
CopyChat/Plotting
Python/MeanBias2D.py
Python
gpl-3.0
13,619
[ "NetCDF" ]
3510af193bfce6692dc53beaa34d82b64b1c1c32986b32e725bb5052db15f1e6
""" Initialize the EpcAnalyzer object and call specific functions before writing the netCDF file. Only two functions are being called in this example, but the user may look up the list of functions available. """ from ElectronPhononCoupling import EpcAnalyzer # Lists of files used # =================== ddb_fnames = """ Calculations/01-LiF-dynamical/odat_calc_DS5_DDB.nc Calculations/01-LiF-dynamical/odat_calc_DS9_DDB.nc Calculations/01-LiF-dynamical/odat_calc_DS13_DDB.nc """.split() eigq_fnames = """ Calculations/01-LiF-dynamical/odat_calc_DS6_EIG.nc Calculations/01-LiF-dynamical/odat_calc_DS10_EIG.nc Calculations/01-LiF-dynamical/odat_calc_DS14_EIG.nc """.split() eigr2d_fnames = """ Calculations/01-LiF-dynamical/odat_calc_DS7_EIGR2D.nc Calculations/01-LiF-dynamical/odat_calc_DS11_EIGR2D.nc Calculations/01-LiF-dynamical/odat_calc_DS15_EIGR2D.nc """.split() gkk_fnames = """ Calculations/01-LiF-dynamical/odat_calc_DS7_GKK.nc Calculations/01-LiF-dynamical/odat_calc_DS11_GKK.nc Calculations/01-LiF-dynamical/odat_calc_DS15_GKK.nc """.split() eigk_fname = 'Calculations/01-LiF-dynamical/odat_calc_DS3_EIG.nc' # Initialization and computation # ============================== epca = EpcAnalyzer( rootname = 'Out/2-1', # Rootname for the output smearing_eV = 0.10, # Imaginary parameter for broadening. omega_range = [-0.1, 0.1, 0.001], # Frequency range in Ha (min, max, step) temp_range = [0, 1000, 250], # Temperature range (min, max, step) nqpt = 3, # Number of q-points (2x2x2 qpt grid) wtq = [0.125, 0.5, 0.375], # Weights of the q-points. # These can be obtained by running Abinit # with the corresponding k-point grid. eigk_fname = eigk_fname, # All the files needed for eigq_fnames = eigq_fnames, # this calculation. ddb_fnames = ddb_fnames, # gkk_fnames = gkk_fnames, # eigr2d_fnames = eigr2d_fnames, # ) # Compute the temperature-dependent dynamical self-energy. epca.compute_td_self_energy() # Compute the mode-by-mode decomposition of the zero-point renormalization. epca.compute_dynamical_zp_renormalization_modes() # Write the result in a netCDF file. epca.write_netcdf()
abinit/abinit
scripts/post_processing/ElectronPhononCoupling/Examples/2-1-advanced.py
Python
gpl-3.0
2,300
[ "ABINIT", "NetCDF" ]
f527173ff3129a8c00cde266710129dbf45f395274db3e4488a0ecac4373f009
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module implements the Zur and McGill lattice matching algorithm """ from typing import Iterator, List from dataclasses import dataclass from itertools import product import numpy as np from monty.json import MSONable @dataclass class ZSLMatch(MSONable): """ A match from the Zur and McGill Algorithm. The super_lattice vectors are listed as _sl_vectors. These are reduced according to the algorithm in the paper which effectively a rotation in 3D space. Use the match_transformation property to get the appropriate transformation matrix """ film_sl_vectors: List substrate_sl_vectors: List film_vectors: List substrate_vectors: List film_transformation: List substrate_transformation: List @property def match_area(self): """The area of the match between the substrate and film super lattice vectors""" return vec_area(*self.film_sl_vectors) @property def match_transformation(self): """The tranformation matrix to conver the film super lattice vectors to the substrate""" # Generate 3D lattice vectors for film super lattice film_matrix = list(self.film_sl_vectors) film_matrix.append(np.cross(film_matrix[0], film_matrix[1])) # Generate 3D lattice vectors for substrate super lattice # Out of plane substrate super lattice has to be same length as # Film out of plane vector to ensure no extra deformation in that # direction substrate_matrix = list(self.substrate_sl_vectors) temp_sub = np.cross(substrate_matrix[0], substrate_matrix[1]) temp_sub = temp_sub * fast_norm(film_matrix[2]) / fast_norm(temp_sub) substrate_matrix.append(temp_sub) transform_matrix = np.transpose(np.linalg.solve(film_matrix, substrate_matrix)) return transform_matrix class ZSLGenerator(MSONable): """ This class generate matching interface super lattices based on the methodology of lattice vector matching for heterostructural interfaces proposed by Zur and McGill: Journal of Applied Physics 55 (1984), 378 ; doi: 10.1063/1.333084 The process of generating all possible matching super lattices is: 1.) Reduce the surface lattice vectors and calculate area for the surfaces 2.) Generate all super lattice transformations within a maximum allowed area limit that give nearly equal area super-lattices for the two surfaces - generate_sl_transformation_sets 3.) For each superlattice set: 1.) Reduce super lattice vectors 2.) Check length and angle between film and substrate super lattice vectors to determine if the super lattices are the nearly same and therefore coincident - get_equiv_transformations """ def __init__( self, max_area_ratio_tol=0.09, max_area=400, max_length_tol=0.03, max_angle_tol=0.01, bidirectional=False, ): """ Intialize a Zur Super Lattice Generator for a specific film and substrate Args: max_area_ratio_tol(float): Max tolerance on ratio of super-lattices to consider equal max_area(float): max super lattice area to generate in search max_length_tol: maximum length tolerance in checking if two vectors are of nearly the same length max_angle_tol: maximum angle tolerance in checking of two sets of vectors have nearly the same angle between them """ self.max_area_ratio_tol = max_area_ratio_tol self.max_area = max_area self.max_length_tol = max_length_tol self.max_angle_tol = max_angle_tol self.bidirectional = bidirectional def is_same_vectors(self, vec_set1, vec_set2): """ Determine if two sets of vectors are the same within length and angle tolerances Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ if self.bidirectional: return self._bidirectional_same_vectors(vec_set1, vec_set2) return self._unidirectional_is_same_vectors(vec_set1, vec_set2) def _unidirectional_is_same_vectors(self, vec_set1, vec_set2): """ Determine if two sets of vectors are the same within length and angle tolerances Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ if np.absolute(rel_strain(vec_set1[0], vec_set2[0])) > self.max_length_tol: return False if np.absolute(rel_strain(vec_set1[1], vec_set2[1])) > self.max_length_tol: return False if np.absolute(rel_angle(vec_set1, vec_set2)) > self.max_angle_tol: return False return True def _bidirectional_same_vectors(self, vec_set1, vec_set2): """Bidirectional version of above matching constraint check""" return self._unidirectional_is_same_vectors(vec_set1, vec_set2) or self._unidirectional_is_same_vectors( vec_set2, vec_set1 ) def generate_sl_transformation_sets(self, film_area, substrate_area): """ Generates transformation sets for film/substrate pair given the area of the unit cell area for the film and substrate. The transformation sets map the film and substrate unit cells to super lattices with a maximum area Args: film_area(int): the unit cell area for the film substrate_area(int): the unit cell area for the substrate Returns: transformation_sets: a set of transformation_sets defined as: 1.) the transformation matricies for the film to create a super lattice of area i*film area 2.) the tranformation matricies for the substrate to create a super lattice of area j*film area """ transformation_indicies = [ (i, j) for i in range(1, int(self.max_area / film_area)) for j in range(1, int(self.max_area / substrate_area)) if np.absolute(film_area / substrate_area - float(j) / i) < self.max_area_ratio_tol ] + [ (i, j) for i in range(1, int(self.max_area / film_area)) for j in range(1, int(self.max_area / substrate_area)) if np.absolute(substrate_area / film_area - float(i) / j) < self.max_area_ratio_tol ] transformation_indicies = list(set(transformation_indicies)) # Sort sets by the square of the matching area and yield in order # from smallest to largest for i, j in sorted(transformation_indicies, key=lambda x: x[0] * x[1]): yield (gen_sl_transform_matricies(i), gen_sl_transform_matricies(j)) def get_equiv_transformations(self, transformation_sets, film_vectors, substrate_vectors): """ Applies the transformation_sets to the film and substrate vectors to generate super-lattices and checks if they matches. Returns all matching vectors sets. Args: transformation_sets(array): an array of transformation sets: each transformation set is an array with the (i,j) indicating the area multipes of the film and subtrate it corresponds to, an array with all possible transformations for the film area multiple i and another array for the substrate area multiple j. film_vectors(array): film vectors to generate super lattices substrate_vectors(array): substrate vectors to generate super lattices """ for (film_transformations, substrate_transformations) in transformation_sets: # Apply transformations and reduce using Zur reduce methodology films = [reduce_vectors(*np.dot(f, film_vectors)) for f in film_transformations] substrates = [reduce_vectors(*np.dot(s, substrate_vectors)) for s in substrate_transformations] # Check if equivalant super lattices for (f_trans, s_trans), (f, s) in zip( product(film_transformations, substrate_transformations), product(films, substrates), ): if self.is_same_vectors(f, s): yield [f, s, f_trans, s_trans] def __call__(self, film_vectors, substrate_vectors, lowest=False) -> Iterator[ZSLMatch]: """ Runs the ZSL algorithm to generate all possible matching :return: """ film_area = vec_area(*film_vectors) substrate_area = vec_area(*substrate_vectors) # Generate all super lattice comnbinations for a given set of miller # indicies transformation_sets = self.generate_sl_transformation_sets(film_area, substrate_area) # Check each super-lattice pair to see if they match for match in self.get_equiv_transformations(transformation_sets, film_vectors, substrate_vectors): # Yield the match area, the miller indicies, yield ZSLMatch( film_sl_vectors=match[0], substrate_sl_vectors=match[1], film_vectors=film_vectors, substrate_vectors=substrate_vectors, film_transformation=match[2], substrate_transformation=match[3], ) # Just want lowest match per direction if lowest: break def gen_sl_transform_matricies(area_multiple): """ Generates the transformation matricies that convert a set of 2D vectors into a super lattice of integer area multiple as proven in Cassels: Cassels, John William Scott. An introduction to the geometry of numbers. Springer Science & Business Media, 2012. Args: area_multiple(int): integer multiple of unit cell area for super lattice area Returns: matrix_list: transformation matricies to covert unit vectors to super lattice vectors """ return [ np.array(((i, j), (0, area_multiple / i))) for i in get_factors(area_multiple) for j in range(area_multiple // i) ] def rel_strain(vec1, vec2): """ Calculate relative strain between two vectors """ return fast_norm(vec2) / fast_norm(vec1) - 1 def rel_angle(vec_set1, vec_set2): """ Calculate the relative angle between two vector sets Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle(vec_set1[0], vec_set1[1]) - 1 def fast_norm(a): """ Much faster variant of numpy linalg norm """ return np.sqrt(np.dot(a, a)) def vec_angle(a, b): """ Calculate angle between two vectors """ cosang = np.dot(a, b) sinang = fast_norm(np.cross(a, b)) return np.arctan2(sinang, cosang) def vec_area(a, b): """ Area of lattice plane defined by two vectors """ return fast_norm(np.cross(a, b)) def reduce_vectors(a, b): """ Generate independent and unique basis vectors based on the methodology of Zur and McGill """ if np.dot(a, b) < 0: return reduce_vectors(a, -b) if fast_norm(a) > fast_norm(b): return reduce_vectors(b, a) if fast_norm(b) > fast_norm(np.add(b, a)): return reduce_vectors(a, np.add(b, a)) if fast_norm(b) > fast_norm(np.subtract(b, a)): return reduce_vectors(a, np.subtract(b, a)) return [a, b] def get_factors(n): """ Generate all factors of n """ for x in range(1, n + 1): if n % x == 0: yield x
vorwerkc/pymatgen
pymatgen/analysis/interfaces/zsl.py
Python
mit
12,016
[ "pymatgen" ]
956dd45d06c9b07722bc3636e963a230454a7f85f2bbd9963076f626c9478c25
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. from unittest import TestCase from mock import Mock, patch from pyqrllib.pyqrllib import bin2hstr, hstr2bin from qrl.core.misc import logger from qrl.core.AddressState import AddressState from qrl.daemon.walletd import WalletD from qrl.generated import qrlwallet_pb2, qrl_pb2 from qrl.services.WalletAPIService import WalletAPIService from tests.misc.helper import get_alice_xmss, get_bob_xmss, set_qrl_dir, replacement_getTime logger.initialize_default() @patch('qrl.core.misc.ntp.getTime', new=replacement_getTime) class TestWalletAPI(TestCase): def __init__(self, *args, **kwargs): self.passphrase = '你好' self.qaddress = "Q010400ff39df1ba4d1d5b8753e6d04c51c34b95b01fc3650c10ca7b296a18bdc105412c59d0b3b" self.hex_seed = "0104008441d43524996f76236141d16b7b324323abf796e77ad" \ "7c874622a82f5744bb803f9b404d25733d0db82be7ac6f3c4cf" self.mnemonic = "absorb drank lute brick cure evil inept group grey " \ "breed hood reefy eager depict weed image law legacy " \ "jockey calm lover freeze fact lively wide dread spiral " \ "jaguar span rinse salty pulsar violet fare" super(TestWalletAPI, self).__init__(*args, **kwargs) def test_addNewAddress(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.address[0], 'Q') def test_addNewAddressWithSlaves(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.address[0], 'Q') def test_addAddressFromSeed(self): with set_qrl_dir("wallet_ver1"): qaddress = "Q010400ff39df1ba4d1d5b8753e6d04c51c34b95b01fc3650c10ca7b296a18bdc105412c59d0b3b" hex_seed = "0104008441d43524996f76236141d16b7b324323abf796e77ad7c874622a82f5744bb803f9b404d25733d0db82be7ac6f3c4cf" walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddAddressFromSeed(qrlwallet_pb2.AddAddressFromSeedReq(seed=hex_seed), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.address, qaddress) def test_addAddressFromSeed2(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddAddressFromSeed(qrlwallet_pb2.AddAddressFromSeedReq(seed=self.mnemonic), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.address, self.qaddress) def test_listAddresses(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) address = resp.address resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.addresses[0], address) def test_removeAddress(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) address = resp.address resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(len(resp.addresses), 1) resp = service.RemoveAddress(qrlwallet_pb2.RemoveAddressReq(address=address), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(len(resp.addresses), 0) def test_isValidAddress(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) qaddress = "Q010400ff39df1ba4d1d5b8753e6d04c51c34b95b01fc3650c10ca7b296a18bdc105412c59d0b3b" resp = service.IsValidAddress(qrlwallet_pb2.ValidAddressReq(address=qaddress), context=None) self.assertEqual(resp.valid, "True") qaddress = "Q010400ff39df1ba4d1d5b8753e6d04c51c34b95b01fc3650c10ca7b296a18bdc105412c59d0b00" resp = service.IsValidAddress(qrlwallet_pb2.ValidAddressReq(address=qaddress), context=None) self.assertEqual(resp.valid, "False") def test_getRecoverySeeds(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) service.AddAddressFromSeed(qrlwallet_pb2.AddAddressFromSeedReq(seed=self.mnemonic), context=None) resp = service.GetRecoverySeeds(qrlwallet_pb2.GetRecoverySeedsReq(address=self.qaddress), context=None) self.assertEqual(resp.hexseed, self.hex_seed) self.assertEqual(resp.mnemonic, self.mnemonic) def test_getWalletInfo(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.GetWalletInfo(qrlwallet_pb2.GetWalletInfoReq(), context=None) self.assertEqual(resp.version, 1) self.assertEqual(resp.address_count, 0) self.assertFalse(resp.is_encrypted) def test_relayTransferTxn(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) walletd._public_stub.IsSlave = Mock( return_value=qrl_pb2.IsSlaveResp(result=True)) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(next_unused_ots_index=0, unused_ots_index_found=True)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses_to = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) resp = service.RelayTransferTxn(qrlwallet_pb2.RelayTransferTxnReq(addresses_to=qaddresses_to, amounts=amounts, fee=100000000, master_address=None, signer_address=qaddress, ots_index=0), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayTransferTxnBySlave(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) slaves = walletd.get_slave_list(qaddress) addr_state.add_slave_pks_access_type(bytes(hstr2bin(slaves[0][0].pk)), 0) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses_to = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] resp = service.RelayTransferTxnBySlave( qrlwallet_pb2.RelayTransferTxnBySlaveReq(addresses_to=qaddresses_to, amounts=amounts, fee=100000000, master_address=qaddress), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayMessageTxn(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(next_unused_ots_index=0, unused_ots_index_found=True)) resp = service.RelayMessageTxn(qrlwallet_pb2.RelayMessageTxnReq(message=b'Hello QRL!', fee=100000000, master_address=None, signer_address=qaddress, ots_index=0), context=None) self.assertEqual(0, resp.code) self.assertIsNotNone(resp.tx) def test_relayMessageTxnBySlave(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) slaves = walletd.get_slave_list(qaddress) addr_state.add_slave_pks_access_type(bytes(hstr2bin(slaves[0][0].pk)), 0) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) resp = service.RelayMessageTxnBySlave( qrlwallet_pb2.RelayMessageTxnReq(message=b'Hello QRL!', fee=100000000, master_address=qaddress), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayTokenTxn(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) walletd._public_stub.IsSlave = Mock( return_value=qrl_pb2.IsSlaveResp(result=True)) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(next_unused_ots_index=0, unused_ots_index_found=True)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) resp = service.RelayTokenTxn(qrlwallet_pb2.RelayTokenTxnReq(symbol=b'QRL', name=b'Quantum Resistant Ledger', owner=alice_xmss.qaddress, decimals=5, addresses=qaddresses, amounts=amounts, fee=100000000, master_address=None, signer_address=qaddress, ots_index=0), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayTokenTxnBySlave(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) slaves = walletd.get_slave_list(qaddress) addr_state.add_slave_pks_access_type(bytes(hstr2bin(slaves[0][0].pk)), 0) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] resp = service.RelayTokenTxnBySlave( qrlwallet_pb2.RelayTokenTxnBySlaveReq(symbol=b'QRL', name=b'Quantum Resistant Ledger', owner=alice_xmss.qaddress, decimals=5, addresses=qaddresses, amounts=amounts, fee=100000000, master_address=qaddress), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayTransferTokenTxn(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) walletd._public_stub.IsSlave = Mock( return_value=qrl_pb2.IsSlaveResp(result=True)) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(next_unused_ots_index=0, unused_ots_index_found=True)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses_to = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) resp = service.RelayTransferTokenTxn(qrlwallet_pb2.RelayTransferTokenTxnReq(addresses_to=qaddresses_to, amounts=amounts, token_txhash='', fee=100000000, master_address=None, signer_address=qaddress, ots_index=0), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relayTransferTokenTxnBySlave(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) slaves = walletd.get_slave_list(qaddress) addr_state.add_slave_pks_access_type(bytes(hstr2bin(slaves[0][0].pk)), 0) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) alice_xmss = get_alice_xmss(4) bob_xmss = get_bob_xmss(4) qaddresses_to = [alice_xmss.qaddress, bob_xmss.qaddress] amounts = [1000000000, 1000000000] resp = service.RelayTransferTokenTxnBySlave( qrlwallet_pb2.RelayTransferTokenTxnBySlaveReq(addresses_to=qaddresses_to, amounts=amounts, token_txhash='', fee=100000000, master_address=qaddress), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relaySlaveTxn(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) resp = service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) walletd._public_stub.IsSlave = Mock( return_value=qrl_pb2.IsSlaveResp(result=True)) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(next_unused_ots_index=0, unused_ots_index_found=True)) alice_xmss = get_alice_xmss(4) slave_pks = [alice_xmss.pk] access_types = [0] walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) resp = service.RelaySlaveTxn(qrlwallet_pb2.RelaySlaveTxnReq(slave_pks=slave_pks, access_types=access_types, fee=100000000, master_address=None, signer_address=qaddress, ots_index=0), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_relaySlaveTxnBySlave(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() walletd._public_stub.PushTransaction = Mock( return_value=qrl_pb2.PushTransactionResp(error_code=qrl_pb2.PushTransactionResp.SUBMITTED)) service = WalletAPIService(walletd) resp = service.AddNewAddressWithSlaves(qrlwallet_pb2.AddNewAddressWithSlavesReq(), context=None) qaddress = resp.address addr_state = AddressState.get_default(walletd.qaddress_to_address(qaddress)) slaves = walletd.get_slave_list(qaddress) addr_state.add_slave_pks_access_type(bytes(hstr2bin(slaves[0][0].pk)), 0) walletd._public_stub.GetAddressState = Mock( return_value=qrl_pb2.GetAddressStateResp(state=addr_state.pbdata)) alice_xmss = get_alice_xmss(4) slave_pks = [alice_xmss.pk] access_types = [0] resp = service.RelaySlaveTxnBySlave( qrlwallet_pb2.RelaySlaveTxnBySlaveReq(slave_pks=slave_pks, access_types=access_types, fee=100000000, master_address=qaddress), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) def test_encryptWallet(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(), context=None) self.assertEqual(resp.code, 1) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 1) def test_lockWallet(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(len(resp.addresses), 1) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) resp = service.LockWallet(qrlwallet_pb2.LockWalletReq(), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 1) def test_unlockWallet(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(len(resp.addresses), 1) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) resp = service.LockWallet(qrlwallet_pb2.LockWalletReq(), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase="wrong"), context=None) self.assertEqual(resp.code, 1) def test_changePassphrase(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) service.AddNewAddress(qrlwallet_pb2.AddNewAddressReq(), context=None) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(len(resp.addresses), 1) resp = service.EncryptWallet(qrlwallet_pb2.EncryptWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.ListAddresses(qrlwallet_pb2.ListAddressesReq(), context=None) self.assertEqual(resp.code, 0) resp = service.LockWallet(qrlwallet_pb2.LockWalletReq(), context=None) self.assertEqual(resp.code, 0) new_passphrase = "Hello World" resp = service.ChangePassphrase( qrlwallet_pb2.ChangePassphraseReq(oldPassphrase=self.passphrase, newPassphrase=new_passphrase), context=None) self.assertEqual(resp.code, 0) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase=self.passphrase), context=None) self.assertEqual(resp.code, 1) resp = service.UnlockWallet(qrlwallet_pb2.UnlockWalletReq(passphrase=new_passphrase), context=None) self.assertEqual(resp.code, 0) def test_getTransactionsByAddress(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) walletd._public_stub.GetMiniTransactionsByAddress = Mock( return_value=qrl_pb2.GetMiniTransactionsByAddressResp(mini_transactions=[], balance=0)) resp = service.GetTransactionsByAddress( qrlwallet_pb2.TransactionsByAddressReq(address=get_alice_xmss(4).qaddress), context=None) self.assertEqual(resp.code, 0) self.assertEqual(len(resp.mini_transactions), 0) self.assertEqual(resp.balance, 0) def test_getTransaction(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) tx = qrl_pb2.Transaction() tx.fee = 10 tx.transaction_hash = b'1234' tx.message.message_hash = b'hello' pk = '01020016ecb9f39b9f4275d5a49e232346a15ae2fa8c50a2927daeac189b8c5f2d1' \ '8bc4e3983bd564298c49ae2e7fa6e28d4b954d8cd59398f1225b08d6144854aee0e' tx.public_key = bytes(hstr2bin(pk)) walletd._public_stub.GetTransaction = Mock( return_value=qrl_pb2.GetTransactionResp(tx=tx, confirmations=10)) resp = service.GetTransaction(qrlwallet_pb2.TransactionReq(tx_hash=tx.transaction_hash), context=None) self.assertEqual(resp.code, 0) self.assertIsNotNone(resp.tx) self.assertEqual(resp.tx.transaction_hash, bin2hstr(tx.transaction_hash)) self.assertEqual(resp.confirmations, "10") def test_getBalance(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) walletd._public_stub.GetBalance = Mock( return_value=qrl_pb2.GetBalanceResp(balance=1000)) resp = service.GetBalance(qrlwallet_pb2.BalanceReq(address=self.qaddress), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.balance, "1000") def test_getTotalBalance(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) walletd._public_stub.GetTotalBalance = Mock( return_value=qrl_pb2.GetTotalBalanceResp(balance=6000)) resp = service.GetTotalBalance(qrlwallet_pb2.TotalBalanceReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.balance, "6000") def test_getOTS(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) ots_bitfield_by_page = qrl_pb2.OTSBitfieldByPage(ots_bitfield=[b'\x00'] * 10, page_number=1) walletd._public_stub.GetOTS = Mock( return_value=qrl_pb2.GetOTSResp(ots_bitfield_by_page=[ots_bitfield_by_page], next_unused_ots_index=1, unused_ots_index_found=True)) resp = service.GetOTS(qrlwallet_pb2.OTSReq(address=self.qaddress), context=None) self.assertEqual(resp.code, 0) self.assertEqual(len(resp.ots_bitfield_by_page), 1) self.assertEqual(resp.ots_bitfield_by_page[0], ots_bitfield_by_page) self.assertEqual(resp.next_unused_ots_index, 1) def test_getHeight(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) walletd._public_stub.GetHeight = Mock( return_value=qrl_pb2.GetHeightResp(height=1001)) resp = service.GetHeight(qrlwallet_pb2.HeightReq(), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.height, 1001) def test_getBlock(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) block = qrl_pb2.Block() block.header.hash_header = b'001122' block.header.block_number = 1 walletd._public_stub.GetBlock = Mock( return_value=qrl_pb2.GetBlockResp(block=block)) resp = service.GetBlock(qrlwallet_pb2.BlockReq(header_hash=b'001122'), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.block.header.hash_header, bin2hstr(block.header.hash_header)) self.assertEqual(resp.block.header.block_number, block.header.block_number) def test_getBlockByNumber(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) block = qrl_pb2.Block() block.header.hash_header = b'001122' block.header.block_number = 1 walletd._public_stub.GetBlockByNumber = Mock( return_value=qrl_pb2.GetBlockResp(block=block)) resp = service.GetBlockByNumber(qrlwallet_pb2.BlockByNumberReq(block_number=1), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.block.header.hash_header, bin2hstr(block.header.hash_header)) self.assertEqual(resp.block.header.block_number, block.header.block_number) def test_getAddressFromPK(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) pk = '01020016ecb9f39b9f4275d5a49e232346a15ae2fa8c50a2927daeac189b8c5f2d1' \ '8bc4e3983bd564298c49ae2e7fa6e28d4b954d8cd59398f1225b08d6144854aee0e' resp = service.GetAddressFromPK(qrlwallet_pb2.AddressFromPKReq(pk=pk), context=None) self.assertEqual(resp.code, 0) self.assertEqual(resp.address, 'Q010200670246b0026436b717f199e3ec5320ba6ab61d5eddff811ac199a9e9b871d3280178b343') def test_getNodeInfo(self): with set_qrl_dir("wallet_ver1"): walletd = WalletD() service = WalletAPIService(walletd) block_last_hash_str = 'c23f47a10a8c53cc5ded096369255a32c4a218682a961d0ee7db22c500000000' version = "1.0.0" num_connections = 10 num_known_peers = 200 uptime = 10000 block_height = 102345 block_last_hash = bytes(hstr2bin(block_last_hash_str)) network_id = "network id" node_info = qrl_pb2.NodeInfo(version=version, num_connections=num_connections, num_known_peers=num_known_peers, uptime=uptime, block_height=block_height, block_last_hash=block_last_hash, network_id=network_id) walletd._public_stub.GetNodeState = Mock( return_value=qrl_pb2.GetNodeStateResp(info=node_info)) resp = service.GetNodeInfo(qrlwallet_pb2.NodeInfoReq(), context=None) self.assertEqual(resp.version, version) self.assertEqual(resp.num_connections, str(num_connections)) self.assertEqual(resp.num_known_peers, str(num_known_peers)) self.assertEqual(resp.uptime, uptime) self.assertEqual(resp.block_height, block_height) self.assertEqual(resp.block_last_hash, block_last_hash_str) self.assertEqual(resp.network_id, network_id)
theQRL/QRL
tests/services/test_WalletAPIService.py
Python
mit
35,966
[ "Jaguar" ]
25cbc3e5b7dc38898a31c790b8d607c56345d1d71a6ba234e702bba8841467f0
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'CustomValue.supress' db.add_column(u'profiles_customvalue', 'supress', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'CustomValue.supress' db.delete_column(u'profiles_customvalue', 'supress') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 9, 12, 10, 50, 32, 603499)'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 9, 12, 10, 50, 32, 603096)'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'maps.shapefile': { 'Meta': {'object_name': 'ShapeFile'}, 'color': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'geo_key_column': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'geo_meta_key_column': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'geom_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label_column': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'shape_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'zoom_threshold': ('django.db.models.fields.IntegerField', [], {'default': '5'}) }, u'profiles.customvalue': { 'Meta': {'object_name': 'CustomValue'}, 'data_type': ('django.db.models.fields.CharField', [], {'default': "'COUNT'", 'max_length': '30'}), 'display_value': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}), 'supress': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'value_operator': ('django.db.models.fields.CharField', [], {'max_length': "'255'"}) }, u'profiles.datadomain': { 'Meta': {'ordering': "['weight']", 'object_name': 'DataDomain'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicators': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['profiles.Indicator']", 'through': u"orm['profiles.IndicatorDomain']", 'symmetrical': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'subdomain_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'subdomains': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['profiles.DataDomain']", 'symmetrical': 'False', 'blank': 'True'}), 'weight': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}) }, u'profiles.datapoint': { 'Meta': {'unique_together': "(('indicator', 'record', 'time'),)", 'object_name': 'DataPoint'}, 'change_from_time': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'datapoint_as_change_from'", 'null': 'True', 'to': u"orm['profiles.Time']"}), 'change_to_time': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'datapoint_as_change_to'", 'null': 'True', 'to': u"orm['profiles.Time']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}), 'record': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.GeoRecord']"}), 'time': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Time']", 'null': 'True'}) }, u'profiles.datasource': { 'Meta': {'object_name': 'DataSource'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'implementation': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}) }, u'profiles.denominator': { 'Meta': {'object_name': 'Denominator'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'multiplier': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'sort': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}) }, u'profiles.denominatorpart': { 'Meta': {'object_name': 'DenominatorPart'}, 'data': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'data_source': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.DataSource']"}), 'denominator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Denominator']"}), 'formula': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}), 'part': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.IndicatorPart']"}) }, u'profiles.geolevel': { 'Meta': {'object_name': 'GeoLevel'}, 'data_sources': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['profiles.DataSource']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.GeoLevel']", 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'}) }, u'profiles.georecord': { 'Meta': {'unique_together': "(('slug', 'level'), ('level', 'geo_id', 'custom_name', 'owner'))", 'object_name': 'GeoRecord'}, 'components': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'components_rel_+'", 'blank': 'True', 'to': u"orm['profiles.GeoRecord']"}), 'custom_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'geo_id': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'geo_searchable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.GeoLevel']"}), 'mappings': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'mappings_rel_+'", 'blank': 'True', 'to': u"orm['profiles.GeoRecord']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.GeoRecord']", 'null': 'True', 'blank': 'True'}), 'shapefile': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['maps.ShapeFile']", 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}) }, u'profiles.indicator': { 'Meta': {'object_name': 'Indicator'}, 'data_domains': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['profiles.DataDomain']", 'through': u"orm['profiles.IndicatorDomain']", 'symmetrical': 'False'}), 'data_type': ('django.db.models.fields.CharField', [], {'default': "'COUNT'", 'max_length': '30'}), 'display_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'display_distribution': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'display_percent': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_generated_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'levels': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['profiles.GeoLevel']", 'symmetrical': 'False'}), 'limitations': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'long_definition': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'purpose': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'routine_use': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'short_definition': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}), 'source': ('django.db.models.fields.CharField', [], {'default': "'U.S. Census Bureau'", 'max_length': '300', 'blank': 'True'}), 'universe': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}) }, u'profiles.indicatordomain': { 'Meta': {'object_name': 'IndicatorDomain'}, 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.DataDomain']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}) }, u'profiles.indicatorpart': { 'Meta': {'object_name': 'IndicatorPart'}, 'data': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'data_source': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.DataSource']"}), 'formula': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Indicator']"}), 'time': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Time']"}) }, u'profiles.precalculatedvalue': { 'Meta': {'object_name': 'PrecalculatedValue'}, 'data_source': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.DataSource']"}), 'geo_record': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.GeoRecord']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'table': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'value': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, u'profiles.taskstatus': { 'Meta': {'object_name': 'TaskStatus'}, 'error': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 't_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'traceback': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, u'profiles.time': { 'Meta': {'object_name': 'Time'}, 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'sort': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '1'}) }, u'profiles.value': { 'Meta': {'object_name': 'Value'}, 'datapoint': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.DataPoint']"}), 'denominator': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['profiles.Denominator']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'moe': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'number': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'percent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}) } } complete_apps = ['profiles']
ProvidencePlan/Profiles
communityprofiles/profiles/oldmigrations/0054_auto__add_field_customvalue_supress.py
Python
mit
18,259
[ "MOE" ]
57b268a88a83c676b2728be26d0b8393a2ebfbd23d88c28c1c455bbe7c5fa95c
# # Copyright (C) 2013-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import unittest as ut import unittest_decorators as utx import espressomd if espressomd.has_features("VIRTUAL_SITES_RELATIVE"): from espressomd.virtual_sites import VirtualSitesRelative, VirtualSitesOff import numpy as np from tests_common import verify_lj_forces from numpy import random @utx.skipIfMissingFeatures("VIRTUAL_SITES_RELATIVE") class VirtualSites(ut.TestCase): system = espressomd.System(box_l=[1.0, 1.0, 1.0]) system.seed = range(system.cell_system.get_state()["n_nodes"]) np.random.seed(42) def multiply_quaternions(self, a, b): return np.array( (a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2], a[0] * b[2] + a[2] * b[0] + a[3] * b[1] - a[1] * b[3], a[0] * b[3] + a[3] * b[0] + a[1] * b[2] - a[2] * b[1])) def director_from_quaternion(self, quat): return np.array(( 2 * (quat[1] * quat[3] + quat[0] * quat[2]), 2 * (quat[2] * quat[3] - quat[0] * quat[1]), (quat[0] * quat[0] - quat[1] * quat[1] - quat[2] * quat[2] + quat[3] * quat[3]))) def verify_vs(self, vs, verify_velocity=True): """Verify vs position and (if compiled in) velocity.""" self.assertEqual(vs.virtual, True) vs_r = vs.vs_relative # Get related particle rel = self.system.part[vs_r[0]] # Distance d = self.system.distance(rel, vs) v_d = self.system.distance_vec(rel, vs) # Check distance self.assertAlmostEqual(d, vs_r[1], places=6) # check velocity if verify_velocity: self.assertLessEqual(np.linalg.norm( vs.v - rel.v - np.cross(rel.omega_lab, v_d)), 1E-6) # Check position self.assertLess(np.linalg.norm( v_d - vs_r[1] * self.director_from_quaternion( self.multiply_quaternions(rel.quat, vs_r[2]))), 1E-6) def test_aa_method_switching(self): # Virtual sites should be disabled by default self.assertTrue(isinstance(self.system.virtual_sites, VirtualSitesOff)) # Switch implementation self.system.virtual_sites = VirtualSitesRelative(have_velocity=False) self.assertTrue(isinstance( self.system.virtual_sites, VirtualSitesRelative)) self.assertEqual(self.system.virtual_sites.have_velocity, False) def test_vs_quat(self): self.system.part.clear() # First check that quaternion of virtual particle is unchanged if # have_quaterion is false. self.system.virtual_sites = VirtualSitesRelative(have_quaternion=False) self.assertEqual(self.system.virtual_sites.have_quaternion, False) self.system.part.add(id=0, pos=[1, 1, 1], rotation=[1, 1, 1], omega_lab=[1, 1, 1]) self.system.part.add(id=1, pos=[1, 1, 1], rotation=[1, 1, 1]) self.system.part[1].vs_auto_relate_to(0) np.testing.assert_array_equal( np.copy(self.system.part[1].quat), [1, 0, 0, 0]) self.system.integrator.run(1) np.testing.assert_array_equal( np.copy(self.system.part[1].quat), [1, 0, 0, 0]) # Now check that quaternion of the virtual particle gets updated. self.system.virtual_sites = VirtualSitesRelative(have_quaternion=True) self.system.integrator.run(1) self.assertRaises(AssertionError, np.testing.assert_array_equal, np.copy( self.system.part[1].quat), [1, 0, 0, 0]) # co-aligned case self.system.part[1].vs_quat = (1, 0, 0, 0) self.system.integrator.run(1) np.testing.assert_allclose( np.copy(self.system.part[1].director), np.copy(self.system.part[0].director), atol=1E-12) # Construct a quaternion with perpendicular orientation. p0 = np.cos(np.pi / 4.0) p = np.array([0, np.sin(np.pi / 4.0), 0]) q0 = 1.0 q = np.array([0, 0, 0]) r0 = p0 * q0 r = -np.dot(q, p) + np.cross(q, p) + p0 * q + q0 * p self.system.part[1].vs_quat = [r0, r[0], r[1], r[2]] self.system.integrator.run(1) # Check for orthogonality. self.assertAlmostEqual( np.dot(self.system.part[0].director, self.system.part[1].director), 0.0, delta=1E-12) # Check if still true after integration. self.system.integrator.run(1) self.assertAlmostEqual( np.dot(self.system.part[0].director, self.system.part[1].director), 0.0) def test_pos_vel_forces(self): system = self.system system.cell_system.skin = 0.3 system.virtual_sites = VirtualSitesRelative(have_velocity=True) system.box_l = [10, 10, 10] system.part.clear() system.time_step = 0.004 system.part.clear() system.thermostat.turn_off() system.non_bonded_inter[0, 0].lennard_jones.set_params( epsilon=0, sigma=0, cutoff=0, shift=0) # Check setting of min_global_cut system.min_global_cut = 0.23 self.assertEqual(system.min_global_cut, 0.23) # Place central particle + 3 vs system.part.add(rotation=(1, 1, 1), pos=(0.5, 0.5, 0.5), id=1, quat=(1, 0, 0, 0), omega_lab=(1, 2, 3)) pos2 = (0.5, 0.4, 0.5) pos3 = (0.3, 0.5, 0.4) pos4 = (0.5, 0.5, 0.5) cur_id = 2 for pos in pos2, pos3, pos4: system.part.add(rotation=(1, 1, 1), pos=pos, id=cur_id) system.part[cur_id].vs_auto_relate_to(1) # Was the particle made virtual self.assertEqual(system.part[cur_id].virtual, True) # Are vs relative to id and vs_r = system.part[cur_id].vs_relative # id self.assertEqual(vs_r[0], 1) # distance self.assertAlmostEqual(vs_r[1], system.distance( system.part[1], system.part[cur_id]), places=6) cur_id += 1 # Move central particle and Check vs placement system.part[1].pos = (0.22, 0.22, 0.22) # linear and rotation velocity on central particle system.part[1].v = (0.45, 0.14, 0.447) system.part[1].omega_lab = (0.45, 0.14, 0.447) system.integrator.run(0, recalc_forces=True) for i in [2, 3, 4]: self.verify_vs(system.part[i]) # Check if still true, when non-virtual particle has rotated and a # linear motion system.part[1].omega_lab = [-5, 3, 8.4] system.integrator.run(10) for i in [2, 3, 4]: self.verify_vs(system.part[i]) if espressomd.has_features("EXTERNAL_FORCES"): # Test transfer of forces accumulating on virtual sites # to central particle f2 = np.array((3, 4, 5)) f3 = np.array((-4, 5, 6)) # Add forces to vs system.part[2].ext_force = f2 system.part[3].ext_force = f3 system.integrator.run(0) # get force/torques on non-vs f = system.part[1].f t = system.part[1].torque_lab # Expected force = sum of the forces on the vs self.assertLess(np.linalg.norm(f - f2 - f3), 1E-6) # Expected torque # Radial components of forces on a rigid body add to the torque t_exp = np.cross(system.distance_vec( system.part[1], system.part[2]), f2) t_exp += np.cross(system.distance_vec( system.part[1], system.part[3]), f3) # Check self.assertLessEqual(np.linalg.norm(t_exp - t), 1E-6) # Check virtual sites without velocity system.virtual_sites.have_velocity = False v2 = system.part[2].v system.part[1].v = 17, -13.5, 2 system.integrator.run(0, recalc_forces=True) self.assertLess(np.linalg.norm(v2 - system.part[2].v), 1E-6) def run_test_lj(self): """This fills the system with vs-based dumbells, adds a lj potential, integrates and verifies forces. This is to make sure that no pairs get lost or are outdated in the short range loop""" system = self.system system.virtual_sites = VirtualSitesRelative(have_velocity=True) # Parameters n = 90 phi = 0.6 sigma = 1. eps = .025 cut = sigma * 2**(1. / 6.) kT = 2 gamma = .5 # box l = (n / 6. * np.pi * sigma**3 / phi)**(1. / 3.) # Setup system.box_l = l, l, l system.min_global_cut = 0.501 system.part.clear() system.time_step = 0.01 system.thermostat.turn_off() # Dumbells consist of 2 virtual lj spheres + central particle w/o interactions # For n spheres, n/2 dumbells. for i in range(int(n / 2)): # Type=1, i.e., no lj ia for the center of mass particles system.part.add( rotation=(1, 1, 1), id=3 * i, pos=random.random(3) * l, type=1, omega_lab=0.3 * random.random(3), v=random.random(3)) # lj spheres system.part.add(rotation=(1, 1, 1), id=3 * i + 1, pos=system.part[3 * i].pos + system.part[3 * i].director / 2., type=0) system.part.add(rotation=(1, 1, 1), id=3 * i + 2, pos=system.part[3 * i].pos - system.part[3 * i].director / 2., type=0) system.part[3 * i + 1].vs_auto_relate_to(3 * i) self.verify_vs(system.part[3 * i + 1], verify_velocity=False) system.part[3 * i + 2].vs_auto_relate_to(3 * i) self.verify_vs(system.part[3 * i + 2], verify_velocity=False) system.integrator.run(0, recalc_forces=True) # interactions system.non_bonded_inter[0, 0].lennard_jones.set_params( epsilon=eps, sigma=sigma, cutoff=cut, shift="auto") # Remove overlap system.integrator.set_steepest_descent( f_max=0, gamma=0.1, max_displacement=0.1) while system.analysis.energy()["total"] > 10 * n: system.integrator.run(20) # Integrate system.integrator.set_vv() for i in range(10): # Langevin to maintain stability system.thermostat.set_langevin(kT=kT, gamma=gamma, seed=42) system.integrator.run(50) system.thermostat.turn_off() # Constant energy to get rid of thermostat forces in the # verification system.integrator.run(2) # Check the virtual sites config,pos and vel of the lj spheres for j in range(int(n / 2)): self.verify_vs(system.part[3 * j + 1]) self.verify_vs(system.part[3 * j + 2]) # Verify lj forces on the particles. The non-virtual particles are # skipped because the forces on them originate from the vss and not # the lj interaction verify_lj_forces(system, 1E-10, 3 * np.arange(int(n / 2), dtype=int)) # Test applying changes enegry_pre_change = system.analysis.energy()['total'] pressure_pre_change = system.analysis.pressure()['total'] system.part[0].pos = system.part[0].pos + (2.2, -1.4, 4.2) enegry_post_change = system.analysis.energy()['total'] pressure_post_change = system.analysis.pressure()['total'] self.assertNotAlmostEqual(enegry_pre_change, enegry_post_change) self.assertNotAlmostEqual(pressure_pre_change, pressure_post_change) # Turn off lj interaction system.non_bonded_inter[0, 0].lennard_jones.set_params( epsilon=0, sigma=0, cutoff=0, shift=0) def test_lj(self): """Run LJ fluid test for different cell systems.""" system = self.system system.cell_system.skin = 0.4 system.cell_system.set_n_square(use_verlet_lists=True) self.run_test_lj() system.cell_system.set_domain_decomposition(use_verlet_lists=True) self.run_test_lj() system.cell_system.set_domain_decomposition(use_verlet_lists=False) self.run_test_lj() @utx.skipIfMissingFeatures("EXTERNAL_FORCES") def test_zz_stress_tensor(self): system = self.system system.time_step = 0.01 system.cell_system.skin = 0.1 system.min_global_cut = 0.2 # Should not have one if vs are turned off system.virtual_sites = VirtualSitesOff() self.assertTrue("virtual_sites" not in system.analysis.pressure()) self.assertTrue("virtual_sites" not in system.analysis.stress_tensor()) # vs relative contrib system.virtual_sites = VirtualSitesRelative() system.part.clear() system.part.add(pos=(0, 0, 0), id=0) p = system.part.add(pos=(0.1, 0.1, 0.1), id=1, ext_force=(1, 2, 3)) p.vs_auto_relate_to(0) p = system.part.add(pos=(0.1, 0, 0), id=2, ext_force=(-1, 0, 0)) p.vs_auto_relate_to(0) system.integrator.run(0, recalc_forces=True) stress_total = system.analysis.stress_tensor()["total"] stress_vs_total = system.analysis.stress_tensor()["virtual_sites"] stress_vs = system.analysis.stress_tensor()["virtual_sites", 0] p_total = system.analysis.pressure()["total"] p_vs_total = system.analysis.pressure()["virtual_sites"] p_vs = system.analysis.pressure()["virtual_sites", 0] # expected stress s_expected = 1. / system.volume() * ( np.outer(system.part[1].ext_force, system.distance_vec( system.part[1], system.part[0])) + np.outer(system.part[2].ext_force, system.distance_vec(system.part[2], system.part[0]))) np.testing.assert_allclose(stress_total, s_expected, atol=1E-5) np.testing.assert_allclose(stress_vs, s_expected, atol=1E-5) np.testing.assert_allclose(stress_vs_total, s_expected, atol=1E-5) # Pressure self.assertAlmostEqual(p_total, np.sum( np.diag(s_expected)) / 3, places=5) self.assertAlmostEqual(p_vs_total, np.sum( np.diag(s_expected)) / 3, places=5) self.assertAlmostEqual(p_vs, np.sum(np.diag(s_expected)) / 3, places=5) if __name__ == "__main__": ut.main()
psci2195/espresso-ffans
testsuite/python/virtual_sites_relative.py
Python
gpl-3.0
15,216
[ "ESPResSo" ]
5b23f6d97929d84fbcd00da4ae3a57054a08ed82fe2bb91caea33194c5e1535d
from __future__ import absolute_import from datetime import timedelta from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.utils import timezone from experiments import conf from experiments.experiment_counters import ExperimentCounter from experiments.middleware import ExperimentsRetentionMiddleware from experiments.models import Experiment, ENABLED_STATE, Enrollment from experiments.conf import CONTROL_GROUP, VISIT_PRESENT_COUNT_GOAL, VISIT_NOT_PRESENT_COUNT_GOAL from experiments.signal_handlers import transfer_enrollments_to_user from experiments.utils import participant from mock import patch import random request_factory = RequestFactory() TEST_ALTERNATIVE = 'blue' TEST_GOAL = 'buy' EXPERIMENT_NAME = 'backgroundcolor' class WebUserTests(object): def setUp(self): self.experiment = Experiment(name=EXPERIMENT_NAME, state=ENABLED_STATE) self.experiment.save() self.request = request_factory.get('/') self.request.session = DatabaseSession() self.experiment_counter = ExperimentCounter() def tearDown(self): self.experiment_counter.delete(self.experiment) def test_enrollment_initially_control(self): experiment_user = participant(self.request) self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), 'control', "Default Enrollment wasn't control") def test_user_enrolls(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), TEST_ALTERNATIVE, "Wrong Alternative Set") def test_record_goal_increments_counts(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 0) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not increment Goal count") def test_can_record_goal_multiple_times(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) experiment_user.goal(TEST_GOAL) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not increment goal count correctly") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), {3: 1}, "Incorrect goal count distribution") def test_counts_increment_immediately_once_confirmed_human(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 1, "Did not count participant after confirm human") def test_visit_increases_goal(self): thetime = timezone.now() with patch('experiments.utils.now', return_value=thetime): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {1: 1}, "Not Present Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {}, "Present Visit was not correctly counted") with patch('experiments.utils.now', return_value=thetime + timedelta(hours=7)): experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {2: 1}, "No Present Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {1: 1}, "Present Visit was not correctly counted") def test_visit_twice_increases_once(self): experiment_user = participant(self.request) experiment_user.confirm_human() experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.visit() experiment_user.visit() self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_NOT_PRESENT_COUNT_GOAL), {1: 1}, "Visit was not correctly counted") self.assertEqual(self.experiment_counter.goal_distribution(self.experiment, TEST_ALTERNATIVE, VISIT_PRESENT_COUNT_GOAL), {}, "Present Visit was not correctly counted") def test_user_force_enrolls(self): experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, ['control', 'alternative1', 'alternative2'], force_alternative='alternative2') self.assertEqual(experiment_user.get_alternative(EXPERIMENT_NAME), 'alternative2') def test_user_does_not_force_enroll_to_new_alternative(self): alternatives = ['control', 'alternative1', 'alternative2'] experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, alternatives) alternative = experiment_user.get_alternative(EXPERIMENT_NAME) self.assertIsNotNone(alternative) other_alternative = random.choice(list(set(alternatives) - set(alternative))) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative=other_alternative) self.assertEqual(alternative, experiment_user.get_alternative(EXPERIMENT_NAME)) def test_second_force_enroll_does_not_change_alternative(self): alternatives = ['control', 'alternative1', 'alternative2'] experiment_user = participant(self.request) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative='alternative1') alternative = experiment_user.get_alternative(EXPERIMENT_NAME) self.assertIsNotNone(alternative) other_alternative = random.choice(list(set(alternatives) - set(alternative))) experiment_user.enroll(EXPERIMENT_NAME, alternatives, force_alternative=other_alternative) self.assertEqual(alternative, experiment_user.get_alternative(EXPERIMENT_NAME)) class WebUserAnonymousTestCase(WebUserTests, TestCase): def setUp(self): super(WebUserAnonymousTestCase, self).setUp() self.request.user = AnonymousUser() def test_confirm_human_increments_participant_count(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Counted participant before confirmed human") experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 1, "Did not count participant after confirm human") def test_confirm_human_increments_goal_count(self): experiment_user = participant(self.request) experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 0, "Counted goal before confirmed human") experiment_user.confirm_human() self.assertEqual(self.experiment_counter.goal_count(self.experiment, TEST_ALTERNATIVE, TEST_GOAL), 1, "Did not count goal after confirm human") class WebUserAuthenticatedTestCase(WebUserTests, TestCase): def setUp(self): super(WebUserAuthenticatedTestCase, self).setUp() User = get_user_model() self.request.user = User(username='brian') self.request.user.save() class BotTests(object): def setUp(self): self.experiment = Experiment(name='backgroundcolor', state=ENABLED_STATE) self.experiment.save() self.experiment_counter = ExperimentCounter() def test_user_does_not_enroll(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Bot counted towards results") def test_user_does_not_fire_goals(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.experiment_user.goal(TEST_GOAL) self.assertEqual(self.experiment_counter.participant_count(self.experiment, TEST_ALTERNATIVE), 0, "Bot counted towards results") def test_bot_in_control_group(self): self.experiment_user.set_alternative(EXPERIMENT_NAME, TEST_ALTERNATIVE) self.assertEqual(self.experiment_user.get_alternative(EXPERIMENT_NAME), 'control', "Bot enrolled in a group") self.assertEqual(self.experiment_user.is_enrolled(self.experiment.name, TEST_ALTERNATIVE), False, "Bot in test alternative") self.assertEqual(self.experiment_user.is_enrolled(self.experiment.name, CONTROL_GROUP), True, "Bot not in control group") def tearDown(self): self.experiment_counter.delete(self.experiment) class LoggedOutBotTestCase(BotTests, TestCase): def setUp(self): super(LoggedOutBotTestCase, self).setUp() self.request = request_factory.get('/', HTTP_USER_AGENT='GoogleBot/2.1') self.experiment_user = participant(self.request) class LoggedInBotTestCase(BotTests, TestCase): def setUp(self): super(LoggedInBotTestCase, self).setUp() User = get_user_model() self.user = User(username='brian') self.user.is_confirmed_human = False self.user.save() self.experiment_user = participant(user=self.user) class ParticipantCacheTestCase(TestCase): def setUp(self): self.experiment = Experiment.objects.create(name='test_experiment1', state=ENABLED_STATE) self.experiment_counter = ExperimentCounter() def tearDown(self): self.experiment_counter.delete(self.experiment) def test_transfer_enrollments(self): User = get_user_model() user = User.objects.create(username='test') request = request_factory.get('/') request.session = DatabaseSession() participant(request).enroll('test_experiment1', ['alternative']) request.user = user transfer_enrollments_to_user(None, request, user) # the call to the middleware will set last_seen on the experiment # if the participant cache hasn't been wiped appropriately then the # session experiment user will be impacted instead of the authenticated # experiment user ExperimentsRetentionMiddleware().process_response(request, HttpResponse()) self.assertIsNotNone(Enrollment.objects.all()[0].last_seen) class ConfirmHumanTestCase(TestCase): def setUp(self): self.experiment = Experiment.objects.create(name='test_experiment1', state=ENABLED_STATE) self.experiment_counter = ExperimentCounter() self.experiment_user = participant(session=DatabaseSession()) self.alternative = self.experiment_user.enroll(self.experiment.name, ['alternative']) self.experiment_user.goal('my_goal') def tearDown(self): self.experiment_counter.delete(self.experiment) def test_confirm_human_updates_experiment(self): self.assertIn('experiments_goals', self.experiment_user.session) self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 0) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 0) self.experiment_user.confirm_human() self.assertNotIn('experiments_goals', self.experiment_user.session) self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) def test_confirm_human_called_twice(self): """ Ensuring that counters aren't incremented twice """ self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 0) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 0) self.experiment_user.confirm_human() self.experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) def test_confirm_human_sets_session(self): self.assertFalse(self.experiment_user.session.get(conf.CONFIRM_HUMAN_SESSION_KEY, False)) self.experiment_user.confirm_human() self.assertTrue(self.experiment_user.session.get(conf.CONFIRM_HUMAN_SESSION_KEY, False)) def test_session_already_confirmed(self): """ Testing that confirm_human works even if code outside of django-experiments updates the key """ self.experiment_user.session[conf.CONFIRM_HUMAN_SESSION_KEY] = True self.experiment_user.confirm_human() self.assertEqual(self.experiment_counter.participant_count(self.experiment, self.alternative), 1) self.assertEqual(self.experiment_counter.goal_count(self.experiment, self.alternative, 'my_goal'), 1) class DefaultAlternativeTestCase(TestCase): def test_default_alternative(self): experiment = Experiment.objects.create(name='test_default') self.assertEqual(experiment.default_alternative, conf.CONTROL_GROUP) experiment.ensure_alternative_exists('alt1') experiment.ensure_alternative_exists('alt2') self.assertEqual(conf.CONTROL_GROUP, participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2'])) experiment.set_default_alternative('alt2') experiment.save() self.assertEqual('alt2', participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2'])) experiment.set_default_alternative('alt1') experiment.save() self.assertEqual('alt1', participant(session=DatabaseSession()).enroll('test_default', ['alt1', 'alt2']))
squamous/django-experiments
experiments/tests/test_webuser.py
Python
mit
15,007
[ "Brian", "VisIt" ]
4bba2d8d694b8a71ea626befd99bc4447009e7ff8a64884f99f30a8fd54ec381
# -*- coding: utf-8 -*- ############################################################################## # 2014 E2OpenPlugins # # # # This file is open source software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License version 2 as # # published by the Free Software Foundation. # # # ############################################################################## # Simulate the oe-a boxbranding module (Only functions required by OWIF) # ############################################################################## from Plugins.Extensions.OpenWebif.__init__ import _ from Components.About import about from socket import has_ipv6 from Tools.Directories import fileExists, pathExists import string import os, hashlib try: from Components.About import about except: pass tpmloaded = 1 try: from enigma import eTPM if not hasattr(eTPM, 'getData'): tpmloaded = 0 except: tpmloaded = 0 def validate_certificate(cert, key): buf = decrypt_block(cert[8:], key) if buf is None: return None return buf[36:107] + cert[139:196] def get_random(): try: xor = lambda a,b: ''.join(chr(ord(c)^ord(d)) for c,d in zip(a,b*100)) random = urandom(8) x = str(time())[-8:] result = xor(random, x) return result except: return None def bin2long(s): return reduce( lambda x,y:(x<<8L)+y, map(ord, s)) def long2bin(l): res = "" for byte in range(128): res += chr((l >> (1024 - (byte + 1) * 8)) & 0xff) return res def rsa_pub1024(src, mod): return long2bin(pow(bin2long(src), 65537, bin2long(mod))) def decrypt_block(src, mod): if len(src) != 128 and len(src) != 202: return None dest = rsa_pub1024(src[:128], mod) hash = hashlib.sha1(dest[1:107]) if len(src) == 202: hash.update(src[131:192]) result = hash.digest() if result == dest[107:127]: return dest return None def tpm_check(): try: tpm = eTPM() rootkey = ['\x9f', '|', '\xe4', 'G', '\xc9', '\xb4', '\xf4', '#', '&', '\xce', '\xb3', '\xfe', '\xda', '\xc9', 'U', '`', '\xd8', '\x8c', 's', 'o', '\x90', '\x9b', '\\', 'b', '\xc0', '\x89', '\xd1', '\x8c', '\x9e', 'J', 'T', '\xc5', 'X', '\xa1', '\xb8', '\x13', '5', 'E', '\x02', '\xc9', '\xb2', '\xe6', 't', '\x89', '\xde', '\xcd', '\x9d', '\x11', '\xdd', '\xc7', '\xf4', '\xe4', '\xe4', '\xbc', '\xdb', '\x9c', '\xea', '}', '\xad', '\xda', 't', 'r', '\x9b', '\xdc', '\xbc', '\x18', '3', '\xe7', '\xaf', '|', '\xae', '\x0c', '\xe3', '\xb5', '\x84', '\x8d', '\r', '\x8d', '\x9d', '2', '\xd0', '\xce', '\xd5', 'q', '\t', '\x84', 'c', '\xa8', ')', '\x99', '\xdc', '<', '"', 'x', '\xe8', '\x87', '\x8f', '\x02', ';', 'S', 'm', '\xd5', '\xf0', '\xa3', '_', '\xb7', 'T', '\t', '\xde', '\xa7', '\xf1', '\xc9', '\xae', '\x8a', '\xd7', '\xd2', '\xcf', '\xb2', '.', '\x13', '\xfb', '\xac', 'j', '\xdf', '\xb1', '\x1d', ':', '?'] random = None result = None l2r = False l2k = None l3k = None l2c = tpm.getData(eTPM.DT_LEVEL2_CERT) if l2c is None: return 0 l2k = validate_certificate(l2c, rootkey) if l2k is None: return 0 l3c = tpm.getData(eTPM.DT_LEVEL3_CERT) if l3c is None: return 0 l3k = validate_certificate(l3c, l2k) if l3k is None: return 0 random = get_random() if random is None: return 0 value = tpm.computeSignature(random) result = decrypt_block(value, l3k) if result is None: return 0 if result [80:88] != random: return 0 return 1 except: return 0 def getAllInfo(): info = {} brand = "unknown" model = "unknown" procmodel = "unknown" orgdream = 0 if tpmloaded: orgdream = tpm_check() if fileExists("/proc/stb/info/hwmodel"): brand = "DAGS" f = open("/proc/stb/info/hwmodel",'r') procmodel = f.readline().strip() f.close() if (procmodel.startswith("optimuss") or procmodel.startswith("pingulux")): brand = "Edision" model = procmodel.replace("optimmuss", "Optimuss ").replace("plus", " Plus").replace(" os", " OS") elif (procmodel.startswith("fusion") or procmodel.startswith("purehd")): brand = "Xsarius" if procmodel == "fusionhd": model = procmodel.replace("fusionhd", "Fusion HD") elif procmodel == "fusionhdse": model = procmodel.replace("fusionhdse", "Fusion HD SE") elif procmodel == "purehd": model = procmodel.replace("purehd", "PureHD") elif fileExists("/proc/stb/info/azmodel"): brand = "AZBox" f = open("/proc/stb/info/model",'r') # To-Do: Check if "model" is really correct ... procmodel = f.readline().strip() f.close() model = procmodel.lower() elif fileExists("/proc/stb/info/gbmodel"): brand = "GigaBlue" f = open("/proc/stb/info/gbmodel",'r') procmodel = f.readline().strip() f.close() model = procmodel.upper().replace("GBQUAD", "Quad").replace("PLUS", " Plus") elif fileExists("/proc/stb/info/vumodel") and not fileExists("/proc/stb/info/boxtype"): brand = "Vu+" f = open("/proc/stb/info/vumodel",'r') procmodel = f.readline().strip() f.close() model = procmodel.title().replace("olose", "olo SE").replace("olo2se", "olo2 SE").replace("2", "²") elif fileExists("/proc/boxtype"): f = open("/proc/boxtype",'r') procmodel = f.readline().strip().lower() f.close() if procmodel in ("adb2850", "adb2849", "bska", "bsla", "bxzb", "bzzb"): brand = "Advanced Digital Broadcast" if procmodel in ("bska", "bxzb"): model = "ADB 5800S" elif procmodel in ("bsla", "bzzb"): model = "ADB 5800SX" elif procmodel == "adb2849": model = "ADB 2849ST" else: model = "ADB 2850ST" elif procmodel in ("esi88", "uhd88"): brand = "Sagemcom" if procmodel == "uhd88": model = "UHD 88" else: model = "ESI 88" elif fileExists("/proc/stb/info/boxtype"): f = open("/proc/stb/info/boxtype",'r') procmodel = f.readline().strip().lower() f.close() if procmodel.startswith("et"): if procmodel == "et7000mini": brand = "Galaxy Innovations" model = "ET-7000 Mini" else: brand = "Xtrend" model = procmodel.upper() elif procmodel.startswith("xpeed"): brand = "Golden Interstar" model = procmodel elif procmodel.startswith("xp"): brand = "MaxDigital" model = procmodel elif procmodel.startswith("ixuss"): brand = "Medialink" model = procmodel.replace(" ", "") elif procmodel.startswith("formuler"): brand = "Formuler" model = procmodel.replace("formuler","") elif procmodel.startswith("g300"): brand = "Miraclebox" model = "Premiun twin+" elif procmodel == "7000s": brand = "Miraclebox" model = "Premium micro" elif procmodel.startswith("ini"): if procmodel.endswith("9000ru"): brand = "Sezam" model = "Marvel" elif procmodel.endswith("5000ru"): brand = "Sezam" model = "hdx" elif procmodel.endswith("1000ru"): brand = "Sezam" model = "hde" elif procmodel.endswith("5000sv"): brand = "Miraclebox" model = "mbtwin" elif procmodel.endswith("1000sv"): brand = "Miraclebox" model = "mbmini" elif procmodel.endswith("1000de"): brand = "Golden Interstar" model = "Xpeed LX" elif procmodel.endswith("9000de"): brand = "Golden Interstar" model = "Xpeed LX3" elif procmodel.endswith("1000lx"): brand = "Golden Interstar" model = "Xpeed LX" elif procmodel.endswith("de"): brand = "Golden Interstar" elif procmodel.endswith("1000am"): brand = "Atemio" model = "5x00" else: brand = "Venton" model = "HDx" elif procmodel.startswith("unibox-"): brand = "Venton" model = "HDe" elif procmodel == "hd1100": brand = "Mut@nt" model = "hd1100" elif procmodel == "hd1200": brand = "Mut@nt" model = "hd1200" elif procmodel == "hd1265": brand = "Mut@nt" model = "hd1265" elif procmodel == "hd2400": brand = "Mut@nt" model = "hd2400" elif procmodel == "arivalink200": brand = "Ferguson" model = "Ariva @Link 200" elif procmodel.startswith("spark"): brand = "Fulan" if procmodel == "spark7162": model = "Spark 7162" else: model = "Spark" elif procmodel == "spycat": brand = "Spycat" model = "spycat" elif procmodel == "spycatmini": brand = "Spycat" model = "spycatmini" elif procmodel == "wetekplay": brand = "WeTeK" model = procmodel elif procmodel.startswith("osm"): brand = "Edision" model = procmodel elif procmodel == "h5": brand = "Zgemma" model = "H5" elif procmodel == "lc": brand = "Zgemma" model = "LC" elif fileExists("/proc/stb/info/model"): f = open("/proc/stb/info/model",'r') procmodel = f.readline().strip().lower() f.close() if procmodel == "tf7700hdpvr": brand = "Topfield" model = "TF7700 HDPVR" elif procmodel == "dsi87": brand = "Sagemcom" model = "DSI 87" elif procmodel.startswith("spark"): brand = "Fulan" if procmodel == "spark7162": model = "Spark 7162" else: model = "Spark" elif (procmodel.startswith("dm") and not procmodel == "dm8000"): brand = "Dream Multimedia" model = procmodel.replace("dm", "DM", 1) # A "dm8000" is only a Dreambox if it passes the tpm verification: elif procmodel == "dm8000" and orgdream: brand = "Dream Multimedia" model = "DM8000" else: model = procmodel if fileExists("/etc/.box"): distro = "HDMU" f = open("/etc/.box",'r') tempmodel = f.readline().strip().lower() if tempmodel.startswith("ufs") or model.startswith("ufc"): brand = "Kathrein" model = tempmodel.upcase() procmodel = tempmodel elif tempmodel.startswith("spark"): brand = "Fulan" model = tempmodel.title() procmodel = tempmodel elif tempmodel.startswith("xcombo"): brand = "EVO" model = "enfinityX combo plus" procmodel = "vg2000" type = procmodel if type in ("et9000", "et9100", "et9200", "et9500"): type = "et9x00" elif type in ("et5000", "et6000", "et6x00"): type = "et5x00" elif type == "et4000": type = "et4x00" elif type == "xp1000": type = "xp1000" elif type in ("bska", "bxzb"): type = "nbox_white" elif type in ("bsla", "bzzb"): type = "nbox" elif type == "sagemcom88": type = "esi88" elif type in ("tf7700hdpvr", "topf"): type = "topf" info['brand'] = brand info['model'] = model info['procmodel'] = procmodel info['type'] = type remote = "dmm" if procmodel in ("solo", "duo", "uno", "solo2", "solose", "zero", "solo4k"): remote = "vu_normal" elif procmodel == "duo2": remote = "vu_duo2" elif procmodel == "ultimo": remote = "vu_ultimo" elif procmodel == "e3hd": remote = "e3hd" elif procmodel in ("et9x00", "et9000", "et9100", "et9200", "et9500"): remote = "et9x00" elif procmodel in ("et5x00", "et5000", "et6x00", "et6000"): remote = "et5x00" elif procmodel in ("et4x00", "et4000"): remote = "et4x00" elif procmodel == "et6500": remote = "et6500" elif procmodel in ("et8x00", "et8000", "et8500", "et8500s","et1x000", "et10000"): remote = "et8000" elif procmodel in ("et7x00", "et7000", "et7500"): remote = "et7x00" elif procmodel == "et7000mini": remote = "et7000mini" elif procmodel == "gbquad": remote = "gigablue" elif procmodel == "gbquadplus": remote = "gbquadplus" elif procmodel in ("formuler1", "formuler3", "formuler4"): remote = "formuler1" elif procmodel in ("azboxme", "azboxminime", "me", "minime"): remote = "me" elif procmodel in ("optimussos1", "optimussos1plus", "optimussos2", "optimussos2plus"): remote = "optimuss" elif procmodel in ("premium", "premium+"): remote = "premium" elif procmodel in ("elite", "ultra"): remote = "elite" elif procmodel in ("ini-1000", "ini-1000ru"): remote = "ini-1000" elif procmodel in ("ini-1000sv", "ini-5000sv", "ini-9000de"): remote = "miraclebox" elif procmodel in ("7000s"): remote = "miraclebox2" elif procmodel == "ini-3000": remote = "ini-3000" elif procmodel in ("ini-7012", "ini-7000", "ini-5000", "ini-5000ru"): remote = "ini-7000" elif procmodel.startswith("spark"): remote = "spark" elif procmodel == "xp1000": remote = "xp1000" elif procmodel.startswith("xpeedlx"): remote = "xpeedlx" elif procmodel in ("adb2850", "adb2849", "bska", "bsla", "bxzb", "bzzb", "esi88", "uhd88", "dsi87", "arivalink200"): remote = "nbox" elif procmodel in ("hd1100", "hd1200", "hd1265"): remote = "hd1x00" elif procmodel == "hd2400": remote = "hd2400" elif procmodel in ("spycat", "spycatmini"): remote = "spycat" elif procmodel.startswith("ixuss"): remote = procmodel.replace(" ", "") elif procmodel == "vg2000": remote = "xcombo" elif procmodel == "dm8000" and orgdream: remote = "dmm1" elif procmodel in ("dm7080", "dm7020hd", "dm7020hdv2", "dm800sev2", "dm500hdv2", "dm820"): remote = "dmm2" elif procmodel == "wetekplay": remote = procmodel elif procmodel.startswith("osm"): remote = "osmini" elif procmodel in ("fusionhd"): remote = procmodel elif procmodel in ("fusionhdse"): remote = procmodel elif procmodel in ("purehd"): remote = procmodel elif procmodel in ("h5", "lc"): remote = "h5" info['remote'] = remote kernel = about.getKernelVersionString()[0] distro = "unknown" imagever = "unknown" imagebuild = "" driverdate = "unknown" # Assume OE 1.6 oever = "OE 1.6" if kernel>2: oever = "OE 2.0" if fileExists("/etc/.box"): distro = "HDMU" oever = "private" elif fileExists("/etc/bhversion"): distro = "Black Hole" f = open("/etc/bhversion",'r') imagever = f.readline().strip() f.close() if kernel>2: oever = "OpenVuplus 2.1" elif fileExists("/etc/vtiversion.info"): distro = "VTi-Team Image" f = open("/etc/vtiversion.info",'r') imagever = f.readline().strip().replace("VTi-Team Image ", "").replace("Release ", "").replace("v.", "") f.close() oever = "OE 1.6" imagelist = imagever.split('.') imagebuild = imagelist.pop() imagever = ".".join(imagelist) if kernel>2: oever = "OpenVuplus 2.1" if ((imagever == "5.1") or (imagever[0] > 5)): oever = "OpenVuplus 2.1" elif fileExists("/var/grun/grcstype"): distro = "Graterlia OS" try: imagever = about.getImageVersionString() except: pass # ToDo: If your distro gets detected as OpenPLi, feel free to add a detection for your distro here ... else: # OE 2.2 uses apt, not opkg if not fileExists("/etc/opkg/all-feed.conf"): oever = "OE 2.2" else: try: f = open("/etc/opkg/all-feed.conf",'r') oeline = f.readline().strip().lower() f.close() distro = oeline.split( )[1].replace("-all","") except: pass if distro == "openpli": imagever = "2.1" # Todo: Detect OpenPLi 3.0 if has_ipv6: # IPv6 support for Python was added in 4.0 imagever = "4.0" oever = "PLi-OE" imagelist = imagever.split('.') imagebuild = imagelist.pop() imagever = ".".join(imagelist) elif distro == "openrsi": oever = "PLi-OE" else: try: imagever = about.getImageVersionString() except: pass if (distro == "unknown" and brand == "Vu+" and fileExists("/etc/version")): # Since OE-A uses boxbranding and bh or vti can be detected, there isn't much else left for Vu+ boxes distro = "Vu+ original" f = open("/etc/version",'r') imagever = f.readline().strip() f.close() if kernel>2: oever = "OpenVuplus 2.1" # reporting the installed dvb-module version is as close as we get without too much hassle driverdate = 'unknown' try: driverdate = os.popen('/usr/bin/opkg -V0 list_installed *dvb-modules*').readline().split( )[2] except: try: driverdate = os.popen('/usr/bin/opkg -V0 list_installed *dvb-proxy*').readline().split( )[2] except: try: driverdate = os.popen('/usr/bin/opkg -V0 list_installed *kernel-core-default-gos*').readline().split( )[2] except: pass info['oever'] = oever info['distro'] = distro info['imagever'] = imagever info['imagebuild'] = imagebuild info['driverdate'] = driverdate return info STATIC_INFO_DIC = getAllInfo() def getMachineBuild(): return STATIC_INFO_DIC['procmodel'] def getMachineBrand(): return STATIC_INFO_DIC['brand'] def getMachineName(): return STATIC_INFO_DIC['model'] def getMachineProcModel(): return STATIC_INFO_DIC['procmodel'] def getBoxType(): return STATIC_INFO_DIC['type'] def getOEVersion(): return STATIC_INFO_DIC['oever'] def getDriverDate(): return STATIC_INFO_DIC['driverdate'] def getImageVersion(): return STATIC_INFO_DIC['imagever'] def getImageBuild(): return STATIC_INFO_DIC['imagebuild'] def getImageDistro(): return STATIC_INFO_DIC['distro'] class rc_model: def getRcFolder(self): return STATIC_INFO_DIC['remote']
svox1/e2openplugin-OpenWebif
plugin/controllers/models/owibranding.py
Python
gpl-2.0
16,710
[ "Galaxy" ]
b5cf9da477e604eca81983be9ea78a9fe6080355cd0a7d42806415ca625b6196
#!/usr/bin/env python ''' Fly ArduPlane in SITL AP_FLAKE8_CLEAN ''' from __future__ import print_function import math import os import signal import sys import time from pymavlink import quaternion from pymavlink import mavextra from pymavlink import mavutil from common import AutoTest from common import AutoTestTimeoutException from common import NotAchievedException from common import PreconditionFailedException from pymavlink.rotmat import Vector3 from pysim import vehicleinfo import operator # get location of scripts testdir = os.path.dirname(os.path.realpath(__file__)) SITL_START_LOCATION = mavutil.location(-35.362938, 149.165085, 585, 354) WIND = "0,180,0.2" # speed,direction,variance class AutoTestPlane(AutoTest): @staticmethod def get_not_armable_mode_list(): return [] @staticmethod def get_not_disarmed_settable_modes_list(): return ["FOLLOW"] @staticmethod def get_no_position_not_settable_modes_list(): return [] @staticmethod def get_position_armable_modes_list(): return ["GUIDED", "AUTO"] @staticmethod def get_normal_armable_modes_list(): return ["MANUAL", "STABILIZE", "ACRO"] def log_name(self): return "ArduPlane" def test_filepath(self): return os.path.realpath(__file__) def sitl_start_location(self): return SITL_START_LOCATION def defaults_filepath(self): return os.path.join(testdir, 'default_params/plane-jsbsim.parm') def set_current_test_name(self, name): self.current_test_name_directory = "ArduPlane_Tests/" + name + "/" def default_frame(self): return "plane-elevrev" def apply_defaultfile_parameters(self): # plane passes in a defaults_filepath in place of applying # parameters afterwards. pass def is_plane(self): return True def get_stick_arming_channel(self): return int(self.get_parameter("RCMAP_YAW")) def get_disarm_delay(self): return int(self.get_parameter("LAND_DISARMDELAY")) def set_autodisarm_delay(self, delay): self.set_parameter("LAND_DISARMDELAY", delay) def takeoff(self, alt=150, alt_max=None, relative=True): """Takeoff to altitude.""" if alt_max is None: alt_max = alt + 30 self.change_mode("FBWA") self.wait_ready_to_arm() self.arm_vehicle() # some rudder to counteract the prop torque self.set_rc(4, 1700) # some up elevator to keep the tail down self.set_rc(2, 1200) # get it moving a bit first self.set_rc(3, 1300) self.wait_groundspeed(6, 100) # a bit faster again, straighten rudder self.set_rc_from_map({ 3: 1600, 4: 1500, }) self.wait_groundspeed(12, 100) # hit the gas harder now, and give it some more elevator self.set_rc_from_map({ 2: 1100, 3: 2000, }) # gain a bit of altitude self.wait_altitude(alt, alt_max, timeout=30, relative=relative) # level off self.set_rc(2, 1500) self.progress("TAKEOFF COMPLETE") def fly_left_circuit(self): """Fly a left circuit, 200m on a side.""" self.change_mode('FBWA') self.set_rc(3, 2000) self.wait_level_flight() self.progress("Flying left circuit") # do 4 turns for i in range(0, 4): # hard left self.progress("Starting turn %u" % i) self.set_rc(1, 1000) self.wait_heading(270 - (90*i), accuracy=10) self.set_rc(1, 1500) self.progress("Starting leg %u" % i) self.wait_distance(100, accuracy=20) self.progress("Circuit complete") def fly_RTL(self): """Fly to home.""" self.progress("Flying home in RTL") self.change_mode('RTL') self.wait_location(self.homeloc, accuracy=120, target_altitude=self.homeloc.alt+100, height_accuracy=20, timeout=180) self.progress("RTL Complete") def test_need_ekf_to_arm(self): """Loiter where we are.""" self.progress("Ensuring we need EKF to be healthy to arm") self.reboot_sitl() self.context_collect("STATUSTEXT") tstart = self.get_sim_time() success = False while not success: if self.get_sim_time_cached() - tstart > 60: raise NotAchievedException("Did not get correct failure reason") self.send_mavlink_arm_command() try: self.wait_statustext(".*(AHRS not healthy|AHRS: Not healthy).*", timeout=1, check_context=True, regex=True) success = True continue except AutoTestTimeoutException: pass if self.armed(): raise NotAchievedException("Armed unexpectedly") def fly_LOITER(self, num_circles=4): """Loiter where we are.""" self.progress("Testing LOITER for %u turns" % num_circles) self.change_mode('LOITER') m = self.mav.recv_match(type='VFR_HUD', blocking=True) initial_alt = m.alt self.progress("Initial altitude %u\n" % initial_alt) while num_circles > 0: self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) num_circles -= 1 self.progress("Loiter %u circles left" % num_circles) m = self.mav.recv_match(type='VFR_HUD', blocking=True) final_alt = m.alt self.progress("Final altitude %u initial %u\n" % (final_alt, initial_alt)) self.change_mode('FBWA') if abs(final_alt - initial_alt) > 20: raise NotAchievedException("Failed to maintain altitude") self.progress("Completed Loiter OK") def fly_CIRCLE(self, num_circles=1): """Circle where we are.""" self.progress("Testing CIRCLE for %u turns" % num_circles) self.change_mode('CIRCLE') m = self.mav.recv_match(type='VFR_HUD', blocking=True) initial_alt = m.alt self.progress("Initial altitude %u\n" % initial_alt) while num_circles > 0: self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) num_circles -= 1 self.progress("CIRCLE %u circles left" % num_circles) m = self.mav.recv_match(type='VFR_HUD', blocking=True) final_alt = m.alt self.progress("Final altitude %u initial %u\n" % (final_alt, initial_alt)) self.change_mode('FBWA') if abs(final_alt - initial_alt) > 20: raise NotAchievedException("Failed to maintain altitude") self.progress("Completed CIRCLE OK") def wait_level_flight(self, accuracy=5, timeout=30): """Wait for level flight.""" tstart = self.get_sim_time() self.progress("Waiting for level flight") self.set_rc(1, 1500) self.set_rc(2, 1500) self.set_rc(4, 1500) while self.get_sim_time_cached() < tstart + timeout: m = self.mav.recv_match(type='ATTITUDE', blocking=True) roll = math.degrees(m.roll) pitch = math.degrees(m.pitch) self.progress("Roll=%.1f Pitch=%.1f" % (roll, pitch)) if math.fabs(roll) <= accuracy and math.fabs(pitch) <= accuracy: self.progress("Attained level flight") return raise NotAchievedException("Failed to attain level flight") def change_altitude(self, altitude, accuracy=30): """Get to a given altitude.""" self.change_mode('FBWA') alt_error = self.mav.messages['VFR_HUD'].alt - altitude if alt_error > 0: self.set_rc(2, 2000) else: self.set_rc(2, 1000) self.wait_altitude(altitude-accuracy/2, altitude+accuracy/2) self.set_rc(2, 1500) self.progress("Reached target altitude at %u" % self.mav.messages['VFR_HUD'].alt) return self.wait_level_flight() def axial_left_roll(self, count=1): """Fly a left axial roll.""" # full throttle! self.set_rc(3, 2000) self.change_altitude(self.homeloc.alt+300) # fly the roll in manual self.change_mode('MANUAL') while count > 0: self.progress("Starting roll") self.set_rc(1, 1000) try: self.wait_roll(-150, accuracy=90) self.wait_roll(150, accuracy=90) self.wait_roll(0, accuracy=90) except Exception as e: self.set_rc(1, 1500) raise e count -= 1 # back to FBWA self.set_rc(1, 1500) self.change_mode('FBWA') self.set_rc(3, 1700) return self.wait_level_flight() def inside_loop(self, count=1): """Fly a inside loop.""" # full throttle! self.set_rc(3, 2000) self.change_altitude(self.homeloc.alt+300) # fly the loop in manual self.change_mode('MANUAL') while count > 0: self.progress("Starting loop") self.set_rc(2, 1000) self.wait_pitch(-60, accuracy=20) self.wait_pitch(0, accuracy=20) count -= 1 # back to FBWA self.set_rc(2, 1500) self.change_mode('FBWA') self.set_rc(3, 1700) return self.wait_level_flight() def set_attitude_target(self, tolerance=10): """Test setting of attitude target in guided mode.""" self.change_mode("GUIDED") # self.set_parameter("STALL_PREVENTION", 0) state_roll_over = "roll-over" state_stabilize_roll = "stabilize-roll" state_hold = "hold" state_roll_back = "roll-back" state_done = "done" tstart = self.get_sim_time() try: state = state_roll_over while state != state_done: m = self.mav.recv_match(type='ATTITUDE', blocking=True, timeout=0.1) now = self.get_sim_time_cached() if now - tstart > 20: raise AutoTestTimeoutException("Manuevers not completed") if m is None: continue r = math.degrees(m.roll) if state == state_roll_over: target_roll_degrees = 60 if abs(r - target_roll_degrees) < tolerance: state = state_stabilize_roll stabilize_start = now elif state == state_stabilize_roll: # just give it a little time to sort it self out if now - stabilize_start > 2: state = state_hold hold_start = now elif state == state_hold: target_roll_degrees = 60 if now - hold_start > tolerance: state = state_roll_back if abs(r - target_roll_degrees) > tolerance: raise NotAchievedException("Failed to hold attitude") elif state == state_roll_back: target_roll_degrees = 0 if abs(r - target_roll_degrees) < tolerance: state = state_done else: raise ValueError("Unknown state %s" % str(state)) m_nav = self.mav.messages['NAV_CONTROLLER_OUTPUT'] self.progress("%s Roll: %f desired=%f set=%f" % (state, r, m_nav.nav_roll, target_roll_degrees)) time_boot_millis = 0 # FIXME target_system = 1 # FIXME target_component = 1 # FIXME type_mask = 0b10000001 ^ 0xFF # FIXME # attitude in radians: q = quaternion.Quaternion([math.radians(target_roll_degrees), 0, 0]) roll_rate_radians = 0.5 pitch_rate_radians = 0 yaw_rate_radians = 0 thrust = 1.0 self.mav.mav.set_attitude_target_send(time_boot_millis, target_system, target_component, type_mask, q, roll_rate_radians, pitch_rate_radians, yaw_rate_radians, thrust) except Exception as e: self.change_mode('FBWA') self.set_rc(3, 1700) raise e # back to FBWA self.change_mode('FBWA') self.set_rc(3, 1700) self.wait_level_flight() def test_stabilize(self, count=1): """Fly stabilize mode.""" # full throttle! self.set_rc(3, 2000) self.set_rc(2, 1300) self.change_altitude(self.homeloc.alt+300) self.set_rc(2, 1500) self.change_mode('STABILIZE') while count > 0: self.progress("Starting roll") self.set_rc(1, 2000) self.wait_roll(-150, accuracy=90) self.wait_roll(150, accuracy=90) self.wait_roll(0, accuracy=90) count -= 1 self.set_rc(1, 1500) self.wait_roll(0, accuracy=5) # back to FBWA self.change_mode('FBWA') self.set_rc(3, 1700) return self.wait_level_flight() def test_acro(self, count=1): """Fly ACRO mode.""" # full throttle! self.set_rc(3, 2000) self.set_rc(2, 1300) self.change_altitude(self.homeloc.alt+300) self.set_rc(2, 1500) self.change_mode('ACRO') while count > 0: self.progress("Starting roll") self.set_rc(1, 1000) self.wait_roll(-150, accuracy=90) self.wait_roll(150, accuracy=90) self.wait_roll(0, accuracy=90) count -= 1 self.set_rc(1, 1500) # back to FBWA self.change_mode('FBWA') self.wait_level_flight() self.change_mode('ACRO') count = 2 while count > 0: self.progress("Starting loop") self.set_rc(2, 1000) self.wait_pitch(-60, accuracy=20) self.wait_pitch(0, accuracy=20) count -= 1 self.set_rc(2, 1500) # back to FBWA self.change_mode('FBWA') self.set_rc(3, 1700) return self.wait_level_flight() def test_FBWB(self, mode='FBWB'): """Fly FBWB or CRUISE mode.""" self.change_mode(mode) self.set_rc(3, 1700) self.set_rc(2, 1500) # lock in the altitude by asking for an altitude change then releasing self.set_rc(2, 1000) self.wait_distance(50, accuracy=20) self.set_rc(2, 1500) self.wait_distance(50, accuracy=20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) initial_alt = m.alt self.progress("Initial altitude %u\n" % initial_alt) self.progress("Flying right circuit") # do 4 turns for i in range(0, 4): # hard left self.progress("Starting turn %u" % i) self.set_rc(1, 1800) try: self.wait_heading(0 + (90*i), accuracy=20, timeout=60) except Exception as e: self.set_rc(1, 1500) raise e self.set_rc(1, 1500) self.progress("Starting leg %u" % i) self.wait_distance(100, accuracy=20) self.progress("Circuit complete") self.progress("Flying rudder left circuit") # do 4 turns for i in range(0, 4): # hard left self.progress("Starting turn %u" % i) self.set_rc(4, 1900) try: self.wait_heading(360 - (90*i), accuracy=20, timeout=60) except Exception as e: self.set_rc(4, 1500) raise e self.set_rc(4, 1500) self.progress("Starting leg %u" % i) self.wait_distance(100, accuracy=20) self.progress("Circuit complete") m = self.mav.recv_match(type='VFR_HUD', blocking=True) final_alt = m.alt self.progress("Final altitude %u initial %u\n" % (final_alt, initial_alt)) # back to FBWA self.change_mode('FBWA') if abs(final_alt - initial_alt) > 20: raise NotAchievedException("Failed to maintain altitude") return self.wait_level_flight() def fly_mission(self, filename, mission_timeout=60.0, strict=True, quadplane=False): """Fly a mission from a file.""" self.progress("Flying mission %s" % filename) num_wp = self.load_mission(filename, strict=strict)-1 self.set_current_waypoint(0, check_afterwards=False) self.change_mode('AUTO') self.wait_waypoint(1, num_wp, max_dist=60, timeout=mission_timeout) self.wait_groundspeed(0, 0.5, timeout=mission_timeout) if quadplane: self.wait_statustext("Throttle disarmed", timeout=200) else: self.wait_statustext("Auto disarmed", timeout=60) self.progress("Mission OK") def fly_do_reposition(self): self.progress("Takeoff") self.takeoff(alt=50) self.set_rc(3, 1500) self.progress("Entering guided and flying somewhere constant") self.change_mode("GUIDED") loc = self.mav.location() self.location_offset_ne(loc, 500, 500) new_alt = 100 self.run_cmd_int( mavutil.mavlink.MAV_CMD_DO_REPOSITION, 0, 0, 0, 0, int(loc.lat * 1e7), int(loc.lng * 1e7), new_alt, # alt frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, ) self.wait_altitude(new_alt-10, new_alt, timeout=30, relative=True) self.fly_home_land_and_disarm() def fly_deepstall(self): # self.fly_deepstall_absolute() self.fly_deepstall_relative() def fly_deepstall_absolute(self): self.start_subtest("DeepStall Relative Absolute") self.set_parameter("LAND_TYPE", 1) deepstall_elevator_pwm = 1661 self.set_parameter("LAND_DS_ELEV_PWM", deepstall_elevator_pwm) self.load_mission("plane-deepstall-mission.txt") self.change_mode("AUTO") self.wait_ready_to_arm() self.arm_vehicle() self.progress("Waiting for deepstall messages") self.wait_text("Deepstall: Entry: ", timeout=240) # assume elevator is on channel 2: self.wait_servo_channel_value(2, deepstall_elevator_pwm) self.disarm_wait(timeout=120) self.progress("Flying home") self.takeoff(10) self.set_parameter("LAND_TYPE", 0) self.fly_home_land_and_disarm() def fly_deepstall_relative(self): self.start_subtest("DeepStall Relative") self.set_parameter("LAND_TYPE", 1) deepstall_elevator_pwm = 1661 self.set_parameter("LAND_DS_ELEV_PWM", deepstall_elevator_pwm) self.load_mission("plane-deepstall-relative-mission.txt") self.change_mode("AUTO") self.wait_ready_to_arm() self.arm_vehicle() self.progress("Waiting for deepstall messages") self.wait_text("Deepstall: Entry: ", timeout=240) # assume elevator is on channel 2: self.wait_servo_channel_value(2, deepstall_elevator_pwm) self.disarm_wait(timeout=120) self.progress("Flying home") self.takeoff(100) self.set_parameter("LAND_TYPE", 0) self.fly_home_land_and_disarm(timeout=240) def SmartBattery(self): self.set_parameters({ "BATT_MONITOR": 16, # Maxell battery monitor }) # Must reboot sitl after setting montior type for SMBus parameters to be set due to dynamic group self.reboot_sitl() self.set_parameters({ "BATT_I2C_BUS": 2, # specified in SIM_I2C.cpp "BATT_I2C_ADDR": 11, # specified in SIM_I2C.cpp }) self.reboot_sitl() self.wait_ready_to_arm() m = self.assert_receive_message('BATTERY_STATUS', timeout=10) if m.voltages_ext[0] == 65536: raise NotAchievedException("Flag value rather than voltage") if abs(m.voltages_ext[0] - 1000) > 300: raise NotAchievedException("Did not get good ext voltage (got=%f)" % (m.voltages_ext[0],)) self.arm_vehicle() self.delay_sim_time(5) self.disarm_vehicle() if not self.current_onboard_log_contains_message("BCL2"): raise NotAchievedException("Expected BCL2 message") def fly_do_change_speed(self): # the following lines ensure we revert these parameter values # - DO_CHANGE_AIRSPEED is a permanent vehicle change! self.set_parameters({ "TRIM_ARSPD_CM": self.get_parameter("TRIM_ARSPD_CM"), "MIN_GNDSPD_CM": self.get_parameter("MIN_GNDSPD_CM"), }) self.progress("Takeoff") self.takeoff(alt=100) self.set_rc(3, 1500) # ensure we know what the airspeed is: self.progress("Entering guided and flying somewhere constant") self.change_mode("GUIDED") self.run_cmd_int( mavutil.mavlink.MAV_CMD_DO_REPOSITION, 0, 0, 0, 0, 12345, # lat* 1e7 12345, # lon* 1e7 100 # alt ) self.delay_sim_time(10) self.progress("Ensuring initial speed is known and relatively constant") initial_speed = 21.5 timeout = 10 tstart = self.get_sim_time() while True: if self.get_sim_time_cached() - tstart > timeout: break m = self.mav.recv_match(type='VFR_HUD', blocking=True) self.progress("GroundSpeed: %f want=%f" % (m.groundspeed, initial_speed)) if abs(initial_speed - m.groundspeed) > 1: raise NotAchievedException("Initial speed not as expected (want=%f got=%f" % (initial_speed, m.groundspeed)) self.progress("Setting groundspeed") new_target_groundspeed = initial_speed + 5 self.run_cmd( mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, 1, # groundspeed new_target_groundspeed, -1, # throttle / no change 0, # absolute values 0, 0, 0) self.wait_groundspeed(new_target_groundspeed-0.5, new_target_groundspeed+0.5, timeout=40) self.progress("Adding some wind, ensuring groundspeed holds") self.set_parameter("SIM_WIND_SPD", 5) self.delay_sim_time(5) self.wait_groundspeed(new_target_groundspeed-0.5, new_target_groundspeed+0.5, timeout=40) self.set_parameter("SIM_WIND_SPD", 0) self.progress("Setting airspeed") new_target_airspeed = initial_speed + 5 self.run_cmd( mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, 0, # airspeed new_target_airspeed, -1, # throttle / no change 0, # absolute values 0, 0, 0) self.wait_groundspeed(new_target_airspeed-0.5, new_target_airspeed+0.5) self.progress("Adding some wind, hoping groundspeed increases/decreases") self.set_parameters({ "SIM_WIND_SPD": 5, "SIM_WIND_DIR": 270, }) self.delay_sim_time(5) timeout = 10 tstart = self.get_sim_time() while True: if self.get_sim_time_cached() - tstart > timeout: raise NotAchievedException("Did not achieve groundspeed delta") m = self.mav.recv_match(type='VFR_HUD', blocking=True) delta = abs(m.airspeed - m.groundspeed) want_delta = 4 self.progress("groundspeed and airspeed should be different (have=%f want=%f)" % (delta, want_delta)) if delta > want_delta: break self.fly_home_land_and_disarm(timeout=240) def fly_home_land_and_disarm(self, timeout=120): filename = "flaps.txt" self.progress("Using %s to fly home" % filename) self.load_generic_mission(filename) self.change_mode("AUTO") # don't set current waypoint to 8 unless we're distant from it # or we arrive instantly and never see it as our current # waypoint: self.wait_distance_to_waypoint(8, 100, 10000000) self.set_current_waypoint(8) self.drain_mav() # TODO: reflect on file to find this magic waypoint number? # self.wait_waypoint(7, num_wp-1, timeout=500) # we # tend to miss the final waypoint by a fair bit, and # this is probably too noisy anyway? self.wait_disarmed(timeout=timeout) def fly_flaps(self): """Test flaps functionality.""" filename = "flaps.txt" self.context_push() ex = None try: flaps_ch = 5 flaps_ch_min = 1000 flaps_ch_trim = 1500 flaps_ch_max = 2000 servo_ch = 5 servo_ch_min = 1200 servo_ch_trim = 1300 servo_ch_max = 1800 self.set_parameters({ "SERVO%u_FUNCTION" % servo_ch: 3, # flapsauto "RC%u_OPTION" % flaps_ch: 208, # Flaps RCx_OPTION "LAND_FLAP_PERCNT": 50, "LOG_DISARMED": 1, "RC%u_MIN" % flaps_ch: flaps_ch_min, "RC%u_MAX" % flaps_ch: flaps_ch_max, "RC%u_TRIM" % flaps_ch: flaps_ch_trim, "SERVO%u_MIN" % servo_ch: servo_ch_min, "SERVO%u_MAX" % servo_ch: servo_ch_max, "SERVO%u_TRIM" % servo_ch: servo_ch_trim, }) self.progress("check flaps are not deployed") self.set_rc(flaps_ch, flaps_ch_min) self.wait_servo_channel_value(servo_ch, servo_ch_min, timeout=3) self.progress("deploy the flaps") self.set_rc(flaps_ch, flaps_ch_max) tstart = self.get_sim_time() self.wait_servo_channel_value(servo_ch, servo_ch_max) tstop = self.get_sim_time_cached() delta_time = tstop - tstart delta_time_min = 0.5 delta_time_max = 1.5 if delta_time < delta_time_min or delta_time > delta_time_max: raise NotAchievedException(( "Flaps Slew not working (%f seconds)" % (delta_time,))) self.progress("undeploy flaps") self.set_rc(flaps_ch, flaps_ch_min) self.wait_servo_channel_value(servo_ch, servo_ch_min) self.progress("Flying mission %s" % filename) self.load_mission(filename) self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() last_mission_current_msg = 0 last_seq = None while self.armed(): m = self.mav.recv_match(type='MISSION_CURRENT', blocking=True) time_delta = (self.get_sim_time_cached() - last_mission_current_msg) if (time_delta > 1 or m.seq != last_seq): dist = None x = self.mav.messages.get("NAV_CONTROLLER_OUTPUT", None) if x is not None: dist = x.wp_dist self.progress("MISSION_CURRENT.seq=%u (dist=%s)" % (m.seq, str(dist))) last_mission_current_msg = self.get_sim_time_cached() last_seq = m.seq # flaps should undeploy at the end self.wait_servo_channel_value(servo_ch, servo_ch_min, timeout=30) # do a short flight in FBWA, watching for flaps # self.mavproxy.send('switch 4\n') # self.wait_mode('FBWA') # self.delay_sim_time(10) # self.mavproxy.send('switch 6\n') # self.wait_mode('MANUAL') # self.delay_sim_time(10) self.progress("Flaps OK") except Exception as e: self.print_exception_caught(e) ex = e self.context_pop() if ex: if self.armed(): self.disarm_vehicle() raise ex def test_rc_relay(self): '''test toggling channel 12 toggles relay''' self.set_parameter("RC12_OPTION", 28) # Relay On/Off self.set_rc(12, 1000) self.reboot_sitl() # needed for RC12_OPTION to take effect off = self.get_parameter("SIM_PIN_MASK") if off: raise PreconditionFailedException("SIM_MASK_PIN off") # allow time for the RC library to register initial value: self.delay_sim_time(1) self.set_rc(12, 2000) self.wait_heartbeat() self.wait_heartbeat() on = self.get_parameter("SIM_PIN_MASK") if not on: raise NotAchievedException("SIM_PIN_MASK doesn't reflect ON") self.set_rc(12, 1000) self.wait_heartbeat() self.wait_heartbeat() off = self.get_parameter("SIM_PIN_MASK") if off: raise NotAchievedException("SIM_PIN_MASK doesn't reflect OFF") def test_rc_option_camera_trigger(self): '''test toggling channel 12 takes picture''' self.set_parameter("RC12_OPTION", 9) # CameraTrigger self.reboot_sitl() # needed for RC12_OPTION to take effect x = self.mav.messages.get("CAMERA_FEEDBACK", None) if x is not None: raise PreconditionFailedException("Receiving CAMERA_FEEDBACK?!") self.set_rc(12, 2000) tstart = self.get_sim_time() while self.get_sim_time_cached() - tstart < 10: x = self.mav.messages.get("CAMERA_FEEDBACK", None) if x is not None: break self.wait_heartbeat() self.set_rc(12, 1000) if x is None: raise NotAchievedException("No CAMERA_FEEDBACK message received") self.wait_ready_to_arm() original_alt = self.get_altitude() takeoff_alt = 30 self.takeoff(takeoff_alt) self.set_rc(12, 2000) self.delay_sim_time(1) self.set_rc(12, 1000) x = self.mav.messages.get("CAMERA_FEEDBACK", None) if abs(x.alt_rel - takeoff_alt) > 10: raise NotAchievedException("Bad relalt (want=%f vs got=%f)" % (takeoff_alt, x.alt_rel)) if abs(x.alt_msl - (original_alt+30)) > 10: raise NotAchievedException("Bad absalt (want=%f vs got=%f)" % (original_alt+30, x.alt_msl)) self.fly_home_land_and_disarm() def test_throttle_failsafe(self): self.change_mode('MANUAL') m = self.mav.recv_match(type='SYS_STATUS', blocking=True) receiver_bit = mavutil.mavlink.MAV_SYS_STATUS_SENSOR_RC_RECEIVER self.progress("Testing receiver enabled") if (not (m.onboard_control_sensors_enabled & receiver_bit)): raise PreconditionFailedException() self.progress("Testing receiver present") if (not (m.onboard_control_sensors_present & receiver_bit)): raise PreconditionFailedException() self.progress("Testing receiver health") if (not (m.onboard_control_sensors_health & receiver_bit)): raise PreconditionFailedException() self.progress("Ensure we know original throttle value") self.wait_rc_channel_value(3, 1000) self.set_parameter("THR_FS_VALUE", 960) self.progress("Failing receiver (throttle-to-950)") self.context_collect("HEARTBEAT") self.set_parameter("SIM_RC_FAIL", 2) # throttle-to-950 self.wait_mode('RTL') # long failsafe if (not self.get_mode_from_mode_mapping("CIRCLE") in [x.custom_mode for x in self.context_stop_collecting("HEARTBEAT")]): raise NotAchievedException("Did not go via circle mode") self.progress("Ensure we've had our throttle squashed to 950") self.wait_rc_channel_value(3, 950) self.drain_mav_unparsed() m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) self.progress("Testing receiver enabled") if (not (m.onboard_control_sensors_enabled & receiver_bit)): raise NotAchievedException("Receiver not enabled") self.progress("Testing receiver present") if (not (m.onboard_control_sensors_present & receiver_bit)): raise NotAchievedException("Receiver not present") # skip this until RC is fixed # self.progress("Testing receiver health") # if (m.onboard_control_sensors_health & receiver_bit): # raise NotAchievedException("Sensor healthy when it shouldn't be") self.set_parameter("SIM_RC_FAIL", 0) self.drain_mav_unparsed() # have to allow time for RC to be fetched from SITL self.delay_sim_time(0.5) m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Testing receiver enabled") if (not (m.onboard_control_sensors_enabled & receiver_bit)): raise NotAchievedException("Receiver not enabled") self.progress("Testing receiver present") if (not (m.onboard_control_sensors_present & receiver_bit)): raise NotAchievedException("Receiver not present") self.progress("Testing receiver health") if (not (m.onboard_control_sensors_health & receiver_bit)): raise NotAchievedException("Receiver not healthy2") self.change_mode('MANUAL') self.progress("Failing receiver (no-pulses)") self.context_collect("HEARTBEAT") self.set_parameter("SIM_RC_FAIL", 1) # no-pulses self.wait_mode('RTL') # long failsafe if (not self.get_mode_from_mode_mapping("CIRCLE") in [x.custom_mode for x in self.context_stop_collecting("HEARTBEAT")]): raise NotAchievedException("Did not go via circle mode") self.drain_mav_unparsed() m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) self.progress("Testing receiver enabled") if (not (m.onboard_control_sensors_enabled & receiver_bit)): raise NotAchievedException("Receiver not enabled") self.progress("Testing receiver present") if (not (m.onboard_control_sensors_present & receiver_bit)): raise NotAchievedException("Receiver not present") self.progress("Testing receiver health") if (m.onboard_control_sensors_health & receiver_bit): raise NotAchievedException("Sensor healthy when it shouldn't be") self.progress("Making RC work again") self.set_parameter("SIM_RC_FAIL", 0) # have to allow time for RC to be fetched from SITL self.progress("Giving receiver time to recover") self.delay_sim_time(0.5) self.drain_mav_unparsed() m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Testing receiver enabled") if (not (m.onboard_control_sensors_enabled & receiver_bit)): raise NotAchievedException("Receiver not enabled") self.progress("Testing receiver present") if (not (m.onboard_control_sensors_present & receiver_bit)): raise NotAchievedException("Receiver not present") self.progress("Testing receiver health") if (not (m.onboard_control_sensors_health & receiver_bit)): raise NotAchievedException("Receiver not healthy") self.change_mode('MANUAL') self.progress("Ensure long failsafe can trigger when short failsafe disabled") self.context_push() self.context_collect("STATUSTEXT") ex = None try: self.set_parameters({ "FS_SHORT_ACTN": 3, # 3 means disabled "SIM_RC_FAIL": 1, }) self.wait_statustext("Long event on", check_context=True) self.wait_mode("RTL") # self.context_clear_collection("STATUSTEXT") self.set_parameter("SIM_RC_FAIL", 0) self.wait_text("Long event off", check_context=True) self.change_mode("MANUAL") self.progress("Trying again with THR_FS_VALUE") self.set_parameters({ "THR_FS_VALUE": 960, "SIM_RC_FAIL": 2, }) self.wait_statustext("Long event on", check_context=True) self.wait_mode("RTL") except Exception as e: self.print_exception_caught(e) ex = e self.context_pop() if ex is not None: raise ex def test_throttle_failsafe_fence(self): fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE self.progress("Checking fence is not present before being configured") m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) if (m.onboard_control_sensors_enabled & fence_bit): raise NotAchievedException("Fence enabled before being configured") self.change_mode('MANUAL') self.wait_ready_to_arm() self.load_fence("CMAC-fence.txt") self.set_parameter("RC7_OPTION", 11) # AC_Fence uses Aux switch functionality self.set_parameter("FENCE_ACTION", 4) # Fence action Brake self.set_rc_from_map({ 3: 1000, 7: 2000, }) # Turn fence on with aux function m = self.mav.recv_match(type='FENCE_STATUS', blocking=True, timeout=2) self.progress("Got (%s)" % str(m)) if m is None: raise NotAchievedException("Got FENCE_STATUS unexpectedly") self.progress("Checking fence is initially OK") self.wait_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE, present=True, enabled=True, healthy=True, verbose=True, timeout=30) self.set_parameter("THR_FS_VALUE", 960) self.progress("Failing receiver (throttle-to-950)") self.set_parameter("SIM_RC_FAIL", 2) # throttle-to-950 self.wait_mode("CIRCLE") self.delay_sim_time(1) # give self.drain_mav_unparsed() self.progress("Checking fence is OK after receiver failure (bind-values)") fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) if (not (m.onboard_control_sensors_enabled & fence_bit)): raise NotAchievedException("Fence not enabled after RC fail") self.do_fence_disable() # Ensure the fence is disabled after test def test_gripper_mission(self): self.context_push() ex = None try: self.load_mission("plane-gripper-mission.txt") self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() self.wait_statustext("Gripper Grabbed", timeout=60) self.wait_statustext("Gripper Released", timeout=60) self.wait_statustext("Auto disarmed", timeout=60) except Exception as e: self.print_exception_caught(e) ex = e self.context_pop() if ex is not None: raise ex def assert_fence_sys_status(self, present, enabled, health): self.delay_sim_time(1) self.drain_mav_unparsed() m = self.assert_receive_message('SYS_STATUS', timeout=1) tests = [ ("present", present, m.onboard_control_sensors_present), ("enabled", enabled, m.onboard_control_sensors_enabled), ("health", health, m.onboard_control_sensors_health), ] bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE for test in tests: (name, want, field) = test got = (field & bit) != 0 if want != got: raise NotAchievedException("fence status incorrect; %s want=%u got=%u" % (name, want, got)) def wait_circling_point_with_radius(self, loc, want_radius, epsilon=5.0, min_circle_time=5, timeout=120): on_radius_start_heading = None average_radius = 0.0 circle_time_start = 0 done_time = False done_angle = False tstart = self.get_sim_time() while True: if self.get_sim_time() - tstart > timeout: raise AutoTestTimeoutException("Did not get onto circle") here = self.mav.location() got_radius = self.get_distance(loc, here) average_radius = 0.95*average_radius + 0.05*got_radius on_radius = abs(got_radius - want_radius) < epsilon m = self.mav.recv_match(type='VFR_HUD', blocking=True) heading = m.heading on_string = "off" got_angle = "" if on_radius_start_heading is not None: got_angle = "%0.2f" % abs(on_radius_start_heading - heading) # FIXME on_string = "on" want_angle = 180 # we don't actually get this (angle-substraction issue. But we get enough... self.progress("wait-circling: got-r=%0.2f want-r=%f avg-r=%f %s want-a=%0.1f got-a=%s" % (got_radius, want_radius, average_radius, on_string, want_angle, got_angle)) if on_radius: if on_radius_start_heading is None: on_radius_start_heading = heading average_radius = got_radius circle_time_start = self.get_sim_time() continue if abs(on_radius_start_heading - heading) > want_angle: # FIXME done_angle = True if self.get_sim_time() - circle_time_start > min_circle_time: done_time = True if done_time and done_angle: return continue if on_radius_start_heading is not None: average_radius = 0.0 on_radius_start_heading = None circle_time_start = 0 def test_fence_static(self): ex = None try: self.progress("Checking for bizarre healthy-when-not-present-or-enabled") self.set_parameter("FENCE_TYPE", 4) # Start by only setting polygon fences, otherwise fence will report present self.assert_fence_sys_status(False, False, True) self.load_fence("CMAC-fence.txt") m = self.mav.recv_match(type='FENCE_STATUS', blocking=True, timeout=2) if m is not None: raise NotAchievedException("Got FENCE_STATUS unexpectedly") self.drain_mav_unparsed() self.set_parameter("FENCE_ACTION", 0) # report only self.assert_fence_sys_status(True, False, True) self.set_parameter("FENCE_ACTION", 1) # RTL self.assert_fence_sys_status(True, False, True) self.do_fence_enable() self.assert_fence_sys_status(True, True, True) m = self.assert_receive_message('FENCE_STATUS', timeout=2) if m.breach_status: raise NotAchievedException("Breached fence unexpectedly (%u)" % (m.breach_status)) self.do_fence_disable() self.assert_fence_sys_status(True, False, True) self.set_parameter("FENCE_ACTION", 1) self.assert_fence_sys_status(True, False, True) self.set_parameter("FENCE_ACTION", 0) self.assert_fence_sys_status(True, False, True) self.clear_fence() if self.get_parameter("FENCE_TOTAL") != 0: raise NotAchievedException("Expected zero points remaining") self.assert_fence_sys_status(False, False, True) self.progress("Trying to enable fence with no points") self.do_fence_enable(want_result=mavutil.mavlink.MAV_RESULT_FAILED) # test a rather unfortunate behaviour: self.progress("Killing a live fence with fence-clear") self.load_fence("CMAC-fence.txt") self.set_parameter("FENCE_ACTION", 1) # AC_FENCE_ACTION_RTL_AND_LAND == 1. mavutil.mavlink.FENCE_ACTION_RTL == 4 self.do_fence_enable() self.assert_fence_sys_status(True, True, True) self.clear_fence() self.wait_sensor_state(mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE, False, False, True) if self.get_parameter("FENCE_TOTAL") != 0: raise NotAchievedException("Expected zero points remaining") self.assert_fence_sys_status(False, False, True) self.do_fence_disable() # ensure that a fence is present if it is tin can, min alt or max alt self.progress("Test other fence types (tin-can, min alt, max alt") self.set_parameter("FENCE_TYPE", 1) # max alt self.assert_fence_sys_status(True, False, True) self.set_parameter("FENCE_TYPE", 8) # min alt self.assert_fence_sys_status(True, False, True) self.set_parameter("FENCE_TYPE", 2) # tin can self.assert_fence_sys_status(True, False, True) # Test cannot arm if outside of fence and fence is enabled self.progress("Test Arming while vehicle below FENCE_ALT_MIN") default_fence_alt_min = self.get_parameter("FENCE_ALT_MIN") self.set_parameter("FENCE_ALT_MIN", 50) self.set_parameter("FENCE_TYPE", 8) # Enables minimum altitude breaches self.do_fence_enable() self.delay_sim_time(2) # Allow breach to propagate self.assert_fence_enabled() self.try_arm(False, "vehicle outside fence") self.do_fence_disable() self.set_parameter("FENCE_ALT_MIN", default_fence_alt_min) # Test arming outside inclusion zone self.progress("Test arming while vehicle outside of inclusion zone") self.set_parameter("FENCE_TYPE", 4) # Enables polygon fence types locs = [ mavutil.location(1.000, 1.000, 0, 0), mavutil.location(1.000, 1.001, 0, 0), mavutil.location(1.001, 1.001, 0, 0), mavutil.location(1.001, 1.000, 0, 0) ] self.upload_fences_from_locations( mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION, [ locs ] ) self.delay_sim_time(10) # let fence check run so it loads-from-eeprom self.do_fence_enable() self.assert_fence_enabled() self.delay_sim_time(2) # Allow breach to propagate self.try_arm(False, "vehicle outside fence") self.do_fence_disable() self.clear_fence() self.progress("Test arming while vehicle inside exclusion zone") self.set_parameter("FENCE_TYPE", 4) # Enables polygon fence types home_loc = self.mav.location() locs = [ mavutil.location(home_loc.lat - 0.001, home_loc.lng - 0.001, 0, 0), mavutil.location(home_loc.lat - 0.001, home_loc.lng + 0.001, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng + 0.001, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng - 0.001, 0, 0), ] self.upload_fences_from_locations( mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, [ locs ] ) self.delay_sim_time(10) # let fence check run so it loads-from-eeprom self.do_fence_enable() self.assert_fence_enabled() self.delay_sim_time(2) # Allow breach to propagate self.try_arm(False, "vehicle outside fence") self.do_fence_disable() self.clear_fence() except Exception as e: self.print_exception_caught(e) ex = e self.clear_fence() if ex is not None: raise ex def test_fence_breach_circle_at(self, loc, disable_on_breach=False): ex = None try: self.load_fence("CMAC-fence.txt") want_radius = 100 # when ArduPlane is fixed, remove this fudge factor REALLY_BAD_FUDGE_FACTOR = 1.16 expected_radius = REALLY_BAD_FUDGE_FACTOR * want_radius self.set_parameters({ "RTL_RADIUS": want_radius, "NAVL1_LIM_BANK": 60, "FENCE_ACTION": 1, # AC_FENCE_ACTION_RTL_AND_LAND == 1. mavutil.mavlink.FENCE_ACTION_RTL == 4 }) self.wait_ready_to_arm() # need an origin to load fence self.do_fence_enable() self.assert_fence_sys_status(True, True, True) self.takeoff(alt=45, alt_max=300) tstart = self.get_sim_time() while True: if self.get_sim_time() - tstart > 30: raise NotAchievedException("Did not breach fence") m = self.assert_receive_message('FENCE_STATUS', timeout=2) if m.breach_status == 0: continue # we've breached; check our state; if m.breach_type != mavutil.mavlink.FENCE_BREACH_BOUNDARY: raise NotAchievedException("Unexpected breach type %u" % (m.breach_type,)) if m.breach_count == 0: raise NotAchievedException("Unexpected breach count %u" % (m.breach_count,)) self.assert_fence_sys_status(True, True, False) break if disable_on_breach: self.do_fence_disable() self.wait_circling_point_with_radius(loc, expected_radius) self.disarm_vehicle(force=True) self.reboot_sitl() except Exception as e: self.print_exception_caught(e) ex = e self.clear_fence() if ex is not None: raise ex def test_fence_rtl(self): self.progress("Testing FENCE_ACTION_RTL no rally point") # have to disable the fence once we've breached or we breach # it as part of the loiter-at-home! self.test_fence_breach_circle_at(self.home_position_as_mav_location(), disable_on_breach=True) def test_fence_rtl_rally(self): ex = None target_system = 1 target_component = 1 try: self.progress("Testing FENCE_ACTION_RTL with rally point") self.wait_ready_to_arm() loc = self.home_relative_loc_ne(50, -50) self.set_parameter("RALLY_TOTAL", 1) self.mav.mav.rally_point_send(target_system, target_component, 0, # sequence number 1, # total count int(loc.lat * 1e7), int(loc.lng * 1e7), 15, 0, # "break" alt?! 0, # "land dir" 0) # flags self.delay_sim_time(1) if self.mavproxy is not None: self.mavproxy.send("rally list\n") self.test_fence_breach_circle_at(loc) except Exception as e: self.print_exception_caught(e) ex = e self.clear_mission(mavutil.mavlink.MAV_MISSION_TYPE_RALLY) if ex is not None: raise ex def test_fence_ret_rally(self): """ Tests the FENCE_RET_RALLY flag, either returning to fence return point, or rally point """ target_system = 1 target_component = 1 self.progress("Testing FENCE_ACTION_RTL with fence rally point") self.wait_ready_to_arm() self.homeloc = self.mav.location() # Grab a location for fence return point, and upload it. fence_loc = self.home_position_as_mav_location() self.location_offset_ne(fence_loc, 50, 50) fence_return_mission_items = [ self.mav.mav.mission_item_int_encode( target_system, target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL_INT, mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT, 0, # current 0, # autocontinue 0, # p1 0, # p2 0, # p3 0, # p4 int(fence_loc.lat * 1e7), # latitude int(fence_loc.lng * 1e7), # longitude 0, # altitude mavutil.mavlink.MAV_MISSION_TYPE_FENCE ) ] self.upload_using_mission_protocol(mavutil.mavlink.MAV_MISSION_TYPE_FENCE, fence_return_mission_items) self.delay_sim_time(1) # Grab a location for rally point, and upload it. rally_loc = self.home_relative_loc_ne(-50, 50) self.set_parameter("RALLY_TOTAL", 1) self.mav.mav.rally_point_send(target_system, target_component, 0, # sequence number 1, # total count int(rally_loc.lat * 1e7), int(rally_loc.lng * 1e7), 15, 0, # "break" alt?! 0, # "land dir" 0) # flags self.delay_sim_time(1) return_radius = 100 return_alt = 80 self.set_parameters({ "RTL_RADIUS": return_radius, "FENCE_ACTION": 6, # Set Fence Action to Guided "FENCE_TYPE": 8, # Only use fence floor "FENCE_RET_ALT": return_alt, }) self.do_fence_enable() self.assert_fence_enabled() self.takeoff(alt=50, alt_max=300) # Trigger fence breach, fly to rally location self.set_parameters({ "FENCE_RET_RALLY": 1, "FENCE_ALT_MIN": 60, }) self.wait_circling_point_with_radius(rally_loc, return_radius) self.set_parameter("FENCE_ALT_MIN", 0) # Clear fence breach # Fly up before re-triggering fence breach. Fly to fence return point self.change_altitude(self.homeloc.alt+30) self.set_parameters({ "FENCE_RET_RALLY": 0, "FENCE_ALT_MIN": 60, }) self.wait_altitude(altitude_min=return_alt-3, altitude_max=return_alt+3, relative=True) self.wait_circling_point_with_radius(fence_loc, return_radius) self.do_fence_disable() # Disable fence so we can land self.fly_home_land_and_disarm() # Pack it up, we're going home. def test_parachute(self): self.set_rc(9, 1000) self.set_parameters({ "CHUTE_ENABLED": 1, "CHUTE_TYPE": 10, "SERVO9_FUNCTION": 27, "SIM_PARA_ENABLE": 1, "SIM_PARA_PIN": 9, }) self.load_mission("plane-parachute-mission.txt") self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() self.wait_statustext("BANG", timeout=60) self.disarm_vehicle(force=True) self.reboot_sitl() def test_parachute_sinkrate(self): self.set_rc(9, 1000) self.set_parameters({ "CHUTE_ENABLED": 1, "CHUTE_TYPE": 10, "SERVO9_FUNCTION": 27, "SIM_PARA_ENABLE": 1, "SIM_PARA_PIN": 9, "CHUTE_CRT_SINK": 9, }) self.progress("Takeoff") self.takeoff(alt=300) self.progress("Diving") self.set_rc(2, 2000) self.wait_statustext("BANG", timeout=60) self.disarm_vehicle(force=True) self.reboot_sitl() def run_subtest(self, desc, func): self.start_subtest(desc) func() def check_attitudes_match(self, a, b): '''make sure ahrs2 and simstate and ATTTIUDE_QUATERNION all match''' # these are ordered to bookend the list with timestamps (which # both attitude messages have): get_names = ['ATTITUDE', 'SIMSTATE', 'AHRS2', 'ATTITUDE_QUATERNION'] msgs = self.get_messages_frame(get_names) for get_name in get_names: self.progress("%s: %s" % (get_name, msgs[get_name])) simstate = msgs['SIMSTATE'] attitude = msgs['ATTITUDE'] ahrs2 = msgs['AHRS2'] attitude_quaternion = msgs['ATTITUDE_QUATERNION'] # check ATTITUDE want = math.degrees(simstate.roll) got = math.degrees(attitude.roll) if abs(mavextra.angle_diff(want, got)) > 20: raise NotAchievedException("ATTITUDE.Roll looks bad (want=%f got=%f)" % (want, got)) want = math.degrees(simstate.pitch) got = math.degrees(attitude.pitch) if abs(mavextra.angle_diff(want, got)) > 20: raise NotAchievedException("ATTITUDE.Pitch looks bad (want=%f got=%f)" % (want, got)) # check AHRS2 want = math.degrees(simstate.roll) got = math.degrees(ahrs2.roll) if abs(mavextra.angle_diff(want, got)) > 20: raise NotAchievedException("AHRS2.Roll looks bad (want=%f got=%f)" % (want, got)) want = math.degrees(simstate.pitch) got = math.degrees(ahrs2.pitch) if abs(mavextra.angle_diff(want, got)) > 20: raise NotAchievedException("AHRS2.Pitch looks bad (want=%f got=%f)" % (want, got)) # check ATTITUDE_QUATERNION q = quaternion.Quaternion([ attitude_quaternion.q1, attitude_quaternion.q2, attitude_quaternion.q3, attitude_quaternion.q4 ]) euler = q.euler self.progress("attquat:%s q:%s euler:%s" % ( str(attitude_quaternion), q, euler)) want = math.degrees(simstate.roll) got = math.degrees(euler[0]) if mavextra.angle_diff(want, got) > 20: raise NotAchievedException("quat roll differs from attitude roll; want=%f got=%f" % (want, got)) want = math.degrees(simstate.pitch) got = math.degrees(euler[1]) if mavextra.angle_diff(want, got) > 20: raise NotAchievedException("quat pitch differs from attitude pitch; want=%f got=%f" % (want, got)) def fly_ahrs2_test(self): '''check secondary estimator is looking OK''' ahrs2 = self.mav.recv_match(type='AHRS2', blocking=True, timeout=1) if ahrs2 is None: raise NotAchievedException("Did not receive AHRS2 message") self.progress("AHRS2: %s" % str(ahrs2)) # check location gpi = self.mav.recv_match( type='GLOBAL_POSITION_INT', blocking=True, timeout=5 ) if gpi is None: raise NotAchievedException("Did not receive GLOBAL_POSITION_INT message") self.progress("GPI: %s" % str(gpi)) if self.get_distance_int(gpi, ahrs2) > 10: raise NotAchievedException("Secondary location looks bad") self.check_attitudes_match(1, 2) def test_main_flight(self): self.change_mode('MANUAL') self.progress("Asserting we do support transfer of fence via mission item protocol") self.assert_capability(mavutil.mavlink.MAV_PROTOCOL_CAPABILITY_MISSION_FENCE) # grab home position: self.mav.recv_match(type='HOME_POSITION', blocking=True) self.homeloc = self.mav.location() self.run_subtest("Takeoff", self.takeoff) self.run_subtest("Set Attitude Target", self.set_attitude_target) self.run_subtest("Fly left circuit", self.fly_left_circuit) self.run_subtest("Left roll", lambda: self.axial_left_roll(1)) self.run_subtest("Inside loop", self.inside_loop) self.run_subtest("Stablize test", self.test_stabilize) self.run_subtest("ACRO test", self.test_acro) self.run_subtest("FBWB test", self.test_FBWB) self.run_subtest("CRUISE test", lambda: self.test_FBWB(mode='CRUISE')) self.run_subtest("RTL test", self.fly_RTL) self.run_subtest("LOITER test", self.fly_LOITER) self.run_subtest("CIRCLE test", self.fly_CIRCLE) self.run_subtest("AHRS2 test", self.fly_ahrs2_test) self.run_subtest("Mission test", lambda: self.fly_mission("ap1.txt", strict=False)) def airspeed_autocal(self): self.progress("Ensure no AIRSPEED_AUTOCAL on ground") self.set_parameter("ARSPD_AUTOCAL", 1) m = self.mav.recv_match(type='AIRSPEED_AUTOCAL', blocking=True, timeout=5) if m is not None: raise NotAchievedException("Got autocal on ground") mission_filepath = "flaps.txt" num_wp = self.load_mission(mission_filepath) self.wait_ready_to_arm() self.arm_vehicle() self.change_mode("AUTO") self.progress("Ensure AIRSPEED_AUTOCAL in air") m = self.mav.recv_match(type='AIRSPEED_AUTOCAL', blocking=True, timeout=5) self.wait_waypoint(7, num_wp-1, max_dist=5, timeout=500) self.wait_disarmed(timeout=120) def deadreckoning_main(self, disable_airspeed_sensor=False): self.wait_ready_to_arm() self.gpi = None self.simstate = None self.last_print = 0 self.max_divergence = 0 def validate_global_position_int_against_simstate(mav, m): if m.get_type() == 'GLOBAL_POSITION_INT': self.gpi = m elif m.get_type() == 'SIMSTATE': self.simstate = m if self.gpi is None: return if self.simstate is None: return divergence = self.get_distance_int(self.gpi, self.simstate) max_allowed_divergence = 200 if (time.time() - self.last_print > 1 or divergence > self.max_divergence): self.progress("position-estimate-divergence=%fm" % (divergence,)) self.last_print = time.time() if divergence > self.max_divergence: self.max_divergence = divergence if divergence > max_allowed_divergence: raise NotAchievedException( "global-position-int diverged from simstate by %fm (max=%fm" % (divergence, max_allowed_divergence,)) self.install_message_hook(validate_global_position_int_against_simstate) try: # wind is from the West: self.set_parameter("SIM_WIND_DIR", 270) # light winds: self.set_parameter("SIM_WIND_SPD", 10) if disable_airspeed_sensor: self.set_parameter("ARSPD_USE", 0) self.takeoff(50) loc = self.mav.location() self.location_offset_ne(loc, 500, 500) self.run_cmd_int( mavutil.mavlink.MAV_CMD_DO_REPOSITION, 0, mavutil.mavlink.MAV_DO_REPOSITION_FLAGS_CHANGE_MODE, 0, 0, int(loc.lat * 1e7), int(loc.lng * 1e7), 100, # alt frame=mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, ) self.wait_location(loc, accuracy=100) self.progress("Stewing") self.delay_sim_time(20) self.set_parameter("SIM_GPS_DISABLE", 1) self.progress("Roasting") self.delay_sim_time(20) self.change_mode("RTL") self.wait_distance_to_home(100, 200, timeout=200) self.set_parameter("SIM_GPS_DISABLE", 0) self.delay_sim_time(10) self.set_rc(3, 1000) self.fly_home_land_and_disarm() self.progress("max-divergence: %fm" % (self.max_divergence,)) finally: self.remove_message_hook(validate_global_position_int_against_simstate) def deadreckoning(self): self.deadreckoning_main() def deadreckoning_no_airspeed_sensor(self): self.deadreckoning_main(disable_airspeed_sensor=True) def climb_before_turn(self): self.wait_ready_to_arm() self.set_parameters({ "FLIGHT_OPTIONS": 0, "ALT_HOLD_RTL": 8000, }) takeoff_alt = 10 self.takeoff(alt=takeoff_alt) self.change_mode("CRUISE") self.wait_distance_to_home(500, 1000, timeout=60) self.change_mode("RTL") expected_alt = self.get_parameter("ALT_HOLD_RTL") / 100.0 home = self.home_position_as_mav_location() distance = self.get_distance(home, self.mav.location()) self.wait_altitude(expected_alt - 10, expected_alt + 10, relative=True) new_distance = self.get_distance(home, self.mav.location()) # We should be closer to home. if new_distance > distance: raise NotAchievedException( "Expected to be closer to home (was %fm, now %fm)." % (distance, new_distance) ) self.fly_home_land_and_disarm() self.change_mode("MANUAL") self.set_rc(3, 1000) self.wait_ready_to_arm() self.set_parameters({ "FLIGHT_OPTIONS": 16, "ALT_HOLD_RTL": 10000, }) self.takeoff(alt=takeoff_alt) self.change_mode("CRUISE") self.wait_distance_to_home(500, 1000, timeout=60) self.change_mode("RTL") home = self.home_position_as_mav_location() distance = self.get_distance(home, self.mav.location()) self.wait_altitude(expected_alt - 10, expected_alt + 10, relative=True) new_distance = self.get_distance(home, self.mav.location()) # We should be farther from to home. if new_distance < distance: raise NotAchievedException( "Expected to be farther from home (was %fm, now %fm)." % (distance, new_distance) ) self.fly_home_land_and_disarm(timeout=240) def rtl_climb_min(self): self.wait_ready_to_arm() rtl_climb_min = 100 self.set_parameter("RTL_CLIMB_MIN", rtl_climb_min) takeoff_alt = 50 self.takeoff(alt=takeoff_alt) self.change_mode('CRUISE') self.wait_distance_to_home(1000, 1500, timeout=60) post_cruise_alt = self.get_altitude(relative=True) self.change_mode('RTL') expected_alt = self.get_parameter("ALT_HOLD_RTL")/100.0 if expected_alt == -1: expected_alt = self.get_altitude(relative=True) # ensure we're about half-way-down at the half-way-home stage: self.wait_distance_to_nav_target( 0, 500, timeout=120, ) alt = self.get_altitude(relative=True) expected_halfway_alt = expected_alt + (post_cruise_alt + rtl_climb_min - expected_alt)/2.0 if abs(alt - expected_halfway_alt) > 30: raise NotAchievedException("Not half-way-down and half-way-home (want=%f got=%f" % (expected_halfway_alt, alt)) self.progress("Half-way-down at half-way-home (want=%f vs got=%f)" % (expected_halfway_alt, alt)) rtl_radius = self.get_parameter("RTL_RADIUS") if rtl_radius == 0: rtl_radius = self.get_parameter("WP_LOITER_RAD") self.wait_distance_to_nav_target( 0, rtl_radius, timeout=120, ) alt = self.get_altitude(relative=True) if abs(alt - expected_alt) > 10: raise NotAchievedException( "Expected to have %fm altitude at end of RTL (got %f)" % (expected_alt, alt)) self.fly_home_land_and_disarm() def sample_enable_parameter(self): return "Q_ENABLE" def test_rangefinder(self): ex = None self.context_push() self.progress("Making sure we don't ordinarily get RANGEFINDER") m = None try: m = self.mav.recv_match(type='RANGEFINDER', blocking=True, timeout=5) except Exception as e: self.print_exception_caught(e) if m is not None: raise NotAchievedException("Received unexpected RANGEFINDER msg") try: self.set_analog_rangefinder_parameters() self.reboot_sitl() '''ensure rangefinder gives height-above-ground''' self.load_mission("plane-gripper-mission.txt") # borrow this self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() self.wait_waypoint(5, 5, max_dist=100) rf = self.mav.recv_match(type="RANGEFINDER", timeout=1, blocking=True) if rf is None: raise NotAchievedException("Did not receive rangefinder message") gpi = self.mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=1) if gpi is None: raise NotAchievedException("Did not receive GLOBAL_POSITION_INT message") if abs(rf.distance - gpi.relative_alt/1000.0) > 3: raise NotAchievedException( "rangefinder alt (%s) disagrees with global-position-int.relative_alt (%s)" % (rf.distance, gpi.relative_alt/1000.0)) self.wait_statustext("Auto disarmed", timeout=60) self.progress("Ensure RFND messages in log") if not self.current_onboard_log_contains_message("RFND"): raise NotAchievedException("No RFND messages in log") except Exception as e: self.print_exception_caught(e) ex = e self.context_pop() self.reboot_sitl() if ex is not None: raise ex def rc_defaults(self): ret = super(AutoTestPlane, self).rc_defaults() ret[3] = 1000 ret[8] = 1800 return ret def initial_mode_switch_mode(self): return "MANUAL" def default_mode(self): return "MANUAL" def test_pid_tuning(self): self.change_mode("FBWA") # we don't update PIDs in MANUAL super(AutoTestPlane, self).test_pid_tuning() def test_setting_modes_via_auxswitches(self): self.set_parameter("FLTMODE1", 1) # circle self.set_rc(8, 950) self.wait_mode("CIRCLE") self.set_rc(9, 1000) self.set_rc(10, 1000) self.set_parameters({ "RC9_OPTION": 4, # RTL "RC10_OPTION": 55, # guided }) self.set_rc(9, 1900) self.wait_mode("RTL") self.set_rc(10, 1900) self.wait_mode("GUIDED") self.progress("resetting both switches - should go back to CIRCLE") self.set_rc(9, 1000) self.set_rc(10, 1000) self.wait_mode("CIRCLE") self.set_rc(9, 1900) self.wait_mode("RTL") self.set_rc(10, 1900) self.wait_mode("GUIDED") self.progress("Resetting switch should repoll mode switch") self.set_rc(10, 1000) # this re-polls the mode switch self.wait_mode("CIRCLE") self.set_rc(9, 1000) def wait_for_collision_threat_to_clear(self): '''wait to get a "clear" collision message", then slurp remaining messages''' last_collision = self.get_sim_time() while True: now = self.get_sim_time() if now - last_collision > 5: return self.progress("Waiting for collision message") m = self.mav.recv_match(type='COLLISION', blocking=True, timeout=1) self.progress("Got (%s)" % str(m)) if m is None: continue last_collision = now def SimADSB(self): '''trivial tests to ensure simulated ADSB sensor continues to function''' self.set_parameters({ "SIM_ADSB_COUNT": 1, "ADSB_TYPE": 1, }) self.reboot_sitl() self.assert_receive_message('ADSB_VEHICLE', timeout=30) def test_adsb(self): self.context_push() ex = None try: # message ADSB_VEHICLE 37 -353632614 1491652305 0 584070 0 0 0 "bob" 3 1 255 17 self.set_parameter("RC12_OPTION", 38) # avoid-adsb self.set_rc(12, 2000) self.set_parameters({ "ADSB_TYPE": 1, "AVD_ENABLE": 1, "AVD_F_ACTION": mavutil.mavlink.MAV_COLLISION_ACTION_RTL, }) self.reboot_sitl() self.wait_ready_to_arm() here = self.mav.location() self.change_mode("FBWA") self.delay_sim_time(2) # TODO: work out why this is required... self.test_adsb_send_threatening_adsb_message(here) self.progress("Waiting for collision message") m = self.assert_receive_message('COLLISION', timeout=4) if m.threat_level != 2: raise NotAchievedException("Expected some threat at least") if m.action != mavutil.mavlink.MAV_COLLISION_ACTION_RTL: raise NotAchievedException("Incorrect action; want=%u got=%u" % (mavutil.mavlink.MAV_COLLISION_ACTION_RTL, m.action)) self.wait_mode("RTL") self.progress("Sending far-away ABSD_VEHICLE message") self.mav.mav.adsb_vehicle_send( 37, # ICAO address int(here.lat+1 * 1e7), int(here.lng * 1e7), mavutil.mavlink.ADSB_ALTITUDE_TYPE_PRESSURE_QNH, int(here.alt*1000 + 10000), # 10m up 0, # heading in cdeg 0, # horizontal velocity cm/s 0, # vertical velocity cm/s "bob".encode("ascii"), # callsign mavutil.mavlink.ADSB_EMITTER_TYPE_LIGHT, 1, # time since last communication 65535, # flags 17 # squawk ) self.wait_for_collision_threat_to_clear() self.change_mode("FBWA") self.progress("Disabling ADSB-avoidance with RC channel") self.set_rc(12, 1000) self.delay_sim_time(1) # let the switch get polled self.test_adsb_send_threatening_adsb_message(here) m = self.mav.recv_match(type='COLLISION', blocking=True, timeout=4) self.progress("Got (%s)" % str(m)) if m is not None: raise NotAchievedException("Got collision message when I shouldn't have") except Exception as e: self.print_exception_caught(e) ex = e self.context_pop() self.reboot_sitl() if ex is not None: raise ex def fly_do_guided_request(self, target_system=1, target_component=1): self.progress("Takeoff") self.takeoff(alt=50) self.set_rc(3, 1500) self.start_subtest("Ensure command bounced outside guided mode") desired_relative_alt = 33 loc = self.mav.location() self.location_offset_ne(loc, 300, 300) loc.alt += desired_relative_alt self.mav.mav.mission_item_int_send( target_system, target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, # current - guided-mode request 0, # autocontinue 0, # p1 0, # p2 0, # p3 0, # p4 int(loc.lat * 1e7), # latitude int(loc.lng * 1e7), # longitude loc.alt, # altitude mavutil.mavlink.MAV_MISSION_TYPE_MISSION) m = self.assert_receive_message('MISSION_ACK', timeout=5) if m.type != mavutil.mavlink.MAV_MISSION_ERROR: raise NotAchievedException("Did not get appropriate error") self.start_subtest("Enter guided and flying somewhere constant") self.change_mode("GUIDED") self.mav.mav.mission_item_int_send( target_system, target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, # current - guided-mode request 0, # autocontinue 0, # p1 0, # p2 0, # p3 0, # p4 int(loc.lat * 1e7), # latitude int(loc.lng * 1e7), # longitude desired_relative_alt, # altitude mavutil.mavlink.MAV_MISSION_TYPE_MISSION) m = self.assert_receive_message('MISSION_ACK', timeout=5) if m.type != mavutil.mavlink.MAV_MISSION_ACCEPTED: raise NotAchievedException("Did not get accepted response") self.wait_location(loc, accuracy=100) # based on loiter radius self.wait_altitude(altitude_min=desired_relative_alt-3, altitude_max=desired_relative_alt+3, relative=True, timeout=30) self.start_subtest("changing alt with mission item in guided mode") # test changing alt only - NOTE - this is still a # NAV_WAYPOINT, not a changel-alt request! desired_relative_alt = desired_relative_alt + 50 self.mav.mav.mission_item_int_send( target_system, target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 3, # current - change-alt request 0, # autocontinue 0, # p1 0, # p2 0, # p3 0, # p4 0, # latitude 0, desired_relative_alt, # altitude mavutil.mavlink.MAV_MISSION_TYPE_MISSION) self.wait_altitude(altitude_min=desired_relative_alt-3, altitude_max=desired_relative_alt+3, relative=True, timeout=30) self.fly_home_land_and_disarm() def LOITER(self): self.takeoff(alt=200) self.set_rc(3, 1500) self.change_mode("LOITER") self.progress("Doing a bit of loitering to start with") tstart = self.get_sim_time() while True: now = self.get_sim_time_cached() if now - tstart > 60: break m = self.mav.recv_match(type='VFR_HUD', blocking=True, timeout=5) if m is None: raise NotAchievedException("Did not get VFR_HUD") new_throttle = m.throttle alt = m.alt m = self.assert_receive_message('ATTITUDE', timeout=5) pitch = math.degrees(m.pitch) self.progress("Pitch:%f throttle:%u alt:%f" % (pitch, new_throttle, alt)) m = self.assert_receive_message('VFR_HUD', timeout=5) initial_throttle = m.throttle initial_alt = m.alt self.progress("Initial throttle: %u" % initial_throttle) # pitch down, ensure throttle decreases: rc2_max = self.get_parameter("RC2_MAX") self.set_rc(2, int(rc2_max)) tstart = self.get_sim_time() while True: now = self.get_sim_time_cached() '''stick-mixing is pushing the aircraft down. It doesn't want to go down (the target loiter altitude hasn't changed), so it tries to add energy by increasing the throttle. ''' if now - tstart > 60: raise NotAchievedException("Did not see increase in throttle") m = self.assert_receive_message('VFR_HUD', timeout=5) new_throttle = m.throttle alt = m.alt m = self.assert_receive_message('ATTITUDE', timeout=5) pitch = math.degrees(m.pitch) self.progress("Pitch:%f throttle:%u alt:%f" % (pitch, new_throttle, alt)) if new_throttle - initial_throttle > 20: self.progress("Throttle delta achieved") break self.progress("Centering elevator and ensuring we get back to loiter altitude") self.set_rc(2, 1500) self.wait_altitude(initial_alt-1, initial_alt+1) self.fly_home_land_and_disarm() def CPUFailsafe(self): '''In lockup Plane should copy RC inputs to RC outputs''' self.plane_CPUFailsafe() def test_large_missions(self): self.load_mission("Kingaroy-vlarge.txt", strict=False) self.load_mission("Kingaroy-vlarge2.txt", strict=False) def fly_soaring(self): model = "plane-soaring" self.customise_SITL_commandline( [], model=model, defaults_filepath=self.model_defaults_filepath(model), wipe=True) self.load_mission('CMAC-soar.txt', strict=False) self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() # Enable thermalling RC rc_chan = 0 for i in range(8): rcx_option = self.get_parameter('RC{0}_OPTION'.format(i+1)) if rcx_option == 88: rc_chan = i+1 break if rc_chan == 0: raise NotAchievedException("Did not find soaring enable channel option.") self.set_rc_from_map({ rc_chan: 1900, 3: 1500, # Use trim airspeed. }) # Wait to detect thermal self.progress("Waiting for thermal") self.wait_mode('THERMAL', timeout=600) self.set_parameter("SOAR_VSPEED", 0.6) # Wait to climb to SOAR_ALT_MAX self.progress("Waiting for climb to max altitude") alt_max = self.get_parameter('SOAR_ALT_MAX') self.wait_altitude(alt_max-10, alt_max, timeout=600, relative=True) # Wait for AUTO self.progress("Waiting for AUTO mode") self.wait_mode('AUTO') # Disable thermals self.set_parameter("SIM_THML_SCENARI", 0) # Wait to descend to SOAR_ALT_MIN self.progress("Waiting for glide to min altitude") alt_min = self.get_parameter('SOAR_ALT_MIN') self.wait_altitude(alt_min-10, alt_min, timeout=600, relative=True) self.progress("Waiting for throttle up") self.wait_servo_channel_value(3, 1200, timeout=2, comparator=operator.gt) self.progress("Waiting for climb to cutoff altitude") alt_ctf = self.get_parameter('SOAR_ALT_CUTOFF') self.wait_altitude(alt_ctf-10, alt_ctf, timeout=600, relative=True) # Allow time to suppress throttle and start descent. self.delay_sim_time(20) # Now set FBWB mode self.change_mode('FBWB') self.delay_sim_time(5) # Now disable soaring (should hold altitude) self.set_parameter("SOAR_ENABLE", 0) self.delay_sim_time(10) # And reenable. This should force throttle-down self.set_parameter("SOAR_ENABLE", 1) self.delay_sim_time(10) # Now wait for descent and check throttle up self.wait_altitude(alt_min-10, alt_min, timeout=600, relative=True) self.progress("Waiting for climb") self.wait_altitude(alt_ctf-10, alt_ctf, timeout=600, relative=True) # Back to auto self.change_mode('AUTO') # Reenable thermals self.set_parameter("SIM_THML_SCENARI", 1) # Disable soaring using RC channel. self.set_rc(rc_chan, 1100) # Wait to get back to waypoint before thermal. self.progress("Waiting to get back to position") self.wait_current_waypoint(3, timeout=1200) # Enable soaring with mode changes suppressed) self.set_rc(rc_chan, 1500) # Make sure this causes throttle down. self.wait_servo_channel_value(3, 1200, timeout=2, comparator=operator.lt) self.progress("Waiting for next WP with no thermalling") self.wait_waypoint(4, 4, timeout=1200, max_dist=120) # Disarm self.disarm_vehicle() self.progress("Mission OK") def fly_soaring_speed_to_fly(self): model = "plane-soaring" self.customise_SITL_commandline( [], model=model, defaults_filepath=self.model_defaults_filepath(model), wipe=True) self.load_mission('CMAC-soar.txt', strict=False) # Turn of environmental thermals. self.set_parameter("SIM_THML_SCENARI", 0) # Get thermalling RC channel rc_chan = 0 for i in range(8): rcx_option = self.get_parameter('RC{0}_OPTION'.format(i+1)) if rcx_option == 88: rc_chan = i+1 break if rc_chan == 0: raise NotAchievedException("Did not find soaring enable channel option.") # Disable soaring self.set_rc(rc_chan, 1100) self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() # Wait for to 400m before starting. self.wait_altitude(390, 400, timeout=600, relative=True) # Wait 10s to stabilize. self.delay_sim_time(30) # Enable soaring (no automatic thermalling) self.set_rc(rc_chan, 1500) # Enable speed to fly. self.set_parameter("SOAR_CRSE_ARSPD", -1) # Set appropriate McCready. self.set_parameter("SOAR_VSPEED", 1) self.set_parameter("SIM_WIND_SPD", 0) # Wait a few seconds before determining the "trim" airspeed. self.delay_sim_time(20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) trim_airspeed = m.airspeed min_airspeed = self.get_parameter("ARSPD_FBW_MIN") max_airspeed = self.get_parameter("ARSPD_FBW_MAX") # Add updraft self.set_parameter("SIM_WIND_SPD", 1) self.set_parameter('SIM_WIND_DIR_Z', 90) self.delay_sim_time(20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) if not m.airspeed < trim_airspeed and trim_airspeed > min_airspeed: raise NotAchievedException("Airspeed did not reduce in updraft") # Add downdraft self.set_parameter('SIM_WIND_DIR_Z', -90) self.delay_sim_time(20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) if not m.airspeed > trim_airspeed and trim_airspeed < max_airspeed: raise NotAchievedException("Airspeed did not increase in downdraft") # Zero the wind and increase McCready. self.set_parameter("SIM_WIND_SPD", 0) self.set_parameter("SOAR_VSPEED", 2) self.delay_sim_time(20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) if not m.airspeed > trim_airspeed and trim_airspeed < max_airspeed: raise NotAchievedException("Airspeed did not increase with higher SOAR_VSPEED") # Reduce McCready. self.set_parameter("SOAR_VSPEED", 0) self.delay_sim_time(20) m = self.mav.recv_match(type='VFR_HUD', blocking=True) if not m.airspeed < trim_airspeed and trim_airspeed > min_airspeed: raise NotAchievedException("Airspeed did not reduce with lower SOAR_VSPEED") # Disarm self.disarm_vehicle() self.progress("Mission OK") def test_airspeed_drivers(self): airspeed_sensors = [ ("MS5525", 3, 1), ("DLVR", 7, 2), ] for (name, t, bus) in airspeed_sensors: self.context_push() if bus is not None: self.set_parameter("ARSPD2_BUS", bus) self.set_parameter("ARSPD2_TYPE", t) self.reboot_sitl() self.wait_ready_to_arm() self.arm_vehicle() # insert listener to compare airspeeds: airspeed = [None, None] def check_airspeeds(mav, m): m_type = m.get_type() if (m_type == 'NAMED_VALUE_FLOAT' and m.name == 'AS2'): airspeed[1] = m.value elif m_type == 'VFR_HUD': airspeed[0] = m.airspeed else: return if airspeed[0] is None or airspeed[1] is None: return delta = abs(airspeed[0] - airspeed[1]) if delta > 2: raise NotAchievedException("Airspeed mismatch (as1=%f as2=%f)" % (airspeed[0], airspeed[1])) self.install_message_hook_context(check_airspeeds) self.fly_mission("ap1.txt", strict=False) if airspeed[0] is None: raise NotAchievedException("Never saw an airspeed1") if airspeed[1] is None: raise NotAchievedException("Never saw an airspeed2") self.context_pop() self.reboot_sitl() def TerrainMission(self): self.wait_ready_to_arm() self.arm_vehicle() self.fly_mission("ap-terrain.txt", mission_timeout=600) def Terrain(self): '''test AP_Terrain''' self.reboot_sitl() # we know the terrain height at CMAC mavproxy = self.start_mavproxy() self.wait_ready_to_arm() loc = self.mav.location() lng_int = int(loc.lng * 1e7) lat_int = int(loc.lat * 1e7) # FIXME: once we have a pre-populated terrain cache this # should require an instantly correct report to pass tstart = self.get_sim_time_cached() while True: if self.get_sim_time_cached() - tstart > 60: raise NotAchievedException("Did not get correct terrain report") self.mav.mav.terrain_check_send(lat_int, lng_int) report = self.mav.recv_match(type='TERRAIN_REPORT', blocking=True, timeout=60) self.progress(self.dump_message_verbose(report)) if report.spacing != 0: break self.delay_sim_time(1) self.progress(self.dump_message_verbose(report)) expected_terrain_height = 583.5 if abs(report.terrain_height - expected_terrain_height) > 0.5: raise NotAchievedException("Expected terrain height=%f got=%f" % (expected_terrain_height, report.terrain_height)) self.stop_mavproxy(mavproxy) def test_loiter_terrain(self): default_rad = self.get_parameter("WP_LOITER_RAD") self.set_parameters({ "TERRAIN_FOLLOW": 1, # enable terrain following in loiter "WP_LOITER_RAD": 2000, # set very large loiter rad to get some terrain changes }) alt = 200 self.takeoff(alt*0.9, alt*1.1) self.set_rc(3, 1500) self.change_mode("LOITER") self.progress("loitering at %um" % alt) tstart = self.get_sim_time() while True: now = self.get_sim_time_cached() if now - tstart > 60*15: # enough time to do one and a bit circles break terrain = self.mav.recv_match( type='TERRAIN_REPORT', blocking=True, timeout=1 ) if terrain is None: raise NotAchievedException("Did not get TERRAIN_REPORT message") rel_alt = terrain.current_height self.progress("%um above terrain" % rel_alt) if rel_alt > alt*1.2 or rel_alt < alt * 0.8: raise NotAchievedException("Not terrain following") self.progress("Returning home") self.set_parameters({ "TERRAIN_FOLLOW": 0, "WP_LOITER_RAD": default_rad, }) self.fly_home_land_and_disarm(240) def fly_external_AHRS(self, sim, eahrs_type, mission): """Fly with external AHRS (VectorNav)""" self.customise_SITL_commandline(["--uartE=sim:%s" % sim]) self.set_parameters({ "EAHRS_TYPE": eahrs_type, "SERIAL4_PROTOCOL": 36, "SERIAL4_BAUD": 230400, "GPS_TYPE": 21, "AHRS_EKF_TYPE": 11, "INS_GYR_CAL": 1, }) self.reboot_sitl() self.progress("Running accelcal") self.run_cmd(mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, 0, 0, 0, 4, 0, 0, timeout=5) self.wait_ready_to_arm() self.arm_vehicle() self.fly_mission(mission) def test_vectornav(self): self.fly_external_AHRS("VectorNav", 1, "ap1.txt") def test_lord(self): self.fly_external_AHRS("LORD", 2, "ap1.txt") def get_accelvec(self, m): return Vector3(m.xacc, m.yacc, m.zacc) * 0.001 * 9.81 def get_gyrovec(self, m): return Vector3(m.xgyro, m.ygyro, m.zgyro) * 0.001 * math.degrees(1) def test_imu_tempcal(self): self.progress("Setting up SITL temperature profile") self.set_parameters({ "SIM_IMUT1_ENABLE" : 1, "SIM_IMUT1_ACC1_X" : 120000.000000, "SIM_IMUT1_ACC1_Y" : -190000.000000, "SIM_IMUT1_ACC1_Z" : 1493.864746, "SIM_IMUT1_ACC2_X" : -51.624416, "SIM_IMUT1_ACC2_Y" : 10.364172, "SIM_IMUT1_ACC2_Z" : -7878.000000, "SIM_IMUT1_ACC3_X" : -0.514242, "SIM_IMUT1_ACC3_Y" : 0.862218, "SIM_IMUT1_ACC3_Z" : -234.000000, "SIM_IMUT1_GYR1_X" : -5122.513817, "SIM_IMUT1_GYR1_Y" : -3250.470428, "SIM_IMUT1_GYR1_Z" : -2136.346676, "SIM_IMUT1_GYR2_X" : 30.720505, "SIM_IMUT1_GYR2_Y" : 17.778447, "SIM_IMUT1_GYR2_Z" : 0.765997, "SIM_IMUT1_GYR3_X" : -0.003572, "SIM_IMUT1_GYR3_Y" : 0.036346, "SIM_IMUT1_GYR3_Z" : 0.015457, "SIM_IMUT1_TMAX" : 70.0, "SIM_IMUT1_TMIN" : -20.000000, "SIM_IMUT2_ENABLE" : 1, "SIM_IMUT2_ACC1_X" : -160000.000000, "SIM_IMUT2_ACC1_Y" : 198730.000000, "SIM_IMUT2_ACC1_Z" : 27812.000000, "SIM_IMUT2_ACC2_X" : 30.658159, "SIM_IMUT2_ACC2_Y" : 32.085022, "SIM_IMUT2_ACC2_Z" : 1572.000000, "SIM_IMUT2_ACC3_X" : 0.102912, "SIM_IMUT2_ACC3_Y" : 0.229734, "SIM_IMUT2_ACC3_Z" : 172.000000, "SIM_IMUT2_GYR1_X" : 3173.925644, "SIM_IMUT2_GYR1_Y" : -2368.312836, "SIM_IMUT2_GYR1_Z" : -1796.497177, "SIM_IMUT2_GYR2_X" : 13.029696, "SIM_IMUT2_GYR2_Y" : -10.349280, "SIM_IMUT2_GYR2_Z" : -15.082653, "SIM_IMUT2_GYR3_X" : 0.004831, "SIM_IMUT2_GYR3_Y" : -0.020528, "SIM_IMUT2_GYR3_Z" : 0.009469, "SIM_IMUT2_TMAX" : 70.000000, "SIM_IMUT2_TMIN" : -20.000000, "SIM_IMUT_END" : 45.000000, "SIM_IMUT_START" : 3.000000, "SIM_IMUT_TCONST" : 75.000000, "SIM_DRIFT_SPEED" : 0, "INS_GYR_CAL" : 0, }) self.set_parameter("SIM_IMUT_FIXED", 12) self.progress("Running accel cal") self.run_cmd(mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, 0, 0, 0, 4, 0, 0, timeout=5) self.progress("Running gyro cal") self.run_cmd(mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0, 0, 0, 0, 1, 0, 0, timeout=5) self.set_parameters({ "SIM_IMUT_FIXED": 0, "INS_TCAL1_ENABLE": 2, "INS_TCAL1_TMAX": 42, "INS_TCAL2_ENABLE": 2, "INS_TCAL2_TMAX": 42, "SIM_SPEEDUP": 200, }) self.set_parameter("LOG_DISARMED", 1) self.reboot_sitl() self.progress("Waiting for IMU temperature") self.assert_reach_imu_temperature(43, timeout=600) if self.get_parameter("INS_TCAL1_ENABLE") != 1.0: raise NotAchievedException("TCAL1 did not complete") if self.get_parameter("INS_TCAL2_ENABLE") != 1.0: raise NotAchievedException("TCAL2 did not complete") self.progress("Logging with calibration enabled") self.reboot_sitl() self.assert_reach_imu_temperature(43, timeout=600) self.progress("Testing with compensation enabled") test_temperatures = range(10, 45, 5) corrected = {} uncorrected = {} for temp in test_temperatures: self.progress("Testing temperature %.1f" % temp) self.set_parameter("SIM_IMUT_FIXED", temp) self.delay_sim_time(2) for msg in ['RAW_IMU', 'SCALED_IMU2']: m = self.assert_receive_message(msg, timeout=2) temperature = m.temperature*0.01 if abs(temperature - temp) > 0.2: raise NotAchievedException("incorrect %s temperature %.1f should be %.1f" % (msg, temperature, temp)) accel = self.get_accelvec(m) gyro = self.get_gyrovec(m) accel2 = accel + Vector3(0, 0, 9.81) corrected[temperature] = (accel2, gyro) self.progress("Testing with compensation disabled") self.set_parameters({ "INS_TCAL1_ENABLE": 0, "INS_TCAL2_ENABLE": 0, }) gyro_threshold = 0.2 accel_threshold = 0.2 for temp in test_temperatures: self.progress("Testing temperature %.1f" % temp) self.set_parameter("SIM_IMUT_FIXED", temp) self.wait_heartbeat() self.wait_heartbeat() for msg in ['RAW_IMU', 'SCALED_IMU2']: m = self.assert_receive_message(msg, timeout=2) temperature = m.temperature*0.01 if abs(temperature - temp) > 0.2: raise NotAchievedException("incorrect %s temperature %.1f should be %.1f" % (msg, temperature, temp)) accel = self.get_accelvec(m) gyro = self.get_gyrovec(m) accel2 = accel + Vector3(0, 0, 9.81) uncorrected[temperature] = (accel2, gyro) for temp in test_temperatures: (accel, gyro) = corrected[temp] self.progress("Corrected gyro at %.1f %s" % (temp, gyro)) self.progress("Corrected accel at %.1f %s" % (temp, accel)) for temp in test_temperatures: (accel, gyro) = uncorrected[temp] self.progress("Uncorrected gyro at %.1f %s" % (temp, gyro)) self.progress("Uncorrected accel at %.1f %s" % (temp, accel)) bad_value = False for temp in test_temperatures: (accel, gyro) = corrected[temp] if gyro.length() > gyro_threshold: raise NotAchievedException("incorrect corrected at %.1f gyro %s" % (temp, gyro)) if accel.length() > accel_threshold: raise NotAchievedException("incorrect corrected at %.1f accel %s" % (temp, accel)) (accel, gyro) = uncorrected[temp] if gyro.length() > gyro_threshold*2: bad_value = True if accel.length() > accel_threshold*2: bad_value = True if not bad_value: raise NotAchievedException("uncompensated IMUs did not vary enough") # the above tests change the internal persistent state of the # vehicle in ways that autotest doesn't track (magically set # parameters). So wipe the vehicle's eeprom: self.reset_SITL_commandline() def ekf_lane_switch(self): self.context_push() ex = None # new lane swtich available only with EK3 self.set_parameters({ "EK3_ENABLE": 1, "EK2_ENABLE": 0, "AHRS_EKF_TYPE": 3, "EK3_AFFINITY": 15, # enable affinity for all sensors "EK3_IMU_MASK": 3, # use only 2 IMUs "GPS_TYPE2": 1, "SIM_GPS2_DISABLE": 0, "SIM_BARO_COUNT": 2, "SIM_BAR2_DISABLE": 0, "ARSPD2_TYPE": 2, "ARSPD2_USE": 1, "ARSPD2_PIN": 2, }) # some parameters need reboot to take effect self.reboot_sitl() self.lane_switches = [] # add an EKF lane switch hook def statustext_hook(mav, message): if message.get_type() != 'STATUSTEXT': return # example msg: EKF3 lane switch 1 if not message.text.startswith("EKF3 lane switch "): return newlane = int(message.text[-1]) self.lane_switches.append(newlane) self.install_message_hook(statustext_hook) # get flying self.takeoff(alt=50) self.change_mode('CIRCLE') try: ################################################################### self.progress("Checking EKF3 Lane Switching trigger from all sensors") ################################################################### self.start_subtest("ACCELEROMETER: Change z-axis offset") # create an accelerometer error by changing the Z-axis offset self.context_collect("STATUSTEXT") old_parameter = self.get_parameter("INS_ACCOFFS_Z") self.wait_statustext( text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("INS_ACCOFFS_Z", old_parameter + 5), check_context=True) if self.lane_switches != [1]: raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1])) # Cleanup self.set_parameter("INS_ACCOFFS_Z", old_parameter) self.context_clear_collection("STATUSTEXT") self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) ################################################################### self.start_subtest("BAROMETER: Freeze to last measured value") self.context_collect("STATUSTEXT") # create a barometer error by inhibiting any pressure change while changing altitude old_parameter = self.get_parameter("SIM_BAR2_FREEZE") self.set_parameter("SIM_BAR2_FREEZE", 1) self.wait_statustext( text="EKF3 lane switch", timeout=30, the_function=lambda: self.set_rc(2, 2000), check_context=True) if self.lane_switches != [1, 0]: raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1])) # Cleanup self.set_rc(2, 1500) self.set_parameter("SIM_BAR2_FREEZE", old_parameter) self.context_clear_collection("STATUSTEXT") self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) ################################################################### self.start_subtest("GPS: Apply GPS Velocity Error in NED") self.context_push() self.context_collect("STATUSTEXT") # create a GPS velocity error by adding a random 2m/s # noise on each axis def sim_gps_verr(): self.set_parameters({ "SIM_GPS_VERR_X": self.get_parameter("SIM_GPS_VERR_X") + 2, "SIM_GPS_VERR_Y": self.get_parameter("SIM_GPS_VERR_Y") + 2, "SIM_GPS_VERR_Z": self.get_parameter("SIM_GPS_VERR_Z") + 2, }) self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=sim_gps_verr, check_context=True) if self.lane_switches != [1, 0, 1]: raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1])) # Cleanup self.context_pop() self.context_clear_collection("STATUSTEXT") self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) ################################################################### self.start_subtest("MAGNETOMETER: Change X-Axis Offset") self.context_collect("STATUSTEXT") # create a magnetometer error by changing the X-axis offset old_parameter = self.get_parameter("SIM_MAG2_OFS_X") self.wait_statustext( text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("SIM_MAG2_OFS_X", old_parameter + 150), check_context=True) if self.lane_switches != [1, 0, 1, 0]: raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1])) # Cleanup self.set_parameter("SIM_MAG2_OFS_X", old_parameter) self.context_clear_collection("STATUSTEXT") self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) ################################################################### self.start_subtest("AIRSPEED: Fail to constant value") self.context_push() self.context_collect("STATUSTEXT") old_parameter = self.get_parameter("SIM_ARSPD_FAIL") def fail_speed(): self.change_mode("GUIDED") loc = self.mav.location() self.run_cmd_int( mavutil.mavlink.MAV_CMD_DO_REPOSITION, 0, 0, 0, 0, int(loc.lat * 1e7), int(loc.lng * 1e7), 50 # alt ) self.delay_sim_time(5) # create an airspeed sensor error by freezing to the # current airspeed then changing the airspeed demand # to a higher value and waiting for the TECS speed # loop to diverge m = self.mav.recv_match(type='VFR_HUD', blocking=True) self.set_parameter("SIM_ARSPD_FAIL", m.airspeed) self.run_cmd( mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, 0, # airspeed 30, -1, # throttle / no change 0, # absolute values 0, 0, 0 ) self.wait_statustext(text="EKF3 lane switch", timeout=30, the_function=fail_speed, check_context=True) if self.lane_switches != [1, 0, 1, 0, 1]: raise NotAchievedException("Expected lane switch 1, got %s" % str(self.lane_switches[-1])) # Cleanup self.set_parameter("SIM_ARSPD_FAIL", old_parameter) self.change_mode('CIRCLE') self.context_pop() self.context_clear_collection("STATUSTEXT") self.wait_heading(0, accuracy=10, timeout=60) self.wait_heading(180, accuracy=10, timeout=60) ################################################################### self.progress("GYROSCOPE: Change Y-Axis Offset") self.context_collect("STATUSTEXT") # create a gyroscope error by changing the Y-axis offset old_parameter = self.get_parameter("INS_GYR2OFFS_Y") self.wait_statustext( text="EKF3 lane switch", timeout=30, the_function=self.set_parameter("INS_GYR2OFFS_Y", old_parameter + 1), check_context=True) if self.lane_switches != [1, 0, 1, 0, 1, 0]: raise NotAchievedException("Expected lane switch 0, got %s" % str(self.lane_switches[-1])) # Cleanup self.set_parameter("INS_GYR2OFFS_Y", old_parameter) self.context_clear_collection("STATUSTEXT") ################################################################### self.disarm_vehicle() except Exception as e: self.print_exception_caught(e) ex = e self.remove_message_hook(statustext_hook) self.context_pop() # some parameters need reboot to take effect self.reboot_sitl() if ex is not None: raise ex def test_fence_alt_ceil_floor(self): fence_bit = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE self.set_parameters({ "FENCE_TYPE": 9, # Set fence type to max and min alt "FENCE_ACTION": 0, # Set action to report "FENCE_ALT_MAX": 200, "FENCE_ALT_MIN": 100, }) # Grab Home Position self.mav.recv_match(type='HOME_POSITION', blocking=True) self.homeloc = self.mav.location() cruise_alt = 150 self.takeoff(cruise_alt) self.do_fence_enable() self.progress("Fly above ceiling and check for breach") self.change_altitude(self.homeloc.alt + cruise_alt + 80) m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) if ((m.onboard_control_sensors_health & fence_bit)): raise NotAchievedException("Fence Ceiling did not breach") self.progress("Return to cruise alt and check for breach clear") self.change_altitude(self.homeloc.alt + cruise_alt) m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) if (not (m.onboard_control_sensors_health & fence_bit)): raise NotAchievedException("Fence breach did not clear") self.progress("Fly below floor and check for breach") self.change_altitude(self.homeloc.alt + cruise_alt - 80) m = self.mav.recv_match(type='SYS_STATUS', blocking=True) self.progress("Got (%s)" % str(m)) if ((m.onboard_control_sensors_health & fence_bit)): raise NotAchievedException("Fence Floor did not breach") self.do_fence_disable() self.fly_home_land_and_disarm(timeout=150) def test_fence_breached_change_mode(self): """ Attempts to change mode while a fence is breached. This should revert to the mode specified by the fence action. """ self.set_parameters({ "FENCE_ACTION": 1, "FENCE_TYPE": 4, }) home_loc = self.mav.location() locs = [ mavutil.location(home_loc.lat - 0.001, home_loc.lng - 0.001, 0, 0), mavutil.location(home_loc.lat - 0.001, home_loc.lng + 0.001, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng + 0.001, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng - 0.001, 0, 0), ] self.upload_fences_from_locations( mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION, [ locs ] ) self.delay_sim_time(1) self.wait_ready_to_arm() self.takeoff(alt=50) self.change_mode("CRUISE") self.wait_distance(90, accuracy=15) self.progress("Enable fence and initiate fence action") self.do_fence_enable() self.assert_fence_enabled() self.wait_mode("RTL") # We should RTL because of fence breach self.progress("User mode change to cruise should retrigger fence action") self.change_mode("CRUISE") self.wait_mode("RTL", timeout=5) self.progress("Test complete, disable fence and come home") self.do_fence_disable() self.fly_home_land_and_disarm() def test_fence_breach_no_return_point(self): """ Attempts to change mode while a fence is breached. This should revert to the mode specified by the fence action. """ want_radius = 100 # Fence Return Radius self.set_parameters({ "FENCE_ACTION": 6, "FENCE_TYPE": 4, "RTL_RADIUS": want_radius, "NAVL1_LIM_BANK": 60, }) home_loc = self.mav.location() locs = [ mavutil.location(home_loc.lat - 0.003, home_loc.lng - 0.001, 0, 0), mavutil.location(home_loc.lat - 0.003, home_loc.lng + 0.003, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng + 0.003, 0, 0), mavutil.location(home_loc.lat + 0.001, home_loc.lng - 0.001, 0, 0), ] self.upload_fences_from_locations( mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION, [ locs ] ) self.delay_sim_time(1) self.wait_ready_to_arm() self.takeoff(alt=50) self.change_mode("CRUISE") self.wait_distance(150, accuracy=20) self.progress("Enable fence and initiate fence action") self.do_fence_enable() self.assert_fence_enabled() self.wait_mode("GUIDED", timeout=120) # We should RTL because of fence breach self.delay_sim_time(60) items = self.download_using_mission_protocol(mavutil.mavlink.MAV_MISSION_TYPE_FENCE) if len(items) != 4: raise NotAchievedException("Unexpected fencepoint count (want=%u got=%u)" % (4, len(items))) # Check there are no fence return points specified still for fence_loc in items: if fence_loc.command == mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT: raise NotAchievedException( "Unexpected fence return point found (%u) got %u" % (fence_loc.command, mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT)) # Work out the approximate return point when no fence return point present # Logic taken from AC_PolyFence_loader.cpp min_loc = self.mav.location() max_loc = self.mav.location() for new_loc in locs: if new_loc.lat < min_loc.lat: min_loc.lat = new_loc.lat if new_loc.lng < min_loc.lng: min_loc.lng = new_loc.lng if new_loc.lat > max_loc.lat: max_loc.lat = new_loc.lat if new_loc.lng > max_loc.lng: max_loc.lng = new_loc.lng # Generate the return location based on min and max locs ret_lat = (min_loc.lat + max_loc.lat) / 2 ret_lng = (min_loc.lng + max_loc.lng) / 2 ret_loc = mavutil.location(ret_lat, ret_lng, 0, 0) self.progress("Return loc: (%s)" % str(ret_loc)) # Wait for guided return to vehicle calculated fence return location self.wait_distance_to_location(ret_loc, 90, 110) self.wait_circling_point_with_radius(ret_loc, 92) self.progress("Test complete, disable fence and come home") self.do_fence_disable() self.fly_home_land_and_disarm() def test_fence_breach_no_return_point_no_inclusion(self): """ Test result when a breach occurs and No fence return point is present and no inclusion fence is present and exclusion fence is present """ want_radius = 100 # Fence Return Radius self.set_parameters({ "FENCE_ACTION": 6, "FENCE_TYPE": 2, "FENCE_RADIUS": 300, "RTL_RADIUS": want_radius, "NAVL1_LIM_BANK": 60, }) self.clear_fence() self.delay_sim_time(1) self.wait_ready_to_arm() home_loc = self.mav.location() self.takeoff(alt=50) self.change_mode("CRUISE") self.wait_distance(150, accuracy=20) self.progress("Enable fence and initiate fence action") self.do_fence_enable() self.assert_fence_enabled() self.wait_mode("GUIDED") # We should RTL because of fence breach self.delay_sim_time(30) items = self.download_using_mission_protocol(mavutil.mavlink.MAV_MISSION_TYPE_FENCE) if len(items) != 0: raise NotAchievedException("Unexpected fencepoint count (want=%u got=%u)" % (0, len(items))) # Check there are no fence return points specified still for fence_loc in items: if fence_loc.command == mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT: raise NotAchievedException( "Unexpected fence return point found (%u) got %u" % (fence_loc.command, mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT)) # Wait for guided return to vehicle calculated fence return location self.wait_distance_to_location(home_loc, 90, 110) self.wait_circling_point_with_radius(home_loc, 92) self.progress("Test complete, disable fence and come home") self.do_fence_disable() self.fly_home_land_and_disarm() def test_fence_disable_under_breach_action(self): """ Fence breach will cause the vehicle to enter guided mode. Upon breach clear, check the vehicle is in the expected mode""" self.set_parameters({ "FENCE_ALT_MIN": 50, # Sets the fence floor "FENCE_TYPE": 8, # Only use fence floor for breaches }) self.wait_ready_to_arm() def attempt_fence_breached_disable(start_mode, end_mode, expected_mode, action): self.set_parameter("FENCE_ACTION", action) # Set Fence Action to Guided self.change_mode(start_mode) self.arm_vehicle() self.do_fence_enable() self.assert_fence_enabled() self.wait_mode(expected_mode) self.do_fence_disable() self.assert_fence_disabled() self.wait_mode(end_mode) self.disarm_vehicle(force=True) attempt_fence_breached_disable(start_mode="FBWA", end_mode="RTL", expected_mode="RTL", action=1) attempt_fence_breached_disable(start_mode="FBWA", end_mode="FBWA", expected_mode="GUIDED", action=6) attempt_fence_breached_disable(start_mode="FBWA", end_mode="FBWA", expected_mode="GUIDED", action=7) def run_auxfunc(self, function, level, want_result=mavutil.mavlink.MAV_RESULT_ACCEPTED): self.run_cmd( mavutil.mavlink.MAV_CMD_DO_AUX_FUNCTION, function, # p1 level, # p2 0, # p3 0, # p4 0, # p5 0, # p6 0, # p7 want_result=want_result ) def fly_aux_function(self): self.context_collect('STATUSTEXT') self.run_auxfunc(64, 2) # 64 == reverse throttle self.wait_statustext("RevThrottle: ENABLE", check_context=True) self.run_auxfunc(64, 0) self.wait_statustext("RevThrottle: DISABLE", check_context=True) self.run_auxfunc(65, 2) # 65 == GPS_DISABLE self.start_subtest("Bad auxfunc") self.run_auxfunc( 65231, 2, want_result=mavutil.mavlink.MAV_RESULT_FAILED ) self.start_subtest("Bad switchpos") self.run_auxfunc( 62, 17, want_result=mavutil.mavlink.MAV_RESULT_DENIED ) def fly_each_frame(self): vinfo = vehicleinfo.VehicleInfo() vinfo_options = vinfo.options[self.vehicleinfo_key()] known_broken_frames = { "firefly": "falls out of sky after transition", "plane-tailsitter": "does not take off; immediately emits 'AP: Transition VTOL done' while on ground", "quadplane-cl84": "falls out of sky instead of transitioning", "quadplane-tilttri": "falls out of sky instead of transitioning", "quadplane-tilttrivec": "loses attitude control and crashes", } for frame in sorted(vinfo_options["frames"].keys()): self.start_subtest("Testing frame (%s)" % str(frame)) if frame in known_broken_frames: self.progress("Actually, no I'm not - it is known-broken (%s)" % (known_broken_frames[frame])) continue frame_bits = vinfo_options["frames"][frame] print("frame_bits: %s" % str(frame_bits)) if frame_bits.get("external", False): self.progress("Actually, no I'm not - it is an external simulation") continue model = frame_bits.get("model", frame) # the model string for Callisto has crap in it.... we # should really have another entry in the vehicleinfo data # to carry the path to the JSON. actual_model = model.split(":")[0] defaults = self.model_defaults_filepath(actual_model) if type(defaults) != list: defaults = [defaults] self.customise_SITL_commandline( ["--defaults", ','.join(defaults), ], model=model, wipe=True, ) mission_file = "basic.txt" quadplane = self.get_parameter('Q_ENABLE') if quadplane: mission_file = "basic-quadplane.txt" tailsitter = self.get_parameter('Q_TAILSIT_ENABLE') if tailsitter: # tailsitter needs extra re-boot to pick up the rotated AHRS view self.reboot_sitl() self.wait_ready_to_arm() self.arm_vehicle() self.fly_mission(mission_file, strict=False, quadplane=quadplane, mission_timeout=400.0) self.wait_disarmed() def RCDisableAirspeedUse(self): self.set_parameter("RC9_OPTION", 106) self.delay_sim_time(5) self.set_rc(9, 1000) self.wait_sensor_state( mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE, True, True, True) self.set_rc(9, 2000) self.wait_sensor_state( mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE, True, False, True) self.set_rc(9, 1000) self.wait_sensor_state( mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE, True, True, True) def WatchdogHome(self): if self.gdb: # we end up signalling the wrong process. I think. # Probably need to have a "sitl_pid()" method to get the # ardupilot process's PID. self.progress("######## Skipping WatchdogHome test under GDB") return ex = None try: self.progress("Enabling watchdog") self.set_parameter("BRD_OPTIONS", 1 << 0) self.reboot_sitl() self.wait_ready_to_arm() self.progress("Explicitly setting home to a known location") orig_home = self.poll_home_position() new_home = orig_home new_home.latitude = new_home.latitude + 1000 new_home.longitude = new_home.longitude + 2000 new_home.altitude = new_home.altitude + 300000 # 300 metres self.run_cmd_int( mavutil.mavlink.MAV_CMD_DO_SET_HOME, 0, # p1, 0, # p2, 0, # p3, 0, # p4, new_home.latitude, new_home.longitude, new_home.altitude/1000.0, # mm => m ) old_bootcount = self.get_parameter('STAT_BOOTCNT') self.progress("Forcing watchdog reset") os.kill(self.sitl.pid, signal.SIGALRM) self.detect_and_handle_reboot(old_bootcount) self.wait_statustext("WDG:") self.wait_statustext("IMU1 is using GPS") # won't be come armable self.progress("Verifying home position") post_reboot_home = self.poll_home_position() delta = self.get_distance_int(new_home, post_reboot_home) max_delta = 1 if delta > max_delta: raise NotAchievedException( "New home not where it should be (dist=%f) (want=%s) (got=%s)" % (delta, str(new_home), str(post_reboot_home))) except Exception as e: self.print_exception_caught(e) ex = e self.reboot_sitl() if ex is not None: raise ex def AUTOTUNE(self): self.takeoff(100) self.change_mode('AUTOTUNE') self.context_collect('STATUSTEXT') tstart = self.get_sim_time() axis = "Roll" rc_value = 1000 while True: timeout = 600 if self.get_sim_time() - tstart > timeout: raise NotAchievedException("Did not complete within %u seconds" % timeout) try: m = self.wait_statustext("%s: Finished" % axis, check_context=True, timeout=0.1) self.progress("Got %s" % str(m)) if axis == "Roll": axis = "Pitch" elif axis == "Pitch": break else: raise ValueError("Bug: %s" % axis) except AutoTestTimeoutException: pass self.delay_sim_time(1) if rc_value == 1000: rc_value = 2000 elif rc_value == 2000: rc_value = 1000 elif rc_value == 1000: rc_value = 2000 else: raise ValueError("Bug") if axis == "Roll": self.set_rc(1, rc_value) self.set_rc(2, 1500) elif axis == "Pitch": self.set_rc(1, 1500) self.set_rc(2, rc_value) else: raise ValueError("Bug") tdelta = self.get_sim_time() - tstart self.progress("Finished in %0.1f seconds" % (tdelta,)) self.set_rc(1, 1500) self.set_rc(2, 1500) self.change_mode('FBWA') self.fly_home_land_and_disarm(timeout=tdelta+240) def fly_landing_baro_drift(self): self.customise_SITL_commandline([], wipe=True) self.set_analog_rangefinder_parameters() self.set_parameters({ "SIM_BARO_DRIFT": -0.02, "SIM_TERRAIN": 0, "RNGFND_LANDING": 1, "LAND_SLOPE_RCALC": 2, "LAND_ABORT_DEG": 1, }) self.reboot_sitl() self.wait_ready_to_arm() self.arm_vehicle() # Load and start mission self.load_mission("ap-circuit.txt", strict=True) self.set_current_waypoint(1, check_afterwards=True) self.change_mode('AUTO') self.wait_current_waypoint(1, timeout=5) self.wait_groundspeed(0, 10, timeout=5) # Wait for landing waypoint self.wait_current_waypoint(9, timeout=1200) # Wait for landing restart self.wait_current_waypoint(5, timeout=60) # Wait for landing waypoint (second attempt) self.wait_current_waypoint(9, timeout=1200) self.wait_disarmed(timeout=180) def DCMFallback(self): self.reboot_sitl() self.delay_sim_time(30) self.wait_ready_to_arm() self.arm_vehicle() self.takeoff(50) self.change_mode('CIRCLE') self.context_collect('STATUSTEXT') self.set_parameters({ "EK3_POS_I_GATE": 0, "SIM_GPS_HZ": 1, "SIM_GPS_LAG_MS": 1000, }) self.wait_statustext("DCM Active", check_context=True, timeout=60) self.wait_statustext("EKF3 Active", check_context=True) self.wait_statustext("DCM Active", check_context=True) self.wait_statustext("EKF3 Active", check_context=True) self.wait_statustext("DCM Active", check_context=True) self.wait_statustext("EKF3 Active", check_context=True) self.context_stop_collecting('STATUSTEXT') self.fly_home_land_and_disarm() def ForcedDCM(self): self.wait_ready_to_arm() self.arm_vehicle() self.takeoff(50) self.context_collect('STATUSTEXT') self.set_parameter("AHRS_EKF_TYPE", 0) self.wait_statustext("DCM Active", check_context=True) self.context_stop_collecting('STATUSTEXT') self.fly_home_land_and_disarm() def MegaSquirt(self): self.assert_not_receiving_message('EFI_STATUS') self.set_parameters({ 'SIM_EFI_TYPE': 1, 'EFI_TYPE': 1, 'SERIAL5_PROTOCOL': 24, }) self.customise_SITL_commandline(["--uartF=sim:megasquirt"]) self.delay_sim_time(5) m = self.assert_receive_message('EFI_STATUS') mavutil.dump_message_verbose(sys.stdout, m) if m.throttle_out != 0: raise NotAchievedException("Expected zero throttle") if m.health != 1: raise NotAchievedException("Not healthy") if m.intake_manifold_temperature < 20: raise NotAchievedException("Bad intake manifold temperature") def test_glide_slope_threshold(self): # Test that GLIDE_SLOPE_THRESHOLD correctly controls re-planning glide slope # in the scenario that aircraft is above planned slope and slope is positive (climbing). # # # Behaviour with GLIDE_SLOPE_THRESH = 0 (no slope replanning) # (2).. __(4) # | \..__/ # | __/ # (3) # # Behaviour with GLIDE_SLOPE_THRESH = 5 (slope replanning when >5m error) # (2)........__(4) # | __/ # | __/ # (3) # Solid is plan, dots are actual flightpath. self.load_mission('rapid-descent-then-climb.txt', strict=False) self.set_current_waypoint(1) self.change_mode('AUTO') self.wait_ready_to_arm() self.arm_vehicle() # # Initial run with GLIDE_SLOPE_THR = 5 (default). # self.set_parameter("GLIDE_SLOPE_THR", 5) # Wait for waypoint commanding rapid descent, followed by climb. self.wait_current_waypoint(5, timeout=1200) # Altitude should not descend significantly below the initial altitude init_altitude = self.get_altitude(relative=True, timeout=2) timeout = 600 wpnum = 7 tstart = self.get_sim_time() while True: if self.get_sim_time() - tstart > timeout: raise AutoTestTimeoutException("Did not get wanted current waypoint") if (self.get_altitude(relative=True, timeout=2) - init_altitude) < -10: raise NotAchievedException("Descended >10m before reaching desired waypoint,\ indicating slope was not replanned") seq = self.mav.waypoint_current() self.progress("Waiting for wp=%u current=%u" % (wpnum, seq)) if seq == wpnum: break self.set_current_waypoint(2) # # Second run with GLIDE_SLOPE_THR = 0 (no re-plan). # self.set_parameter("GLIDE_SLOPE_THR", 0) # Wait for waypoint commanding rapid descent, followed by climb. self.wait_current_waypoint(5, timeout=1200) # This time altitude should descend significantly below the initial altitude init_altitude = self.get_altitude(relative=True, timeout=2) timeout = 600 wpnum = 7 tstart = self.get_sim_time() while True: if self.get_sim_time() - tstart > timeout: raise AutoTestTimeoutException("Did not get wanted altitude") seq = self.mav.waypoint_current() self.progress("Waiting for wp=%u current=%u" % (wpnum, seq)) if seq == wpnum: raise NotAchievedException("Reached desired waypoint without first decending 10m,\ indicating slope was replanned unexpectedly") if (self.get_altitude(relative=True, timeout=2) - init_altitude) < -10: break # Disarm self.wait_disarmed(timeout=600) self.progress("Mission OK") def tests(self): '''return list of all tests''' ret = super(AutoTestPlane, self).tests() ret.extend([ ("AuxModeSwitch", "Set modes via auxswitches", self.test_setting_modes_via_auxswitches), ("TestRCCamera", "Test RC Option - Camera Trigger", self.test_rc_option_camera_trigger), ("TestRCRelay", "Test Relay RC Channel Option", self.test_rc_relay), ("ThrottleFailsafe", "Fly throttle failsafe", self.test_throttle_failsafe), ("NeedEKFToArm", "Ensure we need EKF to be healthy to arm", self.test_need_ekf_to_arm), ("ThrottleFailsafeFence", "Fly fence survives throttle failsafe", self.test_throttle_failsafe_fence), ("TestFlaps", "Flaps", self.fly_flaps), ("DO_CHANGE_SPEED", "Test mavlink DO_CHANGE_SPEED command", self.fly_do_change_speed), ("DO_REPOSITION", "Test mavlink DO_REPOSITION command", self.fly_do_reposition), ("GuidedRequest", "Test handling of MISSION_ITEM in guided mode", self.fly_do_guided_request), ("MainFlight", "Lots of things in one flight", self.test_main_flight), ("TestGripperMission", "Test Gripper mission items", self.test_gripper_mission), ("Parachute", "Test Parachute", self.test_parachute), ("ParachuteSinkRate", "Test Parachute (SinkRate triggering)", self.test_parachute_sinkrate), ("AIRSPEED_AUTOCAL", "Test AIRSPEED_AUTOCAL", self.airspeed_autocal), ("RangeFinder", "Test RangeFinder Basic Functionality", self.test_rangefinder), ("FenceStatic", "Test Basic Fence Functionality", self.test_fence_static), ("FenceRTL", "Test Fence RTL", self.test_fence_rtl), ("FenceRTLRally", "Test Fence RTL Rally", self.test_fence_rtl_rally), ("FenceRetRally", "Test Fence Ret_Rally", self.test_fence_ret_rally), ("FenceAltCeilFloor", "Tests the fence ceiling and floor", self.test_fence_alt_ceil_floor), ("FenceBreachedChangeMode", "Tests retrigger of fence action when changing of mode while fence is breached", self.test_fence_breached_change_mode), ("FenceNoFenceReturnPoint", "Tests calculated return point during fence breach when no fence return point present", self.test_fence_breach_no_return_point), ("FenceNoFenceReturnPointInclusion", "Tests using home as fence return point when none is present, and no inclusion fence is uploaded", self.test_fence_breach_no_return_point_no_inclusion), ("FenceDisableUnderAction", "Tests Disabling fence while undergoing action caused by breach", self.test_fence_disable_under_breach_action), ("ADSB", "Test ADSB", self.test_adsb), ("SimADSB", "Test SIM_ADSB", self.SimADSB), ("Button", "Test Buttons", self.test_button), ("FRSkySPort", "Test FrSky SPort mode", self.test_frsky_sport), ("FRSkyPassThrough", "Test FrSky PassThrough serial output", self.test_frsky_passthrough), ("FRSkyMAVlite", "Test FrSky MAVlite serial output", self.test_frsky_mavlite), ("FRSkyD", "Test FrSkyD serial output", self.test_frsky_d), ("LTM", "Test LTM serial output", self.test_ltm), ("DEVO", "Test DEVO serial output", self.DEVO), ("AdvancedFailsafe", "Test Advanced Failsafe", self.test_advanced_failsafe), ("LOITER", "Test Loiter mode", self.LOITER), ("DeepStall", "Test DeepStall Landing", self.fly_deepstall), ("WatchdogHome", "Ensure home is restored after watchdog reset", self.WatchdogHome), ("LargeMissions", "Test Manipulation of Large missions", self.test_large_missions), ("Soaring", "Test Soaring feature", self.fly_soaring), ("Terrain", "Test AP_Terrain", self.Terrain), ("TerrainMission", "Test terrain following in mission", self.TerrainMission), ("Terrain-loiter", "Test terrain following in loiter", self.test_loiter_terrain), ("VectorNavEAHRS", "Test VectorNav EAHRS support", self.test_vectornav), ("LordEAHRS", "Test LORD Microstrain EAHRS support", self.test_lord), ("Deadreckoning", "Test deadreckoning support", self.deadreckoning), ("DeadreckoningNoAirSpeed", "Test deadreckoning support with no airspeed sensor", self.deadreckoning_no_airspeed_sensor), ("EKFlaneswitch", "Test EKF3 Affinity and Lane Switching", self.ekf_lane_switch), ("AirspeedDrivers", "Test AirSpeed drivers", self.test_airspeed_drivers), ("RTL_CLIMB_MIN", "Test RTL_CLIMB_MIN", self.rtl_climb_min), ("ClimbBeforeTurn", "Test climb-before-turn", self.climb_before_turn), ("IMUTempCal", "Test IMU temperature calibration", self.test_imu_tempcal), ("MAV_DO_AUX_FUNCTION", "Test triggering Auxillary Functions via mavlink", self.fly_aux_function), ("SmartBattery", "Test smart battery logging etc", self.SmartBattery), ("FlyEachFrame", "Fly each supported internal frame", self.fly_each_frame), ("RCDisableAirspeedUse", "Test RC DisableAirspeedUse option", self.RCDisableAirspeedUse), ("AHRS_ORIENTATION", "Test AHRS_ORIENTATION parameter", self.AHRS_ORIENTATION), ("AHRSTrim", "AHRS trim testing", self.ahrstrim), ("Landing-Drift", "Circuit with baro drift", self.fly_landing_baro_drift), ("ForcedDCM", "Switch to DCM mid-flight", self.ForcedDCM), ("DCMFallback", "Really annoy the EKF and force fallback", self.DCMFallback), ("MAVFTP", "Test MAVProxy can talk FTP to autopilot", self.MAVFTP), ("AUTOTUNE", "Test AutoTune mode", self.AUTOTUNE), ("MegaSquirt", "Test MegaSquirt EFI", self.MegaSquirt), ("MSP_DJI", "Test MSP DJI serial output", self.test_msp_dji), ("SpeedToFly", "Test soaring speed-to-fly", self.fly_soaring_speed_to_fly), ("GlideSlopeThresh", "Test rebuild glide slope if above and climbing", self.test_glide_slope_threshold), ("LogUpload", "Log upload", self.log_upload), ("HIGH_LATENCY2", "Set sending of HIGH_LATENCY2", self.HIGH_LATENCY2), ]) return ret def disabled_tests(self): return { "Terrain-loiter": "Loading of terrain data is not reliable", "Landing-Drift": "Flapping test. See https://github.com/ArduPilot/ardupilot/issues/20054", }
lthall/Leonard_ardupilot
Tools/autotest/arduplane.py
Python
gpl-3.0
143,031
[ "Firefly" ]
522edab649f8d664bf2583686747cd327222dc26d37155e240c88b13b8316b74
""" 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. Written (W) 2013 Heiko Strathmann Written (W) 2013 Dino Sejdinovic """ from matplotlib.pyplot import hold, quiver, draw from numpy import reshape, array, shape, meshgrid, zeros, linspace from kameleon_mcmc.distribution.Gaussian import Gaussian from kameleon_mcmc.kernel.GaussianKernel import GaussianKernel from kameleon_mcmc.kernel.Kernel import Kernel from kameleon_mcmc.mcmc.samplers.Kameleon import Kameleon from kameleon_mcmc.tools.Visualise import Visualise class GFunction(object): def __init__(self, distribution, n=200, kernel=GaussianKernel(3), nu2=0.1, \ gamma=0.1, ell=15, nXs=100, nYs=100): self.kernel = kernel self.distribution = distribution self.nu2 = nu2 self.gamma = gamma self.ell = ell # fix some samples self.Z = self.distribution.sample(n).samples # evaluate and center kernel and scale self.K = self.kernel.kernel(self.Z, None) self.K = Kernel.center_kernel_matrix(self.K) # sample beta self.rkhs_gaussian = Gaussian(mu=zeros(len(self.Z)), Sigma=self.K, is_cholesky=False, \ ell=self.ell) self.beta = self.rkhs_gaussian.sample().samples # plotting resolution [(xmin, xmax), (ymin, ymax)] = self.distribution.get_plotting_bounds() self.Xs = linspace(xmin, xmax, nXs) self.Ys = linspace(ymin, ymax, nYs) def resample_beta(self): self.beta = self.rkhs_gaussian.sample().samples def compute(self, x, y, Z, beta): """ Given two points x and y, a set of samples Z, and a vector beta, and a kernel function, this computes the g function g(x,beta,Z)=||k(x,.)-f|| for f=k(.,y)+sum_i beta_i*k(.,z_i) =k(x,x) -2k(x,y) -2sum_i beta_i*k(x,z_i) +C Constant C is not computed """ first = self.kernel.kernel(x, x) second = -2 * self.kernel.kernel(x, y) third = -2 * self.kernel.kernel(x, Z).dot(beta.T) return first + second + third def compute_gradient(self, x, y, Z, beta): """ Given two points x and y, a set of samples Z, and a vector beta, and a kernel gradient, this computes the g function's gradient \nabla_x g(x,beta,Z)=\nabla_x k(x,x) -2k(x,y) -2sum_i beta_i*k(x,z_i) """ x_2d = reshape(x, (1, len(x))) first = self.kernel.gradient(x, x_2d) second = -2 * self.kernel.gradient(x, y) # compute sum_i beta_i \nabla_x k(x,z_i) and beta is a row vector gradients = self.kernel.gradient(x, Z) third = -2 * beta.dot(gradients) return first + second + third def plot(self, y=array([[-2, -2]]), gradient_scale=None, plot_data=False): # where to evaluate G? G = zeros((len(self.Ys), len(self.Xs))) # for plotting the gradient field, each U and V are one dimension of gradient if gradient_scale is not None: GXs2 = linspace(self.Xs.min(), self.Xs.max(), 30) GYs2 = linspace(self.Ys.min(), self.Ys.max(), 20) X, Y = meshgrid(GXs2, GYs2) U = zeros(shape(X)) V = zeros(shape(Y)) # evaluate g at a set of points in Xs and Ys for i in range(len(self.Xs)): # print i, "/", len(self.Xs) for j in range(len(self.Ys)): x_2d = array([[self.Xs[i], self.Ys[j]]]) y_2d = reshape(y, (1, len(y))) G[j, i] = self.compute(x_2d, y_2d, self.Z, self.beta) # gradient at lower resolution if gradient_scale is not None: for i in range(len(GXs2)): # print i, "/", len(GXs2) for j in range(len(GYs2)): x_1d = array([GXs2[i], GYs2[j]]) y_2d = reshape(y, (1, len(y))) G_grad = self.compute_gradient(x_1d, y_2d, self.Z, self.beta) U[j, i] = -G_grad[0, 0] V[j, i] = -G_grad[0, 1] # plot g and Z points and y y_2d = reshape(y, (1, len(y))) Visualise.plot_array(self.Xs, self.Ys, G) if gradient_scale is not None: hold(True) quiver(X, Y, U, V, color='y', scale=gradient_scale) hold(False) if plot_data: hold(True) Visualise.plot_data(self.Z, y_2d) hold(False) def plot_proposal(self, ys): # evaluate density itself Visualise.visualise_distribution(self.distribution, Z=self.Z, Xs=self.Xs, Ys=self.Ys) # precompute constants of proposal mcmc_hammer = Kameleon(self.distribution, self.kernel, self.Z, \ self.nu2, self.gamma) # plot proposal around each y for y in ys: mu, L_R = mcmc_hammer.compute_constants(y) gaussian = Gaussian(mu, L_R, is_cholesky=True) hold(True) Visualise.contour_plot_density(gaussian) hold(False) draw()
karlnapf/kameleon-mcmc
kameleon_mcmc/paper_figures/GFunction.py
Python
bsd-2-clause
5,402
[ "Gaussian" ]
423ccf5186a1d9a03e161092f81b990fd06fb531d9cbd4a0e79dab16178b1e4b
from erukar.system.engine import MaterialGood class NegaciteCrystal(MaterialGood): BaseName = "Negacite Crystal" BriefDescription = "a chunk of crystalline Negacite" BasePricePerSingle = 97 WeightPerSingle = 0.3
etkirsch/legends-of-erukar
erukar/content/inventory/materials/raw/NegaciteCrystal.py
Python
agpl-3.0
229
[ "CRYSTAL" ]
31edaef4922054a564c66c597b470175c5ee0e0343c127ae9fa889668f479747
#!/usr/bin/env python3.5 """Script to post to AutoLovecraft.tumblr.com. Really rough sketch of a script here. Not really meant for public use. Based on my earlier script to do a similar job for the IrishLitDiscourses Tumblr account; see https://github.com/patrick-brian-mooney/IrishLitDiscourses-python The fact that there isn't real documentation here is intentionally meant to reinforce that this is a rough draft not meant for public use. Use at your own risk. My hope is that this script is helpful, but I explicitly disclaim ANY RESPONSIBILITY for the behavior of this piece of work. If you don't have the expertise to evaluate its risks, it's not for you. To put it more bluntly: THIS SOFTWARE IS OFFERED WITHOUT WARRANTY OF ANY KIND AT ALL. # Thanks to https://epicjefferson.wordpress.com/2014/09/28/python-to-tumblr/ for first steps here when I was first cutting my teeth on Python. """ import bz2 import datetime import json import os import pprint import random import sys import social_media # From https://github.com/patrick-brian-mooney/personal-library import text_generator as tg # https://github.com/patrick-brian-mooney/markov-sentence-generator with open('/social_media_auth.json', encoding='utf-8') as auth_file: autolovecraft_client = social_media.Tumblpy_from_dict(json.loads(auth_file.read())['autolovecraft_client']) # First, some contants. chains_file = '/lovecraft/corpora/In the Vault.3.pkl' post_archives = '/lovecraft/archives' the_tags = ['H.P. Lovecraft', 'automatically generated text', 'Patrick Mooney', 'Python', 'Markov chains', '1925', 'In the Vault', 'In the Vault week'] # Utility functions def print_usage(): # Note that, currently, nothing calls this. """Print the docstring as a usage message to stdout""" print("INFO: print_usage() was called") print(__doc__) if __name__ == "__main__": story_length = random.choice(list(range(25, 71))) the_content = '' print("INFO: tags and sentence lengths set up ...") genny = tg.TextGenerator(name='Lovecraft Generator') genny.chains.read_chains(chains_file) print("INFO: chains read, starting run ...") # Next, pick out a title between 10 and 70 characters print("INFO: getting a story title ...") the_title = 'herp a derp!' * 50 # pick something much too long. previous_titles = open('/lovecraft/titles.txt').read() tries, max_length = 0, 70 while not 10 <= len(the_title) <= max_length: the_title = genny.gen_text().strip() tries += 1 title_length = len(the_title) print("INFO: The story title generated was '%s'" % the_title) print("INFO: And the length of that title is: %d" % len(the_title)) if the_title in previous_titles: print("That title's been used! Trying again ...\n\n\n") continue else: print(" That's a new title!") if len(the_title) > max_length: tries += 1 if tries % 100 == 0: # Every hundred failed titles, bump up maximum allowed title length. max_length += 1 # hopefully, this means we'll eventually find a legal title. print("OK, we've got a title.\n\n") print('INFO: tags are:' + pprint.pformat(the_tags)) print('INFO: requested story length is: ' + str(story_length) + ' sentences ... generating ...') the_content = genny.gen_text(sentences_desired=story_length, paragraph_break_probability=0.2) the_lines = ["<p>" + the_line.strip() + "</p>" for the_line in the_content.split('\n\n')] print("the_lines: " + pprint.pformat(the_lines)) the_content = "\n\n".join(the_lines) print("the_content: \n\n" + the_content) # All right, we're ready. Let's go. print('INFO: Attempting to post the content') the_status, the_tumblr_data = social_media.tumblr_text_post(autolovecraft_client, the_tags, the_title, the_content) print('INFO: the_status is: ' + pprint.pformat(the_status)) print('INFO: the_tumblr_data is: ' + pprint.pformat(the_tumblr_data)) try: print('INFO: Adding title of that post to list of titles') with open('/lovecraft/titles.txt', 'a') as f: f.write(the_title + '\n') except IOError: print("ERROR: Can't add the title to the list of used titles.", 0) # Keep an archived copy post_data = {'title': the_title, 'text': the_content, 'time': datetime.datetime.now().isoformat() } post_data['formatted_text'], post_data['tags'] = the_lines, the_tags post_data['status_code'], post_data['tumblr_data'] = the_status, the_tumblr_data archive_name = "%s — %s.json.bz2" % (the_status['id'], the_title) with bz2.BZ2File(os.path.join(post_archives, archive_name), mode='wb') as archive_file: archive_file.write(json.dumps(post_data, sort_keys=True, indent=3, ensure_ascii=False).encode()) print("INFO: We're done") print("Cythonized? {}".format(tg._is_cythonized())) print("Ran under Python version: " + sys.version)
patrick-brian-mooney/AutoLovecraft-python
generate.py
Python
gpl-3.0
5,070
[ "Brian" ]
2bdada24c97bf6ba41d5ec2a34c06504a4f930e9ebdb2092173f5aa9db8d421d
import logging import os from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import modify_settings from selenium.webdriver.chrome.options import Options from splinter import Browser # On ubuntu with chromium installed as snap, we also need to use the chromedriver from the snap if os.path.isfile("/snap/bin/chromium.chromedriver"): chromedriver_path = "/snap/bin/chromium.chromedriver" else: chromedriver_path = "node_modules/chromedriver/bin/chromedriver" logger = logging.getLogger(__name__) @modify_settings(MIDDLEWARE={"remove": ["django.middleware.csrf.CsrfViewMiddleware"]}) class ChromeDriverTestCase(StaticLiveServerTestCase): """ Specifics of ChromeDriverTestCase: - Chrome Headless is used - English is used for the UI - CSRF-checks are disabled, as referrer-checking seems to be problematic, as the HTTPS-header seems to be always set """ browser = None @classmethod def setUpClass(cls): options = Options() options.add_experimental_option("prefs", {"intl.accept_languages": "en_US"}) cls.browser = Browser( "chrome", executable_path=chromedriver_path, options=options, headless=not settings.DEBUG_TESTING, ) super(ChromeDriverTestCase, cls).setUpClass() @classmethod def tearDownClass(cls): cls.browser.quit() super(ChromeDriverTestCase, cls).tearDownClass() """ Helper functions for a more convenient test syntax """ def visit(self, path): self.browser.visit(self.live_server_url + path) def assetElementIsPresentByCss(self, css): self.assertTrue(len(self.browser.find_by_css(css)) > 0) def assetElementIsNotPresentByCss(self, css): self.assertTrue(len(self.browser.find_by_css(css)) == 0) def assertTextIsPresent(self, text): self.assertTrue(self.browser.is_text_present(text)) def assertTextIsNotPresent(self, text): self.assertFalse(self.browser.is_text_present(text)) def assertElementDoesExists(self, css_selector): self.assertTrue(self.browser.is_element_present_by_css(css_selector)) def assertElementDoesNotExists(self, css_selector): self.assertFalse(self.browser.is_element_present_by_css(css_selector)) def click_by_id(self, id): self.browser.find_by_id(id).first.click() def click_by_text(self, text): self.browser.find_by_text(text).first.click() def click_by_css(self, css): self.browser.find_by_css(css).first.click() """ Functions for behaviors used by several test cases """ def logout(self): self.browser.find_by_css("#main-menu-content #navbarMyAccount").click() self.browser.find_by_css("#main-menu-content .logout-button").click() self.assertTextIsPresent("You have signed out.") self.assertElementDoesExists("#main-menu-content .login-link") self.assertElementDoesNotExists("#main-menu-content .my-account-link") def login(self, username, password): self.browser.find_by_css("#main-menu-content .login-link").click() self.browser.fill("login", username) self.browser.fill("password", password) self.browser.find_by_css("form.login button").click() self.assertTextIsPresent("Successfully signed in as " + username)
meine-stadt-transparent/meine-stadt-transparent
mainapp/tests/live/chromedriver_test_case.py
Python
mit
3,430
[ "VisIt" ]
f013777a3e2a34ff7d8c4f1d272fedca27c07e11197065b495803a65f9697db9
from future import standard_library standard_library.install_aliases() from builtins import str import logging import pycurl import io import re import os from datetime import datetime from biomaj.utils import Utils from biomaj.download.interface import DownloadInterface try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO class FTPDownload(DownloadInterface): ''' Base class to download files from FTP protocol=ftp server=ftp.ncbi.nih.gov remote.dir=/blast/db/FASTA/ remote.files=^alu.*\\.gz$ ''' def __init__(self, protocol, host, rootdir): DownloadInterface.__init__(self) logging.debug('Download') self.crl = pycurl.Curl() url = protocol+'://'+host self.rootdir = rootdir self.url = url self.headers= {} def match(self, patterns, file_list, dir_list=None, prefix='', submatch=False): ''' Find files matching patterns. Sets instance variable files_to_download. :param patterns: regexps to match :type patterns: list :param file_list: list of files to match :type file_list: list :param dir_list: sub directories in current dir :type dir_list: list :param prefix: directory prefix :type prefix: str :param submatch: first call to match, or called from match :type submatch: bool ''' logging.debug('Download:File:RegExp:'+str(patterns)) if dir_list is None: dir_list = [] if not submatch: self.files_to_download = [] for pattern in patterns: subdirs_pattern = pattern.split('/') if len(subdirs_pattern) > 1: # Pattern contains sub directories subdir = subdirs_pattern[0] if subdir == '^': subdirs_pattern = subdirs_pattern[1:] subdir = subdirs_pattern[0] for direlt in dir_list: subdir = direlt['name'] logging.debug('Download:File:Subdir:Check:'+subdir) if pattern == '**/*': (subfile_list, subdirs_list) = self.list(prefix+'/'+subdir+'/') self.match([pattern], subfile_list, subdirs_list, prefix+'/'+subdir, True) for rfile in file_list: if pattern == '**/*' or re.match(pattern, rfile['name']): rfile['root'] = self.rootdir if prefix != '': rfile['name'] = prefix + '/' +rfile['name'] self.files_to_download.append(rfile) logging.debug('Download:File:MatchRegExp:'+rfile['name']) else: if re.match(subdirs_pattern[0], subdir): logging.debug('Download:File:Subdir:Match:'+subdir) # subdir match the beginning of the pattern # check match in subdir (subfile_list, subdirs_list) = self.list(prefix+'/'+subdir+'/') self.match(['/'.join(subdirs_pattern[1:])], subfile_list, subdirs_list, prefix+'/'+subdir, True) else: for rfile in file_list: if re.match(pattern, rfile['name']): rfile['root'] = self.rootdir if prefix != '': rfile['name'] = prefix + '/' +rfile['name'] self.files_to_download.append(rfile) logging.debug('Download:File:MatchRegExp:'+rfile['name']) if not submatch and len(self.files_to_download) == 0: raise Exception('no file found matching expressions') def download(self, local_dir, keep_dirs=True): ''' Download remote files to local_dir :param local_dir: Directory where files should be downloaded :type local_dir: str :param keep_dirs: keep file name directory structure or copy file in local_dir directly :param keep_dirs: bool :return: list of downloaded files ''' logging.debug('FTP:Download') nb_files = len(self.files_to_download) cur_files = 1 for rfile in self.files_to_download: if self.kill_received: raise Exception('Kill request received, exiting') file_dir = local_dir if 'save_as' not in rfile or rfile['save_as'] is None: rfile['save_as'] = rfile['name'] if keep_dirs: file_dir = local_dir + '/' + os.path.dirname(rfile['save_as']) file_path = file_dir + '/' + os.path.basename(rfile['save_as']) self.mkdir_lock.acquire() try: if not os.path.exists(file_dir): os.makedirs(file_dir) except Exception as e: logging.error(e) finally: self.mkdir_lock.release() # release lock, no matter what logging.debug('FTP:Download:Progress:'+str(cur_files)+'/'+str(nb_files)+' downloading file '+rfile['name']) logging.debug('FTP:Download:Progress:'+str(cur_files)+'/'+str(nb_files)+' save as '+rfile['save_as']) cur_files += 1 if not 'url' in rfile: rfile['url'] = self.url fp = open(file_path, "wb") curl = pycurl.Curl() try: curl.setopt(pycurl.URL, rfile['url']+rfile['root']+'/'+rfile['name']) except Exception as a: curl.setopt(pycurl.URL, (rfile['url']+rfile['root']+'/'+rfile['name']).encode('ascii','ignore')) if self.proxy is not None: self.crl.setopt(pycurl.PROXY, self.proxy) if self.proxy_auth is not None: curl.setopt(pycurl.PROXYUSERPWD, self.proxy_auth) if self.credentials is not None: curl.setopt(pycurl.USERPWD, self.credentials) curl.setopt(pycurl.WRITEDATA, fp) curl.perform() #errcode = curl.getinfo(pycurl.HTTP_CODE) #if int(errcode) != 200: # self.error = True # logging.error('Error while downloading '+rfile['name']+' - '+str(errcode)) curl.close() fp.close() #logging.debug('downloaded!') self.set_permissions(file_path, rfile) # Add progress only per 10 files to limit db requests if nb_files < 10: nb = 1 do_progress = True else: if cur_files == nb_files: do_progress = True nb = cur_files % 10 elif cur_files > 0 and cur_files % 10 == 0: nb = 10 do_progress= True else: do_progress = False if do_progress: self.set_progress(nb, nb_files) return self.files_to_download def header_function(self, header_line): # HTTP standard specifies that headers are encoded in iso-8859-1. # On Python 2, decoding step can be skipped. # On Python 3, decoding step is required. header_line = header_line.decode('iso-8859-1') # Header lines include the first status line (HTTP/1.x ...). # We are going to ignore all lines that don't have a colon in them. # This will botch headers that are split on multiple lines... if ':' not in header_line: return # Break the header line into header name and value. name, value = header_line.split(':', 1) # Remove whitespace that may be present. # Header lines include the trailing newline, and there may be whitespace # around the colon. name = name.strip() value = value.strip() # Header names are case insensitive. # Lowercase name here. name = name.lower() # Now we can actually record the header name and value. self.headers[name] = value def list(self, directory=''): ''' List FTP directory :return: tuple of file and dirs in current directory with details ''' logging.debug('Download:List:'+self.url+self.rootdir+directory) #self.crl.setopt(pycurl.URL, self.url+self.rootdir+directory) try: self.crl.setopt(pycurl.URL, self.url+self.rootdir+directory) except Exception as a: self.crl.setopt(pycurl.URL, (self.url+self.rootdir+directory).encode('ascii','ignore')) if self.proxy is not None: self.crl.setopt(pycurl.PROXY, self.proxy) if self.proxy_auth is not None: curl.setopt(pycurl.PROXYUSERPWD, self.proxy_auth) if self.credentials is not None: self.crl.setopt(pycurl.USERPWD, self.credentials) output = BytesIO() # lets assign this buffer to pycurl object self.crl.setopt(pycurl.WRITEFUNCTION, output.write) self.crl.setopt(pycurl.HEADERFUNCTION, self.header_function) self.crl.perform() # Figure out what encoding was sent with the response, if any. # Check against lowercased header name. encoding = None if 'content-type' in self.headers: content_type = self.headers['content-type'].lower() match = re.search('charset=(\S+)', content_type) if match: encoding = match.group(1) if encoding is None: # Default encoding for HTML is iso-8859-1. # Other content types may have different default encoding, # or in case of binary data, may have no encoding at all. encoding = 'iso-8859-1' # lets get the output in a string result = output.getvalue().decode(encoding) # FTP LIST output is separated by \r\n # lets split the output in lines #lines = result.split(r'[\r\n]+') lines = re.split(r'[\n\r]+', result) # lets walk through each line rfiles = [] rdirs = [] for line in lines: rfile = {} # lets print each part separately parts = line.split() # the individual fields in this list of parts if not parts: continue rfile['permissions'] = parts[0] rfile['group'] = parts[2] rfile['user'] = parts[3] rfile['size'] = parts[4] rfile['month'] = Utils.month_to_num(parts[5]) rfile['day'] = parts[6] try: rfile['year'] = int(parts[7]) except Exception as e: # specific ftp case issues at getting date info curdate = datetime.now() rfile['year'] = curdate.year # Year not precised, month feater than current means previous year if rfile['month'] > curdate.month: rfile['year'] = curdate.year - 1 # Same month but later day => previous year if rfile['month'] == curdate.month and int(rfile['day']) > curdate.day: rfile['year'] = curdate.year - 1 rfile['name'] = parts[8] if len(parts) >= 10 and parts[9] == '->': # Symlink, add to files AND dirs as we don't know the type of the link rdirs.append(rfile) is_dir = False if re.match('^d', rfile['permissions']): is_dir = True if not is_dir: rfiles.append(rfile) else: rdirs.append(rfile) return (rfiles, rdirs) def chroot(self, cwd): logging.debug('Download: change dir '+cwd) def close(self): if self.crl is not None: self.crl.close() self.crl = None
markiskander/biomaj
biomaj/download/ftp.py
Python
agpl-3.0
12,091
[ "BLAST" ]
893e0f1309f97daf93fc326b29abcf708d269e4018694870e87fc7a3627b00ac
#!/usr/bin/env python # # Copyright 2013 Tristan Bereau and Christian Kramer # # 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. # #################### # # This script transforms a .pun file into a charmm-readable .lpun file. # Optimized Parameters can be given import sys import mtp_tools punfile = '' parmfile = '' ############## # Read input for i in range(len(sys.argv)): if sys.argv[i] == '-pun': punfile = sys.argv[i+1] elif sys.argv[i] == '-par': parmfile = sys.argv[i+1] elif sys.argv[i] == '-h': print "Usage: python pun2charmmlpun.py -pun [file] [-par [parfile]] [-h]" exit(0) if punfile == '': print "Usage: python pun2charmmlpun.py -pun [file] [-par [parfile]] [-h]" exit(0) ############# # Check that the file does not end in .lpun, otherwise quit. if punfile[punfile.rindex('.'):] == '.lpun': print "Error: the script will generate a .lpun file, please rename current file." exit(1) # Read prmfile if given prms = {} if parmfile != '': import numpy f = open(parmfile,'r') a = f.readlines() f.close() for line in a: b = line.split() prms[(b[0][2:-2],b[1][1:-2])] = numpy.array([float(b[i+3]) for i in range(len(b)-3)]) mol = mtp_tools.molecule() mol.readfrompunfile(punfile) mol.Calc_locMTP() if parmfile != '': for atom in mol.atoms: atom.chrg = prms[(atom.atype,'chrg')] atom.dloc = prms[(atom.atype,'dloc')] atom.Qloc = prms[(atom.atype,'Qloc')] mol.Calc_gloMTP() mol.adjust_charge() mol.write_localized_mtp_file(punfile[:punfile.rindex('.')]+'.lpun')
MMunibas/FittingWizard
scripts/pun2charmmlpun.py
Python
bsd-3-clause
2,122
[ "CHARMM" ]
22355b78e0558b9dffa60f87201c4972ad5d7d2b2db932b6dce4ba82c6e0c2d6
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import pootle.core.mixins.treeitem class Migration(migrations.Migration): dependencies = [ ('pootle_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(help_text='ISO 639 language code for the language, possibly followed by an underscore (_) and an ISO 3166 country code. <a href="http://www.w3.org/International/articles/language-tags/">More information</a>', unique=True, max_length=50, verbose_name='Code', db_index=True)), ('fullname', models.CharField(max_length=255, verbose_name='Full Name')), ('specialchars', models.CharField(help_text='Enter any special characters that users might find difficult to type', max_length=255, verbose_name='Special Characters', blank=True)), ('nplurals', models.SmallIntegerField(default=0, help_text='For more information, visit <a href="http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html">our page</a> on plural forms.', verbose_name='Number of Plurals', choices=[(0, 'Unknown'), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)])), ('pluralequation', models.CharField(help_text='For more information, visit <a href="http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html">our page</a> on plural forms.', max_length=255, verbose_name='Plural Equation', blank=True)), ('directory', models.OneToOneField(editable=False, to='pootle_app.Directory', on_delete=models.CASCADE)), ], options={ 'ordering': ['code'], 'db_table': 'pootle_app_language', }, bases=(models.Model, pootle.core.mixins.treeitem.TreeItem), ), ]
claudep/pootle
pootle/apps/pootle_language/migrations/0001_initial.py
Python
gpl-3.0
2,056
[ "VisIt" ]
b7c5c6192d8c8cea45ac87c1897e64bd6f80a3805f63a9786ecfb1d027fcf86e
from typing import Any, Dict EMOJI_NAME_MAPS: Dict[str, Dict[str, Any]] = { # seems like best emoji for happy "1f600": {"canonical_name": "grinning", "aliases": ["happy"]}, "1f603": {"canonical_name": "smiley", "aliases": []}, # the Google emoji for this is not great, so made People/9 'smile' and # renamed this one "1f604": {"canonical_name": "big_smile", "aliases": []}, # from gemoji/Unicode "1f601": {"canonical_name": "grinning_face_with_smiling_eyes", "aliases": []}, # satisfied doesn't seem like a good description of these images "1f606": {"canonical_name": "laughing", "aliases": ["lol"]}, "1f605": {"canonical_name": "sweat_smile", "aliases": []}, # laughter_tears from https://beebom.com/emoji-meanings/ "1f602": {"canonical_name": "joy", "aliases": ["tears", "laughter_tears"]}, "1f923": {"canonical_name": "rolling_on_the_floor_laughing", "aliases": ["rofl"]}, # not sure how the glyphs match relaxed, but both iamcal and gemoji have it "263a": {"canonical_name": "smiling_face", "aliases": ["relaxed"]}, "1f60a": {"canonical_name": "blush", "aliases": []}, # halo comes from gemoji/Unicode "1f607": {"canonical_name": "innocent", "aliases": ["halo"]}, "1f642": {"canonical_name": "smile", "aliases": []}, "1f643": {"canonical_name": "upside_down", "aliases": ["oops"]}, "1f609": {"canonical_name": "wink", "aliases": []}, "1f60c": {"canonical_name": "relieved", "aliases": []}, # in_love from https://beebom.com/emoji-meanings/ "1f60d": {"canonical_name": "heart_eyes", "aliases": ["in_love"]}, # blow_a_kiss from https://beebom.com/emoji-meanings/ "1f618": {"canonical_name": "heart_kiss", "aliases": ["blow_a_kiss"]}, "1f617": {"canonical_name": "kiss", "aliases": []}, "1f619": {"canonical_name": "kiss_smiling_eyes", "aliases": []}, "1f61a": {"canonical_name": "kiss_with_blush", "aliases": []}, "1f60b": {"canonical_name": "yum", "aliases": []}, # crazy from https://beebom.com/emoji-meanings/, seems like best emoji for # joking "1f61b": {"canonical_name": "stuck_out_tongue", "aliases": ["mischievous"]}, "1f61c": {"canonical_name": "stuck_out_tongue_wink", "aliases": ["joking", "crazy"]}, "1f61d": {"canonical_name": "stuck_out_tongue_closed_eyes", "aliases": []}, # kaching suggested by user "1f911": {"canonical_name": "money_face", "aliases": ["kaching"]}, # arms_open seems like a natural addition "1f917": {"canonical_name": "hug", "aliases": ["arms_open"]}, "1f913": {"canonical_name": "nerd", "aliases": ["geek"]}, # several sites suggested this was used for "cool", but cool is taken by # Symbols/137 "1f60e": {"canonical_name": "sunglasses", "aliases": []}, "1f921": {"canonical_name": "clown", "aliases": []}, "1f920": {"canonical_name": "cowboy", "aliases": []}, # https://emojipedia.org/smirking-face/ "1f60f": {"canonical_name": "smirk", "aliases": ["smug"]}, "1f612": {"canonical_name": "unamused", "aliases": []}, "1f61e": {"canonical_name": "disappointed", "aliases": []}, # see People/41 "1f614": {"canonical_name": "pensive", "aliases": ["tired"]}, "1f61f": {"canonical_name": "worried", "aliases": []}, # these seem to better capture the glyphs. This is also what :/ turns into # in Google Hangouts "1f615": {"canonical_name": "oh_no", "aliases": ["half_frown", "concerned", "confused"]}, "1f641": {"canonical_name": "frown", "aliases": ["slight_frown"]}, # sad seemed better than putting another frown as the primary name (see # People/37) "2639": {"canonical_name": "sad", "aliases": ["big_frown"]}, # helpless from https://emojipedia.org/persevering-face/ "1f623": {"canonical_name": "persevere", "aliases": ["helpless"]}, # agony seemed like a good addition "1f616": {"canonical_name": "confounded", "aliases": ["agony"]}, # tired doesn't really match any of the 4 images, put it on People/34 "1f62b": {"canonical_name": "anguish", "aliases": []}, # distraught from https://beebom.com/emoji-meanings/ "1f629": {"canonical_name": "weary", "aliases": ["distraught"]}, "1f624": {"canonical_name": "triumph", "aliases": []}, "1f620": {"canonical_name": "angry", "aliases": []}, # mad and grumpy from https://beebom.com/emoji-meanings/, very_angry to # parallel People/44 and show up in typeahead for "ang.." "1f621": {"canonical_name": "rage", "aliases": ["mad", "grumpy", "very_angry"]}, # blank from https://beebom.com/emoji-meanings/, speechless and poker_face # seemed like good ideas for this "1f636": {"canonical_name": "speechless", "aliases": ["no_mouth", "blank", "poker_face"]}, "1f610": {"canonical_name": "neutral", "aliases": []}, "1f611": {"canonical_name": "expressionless", "aliases": []}, "1f62f": {"canonical_name": "hushed", "aliases": []}, "1f626": {"canonical_name": "frowning", "aliases": []}, # pained from https://beebom.com/emoji-meanings/ "1f627": {"canonical_name": "anguished", "aliases": ["pained"]}, # surprise from https://emojipedia.org/face-with-open-mouth/ "1f62e": {"canonical_name": "open_mouth", "aliases": ["surprise"]}, "1f632": {"canonical_name": "astonished", "aliases": []}, "1f635": {"canonical_name": "dizzy", "aliases": []}, # the alternates are from https://emojipedia.org/flushed-face/. shame # doesn't work with the Google emoji "1f633": {"canonical_name": "flushed", "aliases": ["embarrassed", "blushing"]}, "1f631": {"canonical_name": "scream", "aliases": []}, # scared from https://emojipedia.org/fearful-face/, shock seemed like a # nice addition "1f628": {"canonical_name": "fear", "aliases": ["scared", "shock"]}, "1f630": {"canonical_name": "cold_sweat", "aliases": []}, "1f622": {"canonical_name": "cry", "aliases": []}, # stressed from https://beebom.com/emoji-meanings/. The internet generally # didn't seem to know what to make of the dissapointed_relieved name, and I # got the sense it wasn't an emotion that was often used. Hence replaced it # with exhausted. "1f625": {"canonical_name": "exhausted", "aliases": ["disappointed_relieved", "stressed"]}, "1f924": {"canonical_name": "drooling", "aliases": []}, "1f62d": {"canonical_name": "sob", "aliases": []}, "1f613": {"canonical_name": "sweat", "aliases": []}, "1f62a": {"canonical_name": "sleepy", "aliases": []}, "1f634": {"canonical_name": "sleeping", "aliases": []}, "1f644": {"canonical_name": "rolling_eyes", "aliases": []}, "1f914": {"canonical_name": "thinking", "aliases": []}, "1f925": {"canonical_name": "lying", "aliases": []}, # seems like best emoji for nervous/anxious "1f62c": {"canonical_name": "grimacing", "aliases": ["nervous", "anxious"]}, # zip_it from https://mashable.com/2015/10/23/ios-9-1-emoji-guide/, # lips_sealed from https://emojipedia.org/zipper-mouth-face/, rest seemed # like reasonable additions "1f910": { "canonical_name": "silence", "aliases": ["quiet", "hush", "zip_it", "lips_are_sealed"], }, # queasy seemed like a natural addition "1f922": {"canonical_name": "nauseated", "aliases": ["queasy"]}, "1f927": {"canonical_name": "sneezing", "aliases": []}, "1f637": {"canonical_name": "mask", "aliases": []}, # flu from https://mashable.com/2015/10/23/ios-9-1-emoji-guide/, sick from # https://emojipedia.org/face-with-thermometer/, face_with_thermometer so # it shows up in typeahead (thermometer taken by Objects/82) "1f912": { "canonical_name": "sick", "aliases": ["flu", "face_with_thermometer", "ill", "fever"], }, # hurt and injured from https://beebom.com/emoji-meanings/. Chose hurt as # primary since I think it can cover a wider set of things (e.g. emotional # hurt) "1f915": {"canonical_name": "hurt", "aliases": ["head_bandage", "injured"]}, # devil from https://emojipedia.org/smiling-face-with-horns/, # smiling_face_with_horns from gemoji/Unicode "1f608": { "canonical_name": "smiling_devil", "aliases": ["smiling_imp", "smiling_face_with_horns"], }, # angry_devil from https://beebom.com/emoji-meanings/ "1f47f": {"canonical_name": "devil", "aliases": ["imp", "angry_devil"]}, "1f479": {"canonical_name": "ogre", "aliases": []}, "1f47a": {"canonical_name": "goblin", "aliases": []}, # pile_of_poo from gemoji/Unicode "1f4a9": {"canonical_name": "poop", "aliases": ["pile_of_poo"]}, # alternates seemed like reasonable additions "1f47b": {"canonical_name": "ghost", "aliases": ["boo", "spooky", "haunted"]}, "1f480": {"canonical_name": "skull", "aliases": []}, # alternates seemed like reasonable additions "2620": { "canonical_name": "skull_and_crossbones", "aliases": ["pirate", "death", "hazard", "toxic", "poison"], }, # ufo seemed like a natural addition "1f47d": {"canonical_name": "alien", "aliases": ["ufo"]}, "1f47e": {"canonical_name": "space_invader", "aliases": []}, "1f916": {"canonical_name": "robot", "aliases": []}, # pumpkin seemed like a natural addition "1f383": {"canonical_name": "jack-o-lantern", "aliases": ["pumpkin"]}, "1f63a": {"canonical_name": "smiley_cat", "aliases": []}, "1f638": {"canonical_name": "smile_cat", "aliases": []}, "1f639": {"canonical_name": "joy_cat", "aliases": []}, "1f63b": {"canonical_name": "heart_eyes_cat", "aliases": []}, # smug_cat to parallel People/31 "1f63c": {"canonical_name": "smirk_cat", "aliases": ["smug_cat"]}, "1f63d": {"canonical_name": "kissing_cat", "aliases": []}, # weary_cat from Unicode/gemoji "1f640": {"canonical_name": "scream_cat", "aliases": ["weary_cat"]}, "1f63f": {"canonical_name": "crying_cat", "aliases": []}, # angry_cat to better parallel People/45 "1f63e": {"canonical_name": "angry_cat", "aliases": ["pouting_cat"]}, "1f450": {"canonical_name": "open_hands", "aliases": []}, # praise from # https://emojipedia.org/person-raising-both-hands-in-celebration/ "1f64c": {"canonical_name": "raised_hands", "aliases": ["praise"]}, # applause from https://emojipedia.org/clapping-hands-sign/ "1f44f": {"canonical_name": "clap", "aliases": ["applause"]}, # welcome and thank_you from # https://emojipedia.org/person-with-folded-hands/, namaste from indian # culture "1f64f": {"canonical_name": "pray", "aliases": ["welcome", "thank_you", "namaste"]}, # done_deal seems like a natural addition "1f91d": {"canonical_name": "handshake", "aliases": ["done_deal"]}, "1f44d": {"canonical_name": "+1", "aliases": ["thumbs_up", "like"]}, "1f44e": {"canonical_name": "-1", "aliases": ["thumbs_down"]}, # fist_bump from https://beebom.com/emoji-meanings/ "1f44a": {"canonical_name": "fist_bump", "aliases": ["punch"]}, # used as power in social justice movements "270a": {"canonical_name": "fist", "aliases": ["power"]}, "1f91b": {"canonical_name": "left_fist", "aliases": []}, "1f91c": {"canonical_name": "right_fist", "aliases": []}, "1f91e": {"canonical_name": "fingers_crossed", "aliases": []}, # seems to be mostly used as peace on twitter "270c": {"canonical_name": "peace_sign", "aliases": ["victory"]}, # https://emojipedia.org/sign-of-the-horns/ "1f918": {"canonical_name": "rock_on", "aliases": ["sign_of_the_horns"]}, # got_it seems like a natural addition "1f44c": {"canonical_name": "ok", "aliases": ["got_it"]}, "1f448": {"canonical_name": "point_left", "aliases": []}, "1f449": {"canonical_name": "point_right", "aliases": []}, # :this: is a way of emphasizing the previous message. point_up instead of # point_up_2 so that point_up better matches the other point_*s "1f446": {"canonical_name": "point_up", "aliases": ["this"]}, "1f447": {"canonical_name": "point_down", "aliases": []}, # People/114 is point_up. These seemed better than naming it point_up_2, # and point_of_information means it will come up in typeahead for 'point' "261d": { "canonical_name": "wait_one_second", "aliases": ["point_of_information", "asking_a_question"], }, "270b": {"canonical_name": "hand", "aliases": ["raised_hand"]}, # seems like best emoji for stop, raised_back_of_hand doesn't seem that # useful "1f91a": {"canonical_name": "stop", "aliases": []}, # seems like best emoji for high_five, raised_hand_with_fingers_splayed # doesn't seem that useful "1f590": {"canonical_name": "high_five", "aliases": ["palm"]}, # https://mashable.com/2015/10/23/ios-9-1-emoji-guide/ "1f596": {"canonical_name": "spock", "aliases": ["live_long_and_prosper"]}, # People/119 is a better 'hi', but 'hi' will never show up in the typeahead # due to 'high_five' "1f44b": {"canonical_name": "wave", "aliases": ["hello", "hi"]}, "1f919": {"canonical_name": "call_me", "aliases": []}, # flexed_biceps from gemoji/Unicode, strong seemed like a good addition "1f4aa": {"canonical_name": "muscle", "aliases": []}, "1f595": {"canonical_name": "middle_finger", "aliases": []}, "270d": {"canonical_name": "writing", "aliases": []}, "1f933": {"canonical_name": "selfie", "aliases": []}, # Couldn't figure out why iamcal chose nail_care. Unicode uses nail_polish, # gemoji uses both "1f485": {"canonical_name": "nail_polish", "aliases": ["nail_care"]}, "1f48d": {"canonical_name": "ring", "aliases": []}, "1f484": {"canonical_name": "lipstick", "aliases": []}, # People/18 seems like a better kiss for most circumstances "1f48b": {"canonical_name": "lipstick_kiss", "aliases": []}, # mouth from gemoji/Unicode "1f444": {"canonical_name": "lips", "aliases": ["mouth"]}, "1f445": {"canonical_name": "tongue", "aliases": []}, "1f442": {"canonical_name": "ear", "aliases": []}, "1f443": {"canonical_name": "nose", "aliases": []}, # seems a better feet than Nature/86 (paw_prints) "1f463": {"canonical_name": "footprints", "aliases": ["feet"]}, "1f441": {"canonical_name": "eye", "aliases": []}, # seemed the best emoji for looking "1f440": {"canonical_name": "eyes", "aliases": ["looking"]}, "1f5e3": {"canonical_name": "speaking_head", "aliases": []}, # shadow seems like a good addition "1f464": {"canonical_name": "silhouette", "aliases": ["shadow"]}, # to parallel People/139 "1f465": {"canonical_name": "silhouettes", "aliases": ["shadows"]}, "1f476": {"canonical_name": "baby", "aliases": []}, "1f466": {"canonical_name": "boy", "aliases": []}, "1f467": {"canonical_name": "girl", "aliases": []}, "1f468": {"canonical_name": "man", "aliases": []}, "1f469": {"canonical_name": "woman", "aliases": []}, # It's used on twitter a bunch, either when showing off hair, or in a way # where People/144 would substitute. It'd be nice if there were another # emoji one could use for "good hair", but I think not a big loss to not # have one for Zulip, and not worth the eurocentrism. # '1f471': {'canonical_name': 'X', 'aliases': ['person_with_blond_hair']}, # Added elderly since I think some people prefer that term "1f474": {"canonical_name": "older_man", "aliases": ["elderly_man"]}, # Added elderly since I think some people prefer that term "1f475": {"canonical_name": "older_woman", "aliases": ["elderly_woman"]}, "1f472": {"canonical_name": "gua_pi_mao", "aliases": []}, "1f473": {"canonical_name": "turban", "aliases": []}, # police seems like a more polite term, and matches the Unicode "1f46e": {"canonical_name": "police", "aliases": ["cop"]}, "1f477": {"canonical_name": "construction_worker", "aliases": []}, "1f482": {"canonical_name": "guard", "aliases": []}, # detective from gemoji, sneaky from # https://mashable.com/2015/10/23/ios-9-1-emoji-guide/, agent seems a # reasonable addition "1f575": {"canonical_name": "detective", "aliases": ["spy", "sleuth", "agent", "sneaky"]}, # mrs_claus from https://emojipedia.org/mother-christmas/ "1f936": {"canonical_name": "mother_christmas", "aliases": ["mrs_claus"]}, "1f385": {"canonical_name": "santa", "aliases": []}, "1f478": {"canonical_name": "princess", "aliases": []}, "1f934": {"canonical_name": "prince", "aliases": []}, "1f470": {"canonical_name": "bride", "aliases": []}, "1f935": {"canonical_name": "tuxedo", "aliases": []}, "1f47c": {"canonical_name": "angel", "aliases": []}, # expecting seems like a good addition "1f930": {"canonical_name": "pregnant", "aliases": ["expecting"]}, "1f647": {"canonical_name": "bow", "aliases": []}, # mostly used sassily. person_tipping_hand from # https://emojipedia.org/information-desk-person/ "1f481": {"canonical_name": "information_desk_person", "aliases": ["person_tipping_hand"]}, # no_signal to parallel People/207. Nope seems like a reasonable addition "1f645": {"canonical_name": "no_signal", "aliases": ["nope"]}, "1f646": {"canonical_name": "ok_signal", "aliases": []}, # pick_me seems like a good addition "1f64b": {"canonical_name": "raising_hand", "aliases": ["pick_me"]}, "1f926": {"canonical_name": "face_palm", "aliases": []}, "1f937": {"canonical_name": "shrug", "aliases": []}, "1f64e": {"canonical_name": "person_pouting", "aliases": []}, "1f64d": {"canonical_name": "person_frowning", "aliases": []}, "1f487": {"canonical_name": "haircut", "aliases": []}, "1f486": {"canonical_name": "massage", "aliases": []}, # hover seems like a reasonable addition "1f574": {"canonical_name": "levitating", "aliases": ["hover"]}, "1f483": {"canonical_name": "dancer", "aliases": []}, "1f57a": {"canonical_name": "dancing", "aliases": ["disco"]}, "1f46f": {"canonical_name": "dancers", "aliases": []}, # pedestrian seems like reasonable addition "1f6b6": {"canonical_name": "walking", "aliases": ["pedestrian"]}, "1f3c3": {"canonical_name": "running", "aliases": ["runner"]}, "1f46b": {"canonical_name": "man_and_woman_holding_hands", "aliases": ["man_and_woman_couple"]}, # to parallel People/234 "1f46d": {"canonical_name": "two_women_holding_hands", "aliases": ["women_couple"]}, # to parallel People/234 "1f46c": {"canonical_name": "two_men_holding_hands", "aliases": ["men_couple"]}, # no need for man-woman-boy, since we aren't including the other family # combos "1f46a": {"canonical_name": "family", "aliases": []}, "1f45a": {"canonical_name": "clothing", "aliases": []}, "1f455": {"canonical_name": "shirt", "aliases": ["tshirt"]}, # denim seems like a good addition "1f456": {"canonical_name": "jeans", "aliases": ["denim"]}, # tie is shorter, and a bit more general "1f454": {"canonical_name": "tie", "aliases": []}, "1f457": {"canonical_name": "dress", "aliases": []}, "1f459": {"canonical_name": "bikini", "aliases": []}, "1f458": {"canonical_name": "kimono", "aliases": []}, # I feel like this is always used in the plural "1f460": {"canonical_name": "high_heels", "aliases": []}, # flip_flops seems like a reasonable addition "1f461": {"canonical_name": "sandal", "aliases": ["flip_flops"]}, "1f462": {"canonical_name": "boot", "aliases": []}, "1f45e": {"canonical_name": "shoe", "aliases": []}, # running_shoe is from gemoji, sneaker seems like a reasonable addition "1f45f": {"canonical_name": "athletic_shoe", "aliases": ["sneaker", "running_shoe"]}, "1f452": {"canonical_name": "hat", "aliases": []}, "1f3a9": {"canonical_name": "top_hat", "aliases": []}, # graduate seems like a better word for this "1f393": {"canonical_name": "graduate", "aliases": ["mortar_board"]}, # king and queen seem like good additions "1f451": {"canonical_name": "crown", "aliases": ["queen", "king"]}, # safety and invincibility inspired by # https://mashable.com/2015/10/23/ios-9-1-emoji-guide/. hard_hat and # rescue_worker seem like good additions "26d1": { "canonical_name": "helmet", "aliases": ["hard_hat", "rescue_worker", "safety_first", "invincible"], }, # backpack from gemoji, dominates satchel on Google Trends "1f392": {"canonical_name": "backpack", "aliases": ["satchel"]}, "1f45d": {"canonical_name": "pouch", "aliases": []}, "1f45b": {"canonical_name": "purse", "aliases": []}, "1f45c": {"canonical_name": "handbag", "aliases": []}, "1f4bc": {"canonical_name": "briefcase", "aliases": []}, # glasses seems a more common term than eyeglasses, spectacles seems like a # reasonable synonym to add "1f453": {"canonical_name": "glasses", "aliases": ["spectacles"]}, "1f576": {"canonical_name": "dark_sunglasses", "aliases": []}, "1f302": {"canonical_name": "closed_umbrella", "aliases": []}, "2602": {"canonical_name": "umbrella", "aliases": []}, # Some animals have a Unicode codepoint "<animal>", some have a codepoint # "<animal> face", and some have both. If an animal has just a single # codepoint, we call it <animal>, regardless of what the codepoint is. If # an animal has both, we call the "<animal>" codepoint <animal>, and come # up with something else useful-seeming for the "<animal> face" codepoint. # The reason we chose "<animal> face" for the non-standard name (instead of # giving "<animal>" the non-standard name, as iamcal does) is because the # apple emoji for the "<animal>"s are too realistic. E.g. Apple's Nature/76 # is less plausibly a puppy than this one. "1f436": {"canonical_name": "puppy", "aliases": []}, "1f431": {"canonical_name": "kitten", "aliases": []}, "1f42d": {"canonical_name": "dormouse", "aliases": []}, "1f439": {"canonical_name": "hamster", "aliases": []}, "1f430": {"canonical_name": "bunny", "aliases": []}, "1f98a": {"canonical_name": "fox", "aliases": []}, "1f43b": {"canonical_name": "bear", "aliases": []}, "1f43c": {"canonical_name": "panda", "aliases": []}, "1f428": {"canonical_name": "koala", "aliases": []}, "1f42f": {"canonical_name": "tiger_cub", "aliases": []}, "1f981": {"canonical_name": "lion", "aliases": []}, "1f42e": {"canonical_name": "calf", "aliases": []}, "1f437": {"canonical_name": "piglet", "aliases": []}, "1f43d": {"canonical_name": "pig_nose", "aliases": []}, "1f438": {"canonical_name": "frog", "aliases": []}, "1f435": {"canonical_name": "monkey_face", "aliases": []}, "1f648": {"canonical_name": "see_no_evil", "aliases": []}, "1f649": {"canonical_name": "hear_no_evil", "aliases": []}, "1f64a": {"canonical_name": "speak_no_evil", "aliases": []}, "1f412": {"canonical_name": "monkey", "aliases": []}, # cluck seemed like a good addition "1f414": {"canonical_name": "chicken", "aliases": ["cluck"]}, "1f427": {"canonical_name": "penguin", "aliases": []}, "1f426": {"canonical_name": "bird", "aliases": []}, "1f424": {"canonical_name": "chick", "aliases": ["baby_chick"]}, "1f423": {"canonical_name": "hatching", "aliases": ["hatching_chick"]}, # https://www.iemoji.com/view/emoji/668/animals-nature/front-facing-baby-chick "1f425": {"canonical_name": "new_baby", "aliases": []}, "1f986": {"canonical_name": "duck", "aliases": []}, "1f985": {"canonical_name": "eagle", "aliases": []}, "1f989": {"canonical_name": "owl", "aliases": []}, "1f987": {"canonical_name": "bat", "aliases": []}, "1f43a": {"canonical_name": "wolf", "aliases": []}, "1f417": {"canonical_name": "boar", "aliases": []}, "1f434": {"canonical_name": "pony", "aliases": []}, "1f984": {"canonical_name": "unicorn", "aliases": []}, # buzz seemed like a reasonable addition "1f41d": {"canonical_name": "bee", "aliases": ["buzz", "honeybee"]}, # caterpillar seemed like a reasonable addition "1f41b": {"canonical_name": "bug", "aliases": ["caterpillar"]}, "1f98b": {"canonical_name": "butterfly", "aliases": []}, "1f40c": {"canonical_name": "snail", "aliases": []}, # spiral_shell from Unicode/gemoji, the others seemed like reasonable # additions "1f41a": {"canonical_name": "shell", "aliases": ["seashell", "conch", "spiral_shell"]}, # Unicode/gemoji have lady_beetle; hopefully with ladybug we get both the # people that prefer lady_beetle (with beetle) and ladybug. There is also # ladybird, but seems a bit much for this to complete for bird. "1f41e": {"canonical_name": "beetle", "aliases": ["ladybug"]}, "1f41c": {"canonical_name": "ant", "aliases": []}, "1f577": {"canonical_name": "spider", "aliases": []}, "1f578": {"canonical_name": "web", "aliases": ["spider_web"]}, # tortoise seemed like a reasonable addition "1f422": {"canonical_name": "turtle", "aliases": ["tortoise"]}, # put in a few animal sounds, including this one "1f40d": {"canonical_name": "snake", "aliases": ["hiss"]}, "1f98e": {"canonical_name": "lizard", "aliases": ["gecko"]}, "1f982": {"canonical_name": "scorpion", "aliases": []}, "1f980": {"canonical_name": "crab", "aliases": []}, "1f991": {"canonical_name": "squid", "aliases": []}, "1f419": {"canonical_name": "octopus", "aliases": []}, "1f990": {"canonical_name": "shrimp", "aliases": []}, "1f420": {"canonical_name": "tropical_fish", "aliases": []}, "1f41f": {"canonical_name": "fish", "aliases": []}, "1f421": {"canonical_name": "blowfish", "aliases": []}, "1f42c": {"canonical_name": "dolphin", "aliases": ["flipper"]}, "1f988": {"canonical_name": "shark", "aliases": []}, "1f433": {"canonical_name": "whale", "aliases": []}, # https://emojipedia.org/whale/ "1f40b": {"canonical_name": "humpback_whale", "aliases": []}, "1f40a": {"canonical_name": "crocodile", "aliases": []}, "1f406": {"canonical_name": "leopard", "aliases": []}, "1f405": {"canonical_name": "tiger", "aliases": []}, "1f403": {"canonical_name": "water_buffalo", "aliases": []}, "1f402": {"canonical_name": "ox", "aliases": ["bull"]}, "1f404": {"canonical_name": "cow", "aliases": []}, "1f98c": {"canonical_name": "deer", "aliases": []}, # https://emojipedia.org/dromedary-camel/ "1f42a": {"canonical_name": "arabian_camel", "aliases": []}, "1f42b": {"canonical_name": "camel", "aliases": []}, "1f418": {"canonical_name": "elephant", "aliases": []}, "1f98f": {"canonical_name": "rhinoceros", "aliases": []}, "1f98d": {"canonical_name": "gorilla", "aliases": []}, "1f40e": {"canonical_name": "horse", "aliases": []}, "1f416": {"canonical_name": "pig", "aliases": ["oink"]}, "1f410": {"canonical_name": "goat", "aliases": []}, "1f40f": {"canonical_name": "ram", "aliases": []}, "1f411": {"canonical_name": "sheep", "aliases": ["baa"]}, "1f415": {"canonical_name": "dog", "aliases": ["woof"]}, "1f429": {"canonical_name": "poodle", "aliases": []}, "1f408": {"canonical_name": "cat", "aliases": ["meow"]}, # alarm seemed like a fun addition "1f413": {"canonical_name": "rooster", "aliases": ["alarm", "cock-a-doodle-doo"]}, "1f983": {"canonical_name": "turkey", "aliases": []}, "1f54a": {"canonical_name": "dove", "aliases": ["dove_of_peace"]}, "1f407": {"canonical_name": "rabbit", "aliases": []}, "1f401": {"canonical_name": "mouse", "aliases": []}, "1f400": {"canonical_name": "rat", "aliases": []}, "1f43f": {"canonical_name": "chipmunk", "aliases": []}, # paws seemed like reasonable addition. Put feet at People/135 "1f43e": {"canonical_name": "paw_prints", "aliases": ["paws"]}, "1f409": {"canonical_name": "dragon", "aliases": []}, "1f432": {"canonical_name": "dragon_face", "aliases": []}, "1f335": {"canonical_name": "cactus", "aliases": []}, "1f384": {"canonical_name": "holiday_tree", "aliases": []}, "1f332": {"canonical_name": "evergreen_tree", "aliases": []}, "1f333": {"canonical_name": "tree", "aliases": ["deciduous_tree"]}, "1f334": {"canonical_name": "palm_tree", "aliases": []}, # sprout seemed like a reasonable addition "1f331": {"canonical_name": "seedling", "aliases": ["sprout"]}, # seemed like the best emoji for plant "1f33f": {"canonical_name": "herb", "aliases": ["plant"]}, # clover seemed like a reasonable addition "2618": {"canonical_name": "shamrock", "aliases": ["clover"]}, # lucky seems more useful "1f340": {"canonical_name": "lucky", "aliases": ["four_leaf_clover"]}, "1f38d": {"canonical_name": "bamboo", "aliases": []}, # https://emojipedia.org/tanabata-tree/ "1f38b": {"canonical_name": "wish_tree", "aliases": ["tanabata_tree"]}, # seemed like good additions. Used fall instead of autumn, since don't have # the rest of the seasons, and could imagine someone using both meanings of # fall. "1f343": {"canonical_name": "leaves", "aliases": ["wind", "fall"]}, "1f342": {"canonical_name": "fallen_leaf", "aliases": []}, "1f341": {"canonical_name": "maple_leaf", "aliases": []}, "1f344": {"canonical_name": "mushroom", "aliases": []}, # harvest seems more useful "1f33e": {"canonical_name": "harvest", "aliases": ["ear_of_rice"]}, "1f490": {"canonical_name": "bouquet", "aliases": []}, # seems like the best emoji for flower "1f337": {"canonical_name": "tulip", "aliases": ["flower"]}, "1f339": {"canonical_name": "rose", "aliases": []}, # crushed suggest by a user "1f940": {"canonical_name": "wilted_flower", "aliases": ["crushed"]}, "1f33b": {"canonical_name": "sunflower", "aliases": []}, "1f33c": {"canonical_name": "blossom", "aliases": []}, "1f338": {"canonical_name": "cherry_blossom", "aliases": []}, "1f33a": {"canonical_name": "hibiscus", "aliases": []}, "1f30e": {"canonical_name": "earth_americas", "aliases": []}, "1f30d": {"canonical_name": "earth_africa", "aliases": []}, "1f30f": {"canonical_name": "earth_asia", "aliases": []}, "1f315": {"canonical_name": "full_moon", "aliases": []}, # too many useless moons. Don't seem to get much use on twitter, and clog # up typeahead for moon. # '1f316': {'canonical_name': 'X', 'aliases': ['waning_crescent_moon']}, # '1f317': {'canonical_name': 'X', 'aliases': ['last_quarter_moon']}, # '1f318': {'canonical_name': 'X', 'aliases': ['waning_crescent_moon']}, "1f311": {"canonical_name": "new_moon", "aliases": []}, # '1f312': {'canonical_name': 'X', 'aliases': ['waxing_crescent_moon']}, # '1f313': {'canonical_name': 'X', 'aliases': ['first_quarter_moon']}, "1f314": {"canonical_name": "waxing_moon", "aliases": []}, "1f31a": {"canonical_name": "new_moon_face", "aliases": []}, "1f31d": {"canonical_name": "moon_face", "aliases": []}, "1f31e": {"canonical_name": "sun_face", "aliases": []}, # goodnight seems way more useful "1f31b": {"canonical_name": "goodnight", "aliases": []}, # '1f31c': {'canonical_name': 'X', 'aliases': ['last_quarter_moon_with_face']}, # seems like the best emoji for moon "1f319": {"canonical_name": "moon", "aliases": []}, # dizzy taken by People/54, had to come up with something else "1f4ab": {"canonical_name": "seeing_stars", "aliases": []}, "2b50": {"canonical_name": "star", "aliases": []}, # glowing_star from gemoji/Unicode "1f31f": {"canonical_name": "glowing_star", "aliases": []}, # glamour seems like a reasonable addition "2728": {"canonical_name": "sparkles", "aliases": ["glamour"]}, # high_voltage from gemoji/Unicode "26a1": {"canonical_name": "high_voltage", "aliases": ["zap"]}, # https://emojipedia.org/fire/ "1f525": {"canonical_name": "fire", "aliases": ["lit", "hot", "flame"]}, # explosion and crash seem like reasonable additions "1f4a5": {"canonical_name": "boom", "aliases": ["explosion", "crash", "collision"]}, # meteor seems like a reasonable addition "2604": {"canonical_name": "comet", "aliases": ["meteor"]}, "2600": {"canonical_name": "sunny", "aliases": []}, "1f324": {"canonical_name": "mostly_sunny", "aliases": []}, # partly_cloudy for the glass half empty people "26c5": {"canonical_name": "partly_sunny", "aliases": ["partly_cloudy"]}, "1f325": {"canonical_name": "cloudy", "aliases": []}, # sunshowers seems like a more fun term "1f326": { "canonical_name": "sunshowers", "aliases": ["sun_and_rain", "partly_sunny_with_rain"], }, # pride and lgbtq seem like reasonable additions "1f308": {"canonical_name": "rainbow", "aliases": ["pride", "lgbtq"]}, # overcast seems like a good addition "2601": {"canonical_name": "cloud", "aliases": ["overcast"]}, # suggested by user typing these into their typeahead. "1f327": {"canonical_name": "rainy", "aliases": ["soaked", "drenched"]}, # thunderstorm seems better for this emoji, and thunder_and_rain more # evocative than thunder_cloud_and_rain "26c8": {"canonical_name": "thunderstorm", "aliases": ["thunder_and_rain"]}, # lightning_storm seemed better than lightning_cloud "1f329": {"canonical_name": "lightning", "aliases": ["lightning_storm"]}, # snowy to parallel sunny, cloudy, etc; snowstorm seems like a good # addition "1f328": {"canonical_name": "snowy", "aliases": ["snowstorm"]}, "2603": {"canonical_name": "snowman", "aliases": []}, # don't need two snowmen. frosty is nice because it's a weather (primary # benefit) and also a snowman (one that suffered from not having snow, in # fact) "26c4": {"canonical_name": "frosty", "aliases": []}, "2744": {"canonical_name": "snowflake", "aliases": []}, # the internet didn't seem to have a good use for this emoji. windy is a # good weather that is otherwise not represented. mother_nature from # https://emojipedia.org/wind-blowing-face/ "1f32c": {"canonical_name": "windy", "aliases": ["mother_nature"]}, "1f4a8": {"canonical_name": "dash", "aliases": []}, # tornado_cloud comes from the Unicode, but e.g. gemoji drops the cloud "1f32a": {"canonical_name": "tornado", "aliases": []}, # hazy seemed like a good addition "1f32b": {"canonical_name": "fog", "aliases": ["hazy"]}, "1f30a": {"canonical_name": "ocean", "aliases": []}, # drop seems better than droplet, since could be used for its other # meanings. water drop partly so that it shows up in typeahead for water "1f4a7": {"canonical_name": "drop", "aliases": ["water_drop"]}, "1f4a6": {"canonical_name": "sweat_drops", "aliases": []}, "2614": {"canonical_name": "umbrella_with_rain", "aliases": []}, "1f34f": {"canonical_name": "green_apple", "aliases": []}, "1f34e": {"canonical_name": "apple", "aliases": []}, "1f350": {"canonical_name": "pear", "aliases": []}, # An argument for not calling this orange is to save the color for a color # swatch, but we can deal with that when it happens. Mandarin is from # https://emojipedia.org/tangerine/, also like that it has a second meaning "1f34a": {"canonical_name": "orange", "aliases": ["tangerine", "mandarin"]}, "1f34b": {"canonical_name": "lemon", "aliases": []}, "1f34c": {"canonical_name": "banana", "aliases": []}, "1f349": {"canonical_name": "watermelon", "aliases": []}, "1f347": {"canonical_name": "grapes", "aliases": []}, "1f353": {"canonical_name": "strawberry", "aliases": []}, "1f348": {"canonical_name": "melon", "aliases": []}, "1f352": {"canonical_name": "cherries", "aliases": []}, "1f351": {"canonical_name": "peach", "aliases": []}, "1f34d": {"canonical_name": "pineapple", "aliases": []}, "1f95d": {"canonical_name": "kiwi", "aliases": []}, "1f951": {"canonical_name": "avocado", "aliases": []}, "1f345": {"canonical_name": "tomato", "aliases": []}, "1f346": {"canonical_name": "eggplant", "aliases": []}, "1f952": {"canonical_name": "cucumber", "aliases": []}, "1f955": {"canonical_name": "carrot", "aliases": []}, # maize is from Unicode "1f33d": {"canonical_name": "corn", "aliases": ["maize"]}, # chili_pepper seems like a reasonable addition "1f336": {"canonical_name": "hot_pepper", "aliases": ["chili_pepper"]}, "1f954": {"canonical_name": "potato", "aliases": []}, # yam seems better than sweet_potato, since we already have a potato (not a # strong argument, but is better on the typeahead not to have emoji that # share long prefixes) "1f360": {"canonical_name": "yam", "aliases": ["sweet_potato"]}, "1f330": {"canonical_name": "chestnut", "aliases": []}, "1f95c": {"canonical_name": "peanuts", "aliases": []}, "1f36f": {"canonical_name": "honey", "aliases": []}, "1f950": {"canonical_name": "croissant", "aliases": []}, "1f35e": {"canonical_name": "bread", "aliases": []}, "1f956": {"canonical_name": "baguette", "aliases": []}, "1f9c0": {"canonical_name": "cheese", "aliases": []}, "1f95a": {"canonical_name": "egg", "aliases": []}, # already have an egg in Foods/31, though I guess wouldn't be a big deal to # add it here. "1f373": {"canonical_name": "cooking", "aliases": []}, "1f953": {"canonical_name": "bacon", "aliases": []}, # there's no lunch and dinner, which is a small negative against adding # breakfast "1f95e": {"canonical_name": "pancakes", "aliases": ["breakfast"]}, # There is already shrimp in Nature/51, and tempura seems like a better # description "1f364": {"canonical_name": "tempura", "aliases": []}, # drumstick seems like a better description "1f357": {"canonical_name": "drumstick", "aliases": ["poultry"]}, "1f356": {"canonical_name": "meat", "aliases": []}, "1f355": {"canonical_name": "pizza", "aliases": []}, "1f32d": {"canonical_name": "hotdog", "aliases": []}, "1f354": {"canonical_name": "hamburger", "aliases": []}, "1f35f": {"canonical_name": "fries", "aliases": []}, # https://emojipedia.org/stuffed-flatbread/ "1f959": { "canonical_name": "doner_kebab", "aliases": ["shawarma", "souvlaki", "stuffed_flatbread"], }, "1f32e": {"canonical_name": "taco", "aliases": []}, "1f32f": {"canonical_name": "burrito", "aliases": []}, "1f957": {"canonical_name": "salad", "aliases": []}, # I think Foods/49 is a better :food: "1f958": {"canonical_name": "paella", "aliases": []}, "1f35d": {"canonical_name": "spaghetti", "aliases": []}, # seems like the best noodles? maybe this should be Foods/47? Noodles seem # like a bigger thing in east asia than in europe, so going with that. "1f35c": {"canonical_name": "ramen", "aliases": ["noodles"]}, # seems like the best :food:. Also a reasonable :soup:, though the Google # one is indeed more a pot of food (the Unicode) than a soup "1f372": {"canonical_name": "food", "aliases": ["soup", "stew"]}, # naruto is actual name, and I think don't need this to autocomplete for # "fish" "1f365": {"canonical_name": "naruto", "aliases": []}, "1f363": {"canonical_name": "sushi", "aliases": []}, "1f371": {"canonical_name": "bento", "aliases": []}, "1f35b": {"canonical_name": "curry", "aliases": []}, "1f35a": {"canonical_name": "rice", "aliases": []}, # onigiri is actual name, and I think don't need this to typeahead complete # for "rice" "1f359": {"canonical_name": "onigiri", "aliases": []}, # leaving rice_cracker in, so that we have something for cracker "1f358": {"canonical_name": "senbei", "aliases": ["rice_cracker"]}, "1f362": {"canonical_name": "oden", "aliases": []}, "1f361": {"canonical_name": "dango", "aliases": []}, "1f367": {"canonical_name": "shaved_ice", "aliases": []}, # seemed like the best emoji for gelato "1f368": {"canonical_name": "ice_cream", "aliases": ["gelato"]}, # already have ice_cream in Foods/60, and soft_serve seems like a # potentially fun emoji to have in conjunction with ice_cream. Put in # soft_ice_cream so it typeahead completes on ice_cream as well. "1f366": {"canonical_name": "soft_serve", "aliases": ["soft_ice_cream"]}, "1f370": {"canonical_name": "cake", "aliases": []}, "1f382": {"canonical_name": "birthday", "aliases": []}, # flan seems like a reasonable addition "1f36e": {"canonical_name": "custard", "aliases": ["flan"]}, "1f36d": {"canonical_name": "lollipop", "aliases": []}, "1f36c": {"canonical_name": "candy", "aliases": []}, "1f36b": {"canonical_name": "chocolate", "aliases": []}, "1f37f": {"canonical_name": "popcorn", "aliases": []}, # donut dominates doughnut on # https://trends.google.com/trends/explore?q=doughnut,donut "1f369": {"canonical_name": "donut", "aliases": ["doughnut"]}, "1f36a": {"canonical_name": "cookie", "aliases": []}, "1f95b": {"canonical_name": "milk", "aliases": ["glass_of_milk"]}, "1f37c": {"canonical_name": "baby_bottle", "aliases": []}, "2615": {"canonical_name": "coffee", "aliases": []}, "1f375": {"canonical_name": "tea", "aliases": []}, "1f376": {"canonical_name": "sake", "aliases": []}, "1f37a": {"canonical_name": "beer", "aliases": []}, "1f37b": {"canonical_name": "beers", "aliases": []}, "1f942": {"canonical_name": "clink", "aliases": ["toast"]}, "1f377": {"canonical_name": "wine", "aliases": []}, # tumbler means something different in india, and don't want to use # shot_glass given our policy of using school-age-appropriate terms "1f943": {"canonical_name": "small_glass", "aliases": []}, "1f378": {"canonical_name": "cocktail", "aliases": []}, "1f379": {"canonical_name": "tropical_drink", "aliases": []}, "1f37e": {"canonical_name": "champagne", "aliases": []}, "1f944": {"canonical_name": "spoon", "aliases": []}, # Added eating_utensils so this would show up in typeahead for eat. "1f374": {"canonical_name": "fork_and_knife", "aliases": ["eating_utensils"]}, # Seems like the best emoji for hungry and meal. fork_and_knife_and_plate # is from gemoji/Unicode, and I think is better than the shorter iamcal # version in this case. The rest just seemed like good additions. "1f37d": { "canonical_name": "hungry", "aliases": ["meal", "table_setting", "fork_and_knife_with_plate", "lets_eat"], }, # most people interested in this sport call it football "26bd": {"canonical_name": "football", "aliases": ["soccer"]}, "1f3c0": {"canonical_name": "basketball", "aliases": []}, # to distinguish from Activity/1, but is also the Unicode name "1f3c8": {"canonical_name": "american_football", "aliases": []}, "26be": {"canonical_name": "baseball", "aliases": []}, "1f3be": {"canonical_name": "tennis", "aliases": []}, "1f3d0": {"canonical_name": "volleyball", "aliases": []}, "1f3c9": {"canonical_name": "rugby", "aliases": []}, # https://emojipedia.org/billiards/ suggests this is actually used for # billiards, not for "unlucky" or "losing" or some other connotation of # 8ball. The Unicode name is billiards. "1f3b1": {"canonical_name": "billiards", "aliases": ["pool", "8_ball"]}, # ping pong is the Unicode name, and seems slightly more popular on # https://trends.google.com/trends/explore?q=table%20tennis,ping%20pong "1f3d3": {"canonical_name": "ping_pong", "aliases": ["table_tennis"]}, "1f3f8": {"canonical_name": "badminton", "aliases": []}, # gooooooooal seems more useful of a name, though arguably this isn't the # best emoji for it "1f945": {"canonical_name": "gooooooooal", "aliases": ["goal"]}, "1f3d2": {"canonical_name": "ice_hockey", "aliases": []}, "1f3d1": {"canonical_name": "field_hockey", "aliases": []}, # would say bat, but taken by Nature/30 "1f3cf": {"canonical_name": "cricket", "aliases": ["cricket_bat"]}, # hole_in_one seems like a more useful name to have. Sent golf to # Activity/39 "26f3": {"canonical_name": "hole_in_one", "aliases": []}, # archery seems like a reasonable addition "1f3f9": {"canonical_name": "bow_and_arrow", "aliases": ["archery"]}, "1f3a3": {"canonical_name": "fishing", "aliases": []}, "1f94a": {"canonical_name": "boxing_glove", "aliases": []}, # keikogi and dogi are the actual names for this, I believe. black_belt is # I think a more useful name here "1f94b": {"canonical_name": "black_belt", "aliases": ["keikogi", "dogi", "martial_arts"]}, "26f8": {"canonical_name": "ice_skate", "aliases": []}, "1f3bf": {"canonical_name": "ski", "aliases": []}, "26f7": {"canonical_name": "skier", "aliases": []}, "1f3c2": {"canonical_name": "snowboarder", "aliases": []}, # lift is both what lifters call it, and potentially can be used more # generally than weight_lift. The others seemed like good additions. "1f3cb": {"canonical_name": "lift", "aliases": ["work_out", "weight_lift", "gym"]}, # The decisions on tenses here and in the rest of the sports section are # mostly from gut feel. The Unicode itself is all over the place. "1f93a": {"canonical_name": "fencing", "aliases": []}, "1f93c": {"canonical_name": "wrestling", "aliases": []}, # seemed like reasonable additions "1f938": {"canonical_name": "cartwheel", "aliases": ["acrobatics", "gymnastics", "tumbling"]}, # seemed the best emoji for sports "26f9": {"canonical_name": "ball", "aliases": ["sports"]}, "1f93e": {"canonical_name": "handball", "aliases": []}, "1f3cc": {"canonical_name": "golf", "aliases": []}, "1f3c4": {"canonical_name": "surf", "aliases": []}, "1f3ca": {"canonical_name": "swim", "aliases": []}, "1f93d": {"canonical_name": "water_polo", "aliases": []}, # rest seem like reasonable additions "1f6a3": {"canonical_name": "rowboat", "aliases": ["crew", "sculling", "rowing"]}, # horse_riding seems like a reasonable addition "1f3c7": {"canonical_name": "horse_racing", "aliases": ["horse_riding"]}, # at least in the US: this = cyclist, Activity/53 = mountain biker, and # motorcyclist = biker. Mainly from googling around and personal # experience. E.g. https://grammarist.com/usage/cyclist-biker/ for cyclist # and biker, # https://www.theguardian.com/lifeandstyle/2010/oct/24/bike-snobs-guide-cycling-tribes # for mountain biker (I've never heard the term "mountain cyclist", and # they are the only group on that page that gets "biker" instead of # "cyclist") "1f6b4": {"canonical_name": "cyclist", "aliases": []}, # see Activity/51 "1f6b5": {"canonical_name": "mountain_biker", "aliases": []}, "1f3bd": {"canonical_name": "running_shirt", "aliases": []}, # I feel like people call sports medals "medals", and military medals # "military medals". Also see Activity/56 "1f3c5": {"canonical_name": "medal", "aliases": []}, # See Activity/55. military_medal is the gemoji/Unicode "1f396": {"canonical_name": "military_medal", "aliases": []}, # gold and number_one seem like good additions "1f947": {"canonical_name": "first_place", "aliases": ["gold", "number_one"]}, # to parallel Activity/57 "1f948": {"canonical_name": "second_place", "aliases": ["silver"]}, # to parallel Activity/57 "1f949": {"canonical_name": "third_place", "aliases": ["bronze"]}, # seemed the best emoji for winner "1f3c6": {"canonical_name": "trophy", "aliases": ["winner"]}, "1f3f5": {"canonical_name": "rosette", "aliases": []}, "1f397": {"canonical_name": "reminder_ribbon", "aliases": []}, # don't need ticket and admission_ticket (see Activity/64), so made one of # them :pass:. "1f3ab": {"canonical_name": "pass", "aliases": []}, # see Activity/63 "1f39f": {"canonical_name": "ticket", "aliases": []}, "1f3aa": {"canonical_name": "circus", "aliases": []}, "1f939": {"canonical_name": "juggling", "aliases": []}, # rest seem like good additions "1f3ad": {"canonical_name": "performing_arts", "aliases": ["drama", "theater"]}, # rest seem like good additions "1f3a8": {"canonical_name": "art", "aliases": ["palette", "painting"]}, # action seems more useful than clapper, and clapper doesn't seem like that # common of a term "1f3ac": {"canonical_name": "action", "aliases": []}, # seem like good additions "1f3a4": {"canonical_name": "microphone", "aliases": ["mike", "mic"]}, "1f3a7": {"canonical_name": "headphones", "aliases": []}, "1f3bc": {"canonical_name": "musical_score", "aliases": []}, # piano seems more useful than musical_keyboard "1f3b9": {"canonical_name": "piano", "aliases": ["musical_keyboard"]}, "1f941": {"canonical_name": "drum", "aliases": []}, "1f3b7": {"canonical_name": "saxophone", "aliases": []}, "1f3ba": {"canonical_name": "trumpet", "aliases": []}, "1f3b8": {"canonical_name": "guitar", "aliases": []}, "1f3bb": {"canonical_name": "violin", "aliases": []}, # dice seems more useful "1f3b2": {"canonical_name": "dice", "aliases": ["die"]}, # direct_hit from gemoji/Unicode, and seems more useful. bulls_eye seemed # like a reasonable addition "1f3af": {"canonical_name": "direct_hit", "aliases": ["darts", "bulls_eye"]}, # strike seemed more useful than bowling "1f3b3": {"canonical_name": "strike", "aliases": ["bowling"]}, "1f3ae": {"canonical_name": "video_game", "aliases": []}, # gambling seemed more useful than slot_machine "1f3b0": {"canonical_name": "slot_machine", "aliases": []}, # the Google emoji for this is not red "1f697": {"canonical_name": "car", "aliases": []}, # rideshare seems like a reasonable addition "1f695": {"canonical_name": "taxi", "aliases": ["rideshare"]}, # the Google emoji for this is not blue. recreational_vehicle is from # gemoji/Unicode, jeep seemed like a good addition "1f699": {"canonical_name": "recreational_vehicle", "aliases": ["jeep"]}, # school_bus seemed like a reasonable addition, even though the twitter # glyph for this doesn't really look like a school bus "1f68c": {"canonical_name": "bus", "aliases": ["school_bus"]}, "1f68e": {"canonical_name": "trolley", "aliases": []}, "1f3ce": {"canonical_name": "racecar", "aliases": []}, "1f693": {"canonical_name": "police_car", "aliases": []}, "1f691": {"canonical_name": "ambulance", "aliases": []}, # https://trends.google.com/trends/explore?q=fire%20truck,fire%20engine "1f692": {"canonical_name": "fire_truck", "aliases": ["fire_engine"]}, "1f690": {"canonical_name": "minibus", "aliases": []}, # moving_truck and truck for Places/11 and Places/12 seem much better than # the iamcal names "1f69a": {"canonical_name": "moving_truck", "aliases": []}, # see Places/11 for truck. Rest seem reasonable additions. "1f69b": { "canonical_name": "truck", "aliases": ["tractor-trailer", "big_rig", "semi_truck", "transport_truck"], }, "1f69c": {"canonical_name": "tractor", "aliases": []}, # kick_scooter and scooter seem better for Places/14 and Places /16 than # scooter and motor_scooter. "1f6f4": {"canonical_name": "kick_scooter", "aliases": []}, "1f6b2": {"canonical_name": "bike", "aliases": ["bicycle"]}, # see Places/14. Called motor_bike (or bike) in India "1f6f5": {"canonical_name": "scooter", "aliases": ["motor_bike"]}, "1f3cd": {"canonical_name": "motorcycle", "aliases": []}, # siren seems more useful. alert seems like a reasonable addition "1f6a8": {"canonical_name": "siren", "aliases": ["rotating_light", "alert"]}, "1f694": {"canonical_name": "oncoming_police_car", "aliases": []}, "1f68d": {"canonical_name": "oncoming_bus", "aliases": []}, # car to parallel e.g. Places/1 "1f698": {"canonical_name": "oncoming_car", "aliases": ["oncoming_automobile"]}, "1f696": {"canonical_name": "oncoming_taxi", "aliases": []}, # ski_lift seems like a good addition "1f6a1": {"canonical_name": "aerial_tramway", "aliases": ["ski_lift"]}, # gondola seems more useful "1f6a0": {"canonical_name": "gondola", "aliases": ["mountain_cableway"]}, "1f69f": {"canonical_name": "suspension_railway", "aliases": []}, # train_car seems like a reasonable addition "1f683": {"canonical_name": "railway_car", "aliases": ["train_car"]}, # this does not seem like a good emoji for train, especially compared to # Places/33. streetcar seems like a good addition. "1f68b": {"canonical_name": "tram", "aliases": ["streetcar"]}, "1f69e": {"canonical_name": "mountain_railway", "aliases": []}, # elevated_train seems like a reasonable addition "1f69d": {"canonical_name": "monorail", "aliases": ["elevated_train"]}, # from gemoji/Unicode. Also, don't thin we need two bullettrain's "1f684": {"canonical_name": "high_speed_train", "aliases": []}, # Google, Wikipedia, etc. prefer bullet train to bullettrain "1f685": {"canonical_name": "bullet_train", "aliases": []}, "1f688": {"canonical_name": "light_rail", "aliases": []}, "1f682": {"canonical_name": "train", "aliases": ["steam_locomotive"]}, # oncoming_train seems better than train2 "1f686": {"canonical_name": "oncoming_train", "aliases": []}, # saving metro for Symbols/108. The tunnel makes subway more appropriate # anyway. "1f687": {"canonical_name": "subway", "aliases": []}, # all the glyphs of oncoming vehicles have names like oncoming_*. The # alternate names are to parallel the alternates to Places/27. "1f68a": { "canonical_name": "oncoming_tram", "aliases": ["oncoming_streetcar", "oncoming_trolley"], }, "1f689": {"canonical_name": "station", "aliases": []}, "1f681": {"canonical_name": "helicopter", "aliases": []}, "1f6e9": {"canonical_name": "small_airplane", "aliases": []}, "2708": {"canonical_name": "airplane", "aliases": []}, # take_off seems more useful than airplane_departure. departure also seems # more useful than airplane_departure. Arguably departure should be the # primary, since arrival is probably more useful than landing in Places/42, # but going with this for now. "1f6eb": {"canonical_name": "take_off", "aliases": ["departure", "airplane_departure"]}, # parallel to Places/41 "1f6ec": {"canonical_name": "landing", "aliases": ["arrival", "airplane_arrival"]}, "1f680": {"canonical_name": "rocket", "aliases": []}, "1f6f0": {"canonical_name": "satellite", "aliases": []}, "1f4ba": {"canonical_name": "seat", "aliases": []}, "1f6f6": {"canonical_name": "canoe", "aliases": []}, "26f5": {"canonical_name": "boat", "aliases": ["sailboat"]}, "1f6e5": {"canonical_name": "motor_boat", "aliases": []}, "1f6a4": {"canonical_name": "speedboat", "aliases": []}, # yacht and cruise seem like reasonable additions "1f6f3": {"canonical_name": "passenger_ship", "aliases": ["yacht", "cruise"]}, "26f4": {"canonical_name": "ferry", "aliases": []}, "1f6a2": {"canonical_name": "ship", "aliases": []}, "2693": {"canonical_name": "anchor", "aliases": []}, # there already is a construction in Places/82, and work_in_progress seems # like a useful thing to have. Construction_zone seems better than the # Unicode construction_sign, and is there partly so this autocompletes for # construction. "1f6a7": {"canonical_name": "work_in_progress", "aliases": ["construction_zone"]}, # alternates from https://emojipedia.org/fuel-pump/. Unicode is fuel_pump, # not fuelpump "26fd": {"canonical_name": "fuel_pump", "aliases": ["gas_pump", "petrol_pump"]}, # not sure why iamcal removed the space "1f68f": {"canonical_name": "bus_stop", "aliases": []}, # https://emojipedia.org/vertical-traffic-light/ thinks this is the more # common of the two traffic lights, so putting traffic_light on this one "1f6a6": {"canonical_name": "traffic_light", "aliases": ["vertical_traffic_light"]}, # see Places/57 "1f6a5": {"canonical_name": "horizontal_traffic_light", "aliases": []}, # road_trip from https://mashable.com/2015/10/23/ios-9-1-emoji-guide/ "1f5fa": {"canonical_name": "map", "aliases": ["world_map", "road_trip"]}, # rock_carving, statue, and tower seem more general and less culturally # specific, for Places/60, 61, and 63. "1f5ff": {"canonical_name": "rock_carving", "aliases": ["moyai"]}, # new_york from https://emojipedia.org/statue-of-liberty/. see Places/60 # for statue "1f5fd": {"canonical_name": "statue", "aliases": ["new_york", "statue_of_liberty"]}, "26f2": {"canonical_name": "fountain", "aliases": []}, # see Places/60 "1f5fc": {"canonical_name": "tower", "aliases": ["tokyo_tower"]}, # choosing this as the castle since castles are a way bigger thing in # europe than japan, and shiro is a pretty reasonable name for Places/65 "1f3f0": {"canonical_name": "castle", "aliases": []}, # see Places/64 "1f3ef": {"canonical_name": "shiro", "aliases": []}, "1f3df": {"canonical_name": "stadium", "aliases": []}, "1f3a1": {"canonical_name": "ferris_wheel", "aliases": []}, "1f3a2": {"canonical_name": "roller_coaster", "aliases": []}, # merry_go_round seems like a good addition "1f3a0": {"canonical_name": "carousel", "aliases": ["merry_go_round"]}, # beach_umbrella seems more useful "26f1": {"canonical_name": "beach_umbrella", "aliases": []}, "1f3d6": {"canonical_name": "beach", "aliases": []}, "1f3dd": {"canonical_name": "island", "aliases": []}, "26f0": {"canonical_name": "mountain", "aliases": []}, "1f3d4": {"canonical_name": "snowy_mountain", "aliases": []}, # already lots of other mountains, otherwise would rename this like # Places/60 "1f5fb": {"canonical_name": "mount_fuji", "aliases": []}, "1f30b": {"canonical_name": "volcano", "aliases": []}, "1f3dc": {"canonical_name": "desert", "aliases": []}, # campsite from https://emojipedia.org/camping/, I think Places/79 is a # better camping "1f3d5": {"canonical_name": "campsite", "aliases": []}, "26fa": {"canonical_name": "tent", "aliases": ["camping"]}, "1f6e4": {"canonical_name": "railway_track", "aliases": ["train_tracks"]}, # road is used much more frequently at # https://trends.google.com/trends/explore?q=road,motorway "1f6e3": {"canonical_name": "road", "aliases": ["motorway"]}, "1f3d7": {"canonical_name": "construction", "aliases": []}, "1f3ed": {"canonical_name": "factory", "aliases": []}, "1f3e0": {"canonical_name": "house", "aliases": []}, # suburb seems more useful "1f3e1": {"canonical_name": "suburb", "aliases": []}, "1f3d8": {"canonical_name": "houses", "aliases": []}, # condemned seemed like a good addition "1f3da": {"canonical_name": "derelict_house", "aliases": ["condemned"]}, "1f3e2": {"canonical_name": "office", "aliases": []}, "1f3ec": {"canonical_name": "department_store", "aliases": []}, "1f3e3": {"canonical_name": "japan_post", "aliases": []}, "1f3e4": {"canonical_name": "post_office", "aliases": []}, "1f3e5": {"canonical_name": "hospital", "aliases": []}, "1f3e6": {"canonical_name": "bank", "aliases": []}, "1f3e8": {"canonical_name": "hotel", "aliases": []}, "1f3ea": {"canonical_name": "convenience_store", "aliases": []}, "1f3eb": {"canonical_name": "school", "aliases": []}, "1f3e9": {"canonical_name": "love_hotel", "aliases": []}, "1f492": {"canonical_name": "wedding", "aliases": []}, "1f3db": {"canonical_name": "classical_building", "aliases": []}, "26ea": {"canonical_name": "church", "aliases": []}, "1f54c": {"canonical_name": "mosque", "aliases": []}, "1f54d": {"canonical_name": "synagogue", "aliases": []}, "1f54b": {"canonical_name": "kaaba", "aliases": []}, "26e9": {"canonical_name": "shinto_shrine", "aliases": []}, "1f5fe": {"canonical_name": "japan", "aliases": []}, # rice_scene seems like a strange name to have. gemoji alternate is # moon_ceremony "1f391": {"canonical_name": "moon_ceremony", "aliases": []}, "1f3de": {"canonical_name": "national_park", "aliases": []}, # ocean_sunrise to parallel Places/109 "1f305": {"canonical_name": "sunrise", "aliases": ["ocean_sunrise"]}, "1f304": {"canonical_name": "mountain_sunrise", "aliases": []}, # shooting_star and wish seem like way better descriptions. gemoji/Unicode # is shooting_star "1f320": {"canonical_name": "shooting_star", "aliases": ["wish"]}, "1f387": {"canonical_name": "sparkler", "aliases": []}, "1f386": {"canonical_name": "fireworks", "aliases": []}, "1f307": {"canonical_name": "city_sunrise", "aliases": []}, "1f306": {"canonical_name": "sunset", "aliases": []}, # city and skyline seem more useful than cityscape "1f3d9": {"canonical_name": "city", "aliases": ["skyline"]}, "1f303": {"canonical_name": "night", "aliases": []}, # night_sky seems like a good addition "1f30c": {"canonical_name": "milky_way", "aliases": ["night_sky"]}, "1f309": {"canonical_name": "bridge", "aliases": []}, "1f301": {"canonical_name": "foggy", "aliases": []}, "231a": {"canonical_name": "watch", "aliases": []}, # Unicode/gemoji is mobile_phone. The rest seem like good additions "1f4f1": {"canonical_name": "mobile_phone", "aliases": ["smartphone", "iphone", "android"]}, "1f4f2": {"canonical_name": "calling", "aliases": []}, # gemoji has laptop, even though the Google emoji for this does not look # like a laptop "1f4bb": {"canonical_name": "computer", "aliases": ["laptop"]}, "2328": {"canonical_name": "keyboard", "aliases": []}, "1f5a5": {"canonical_name": "desktop_computer", "aliases": []}, "1f5a8": {"canonical_name": "printer", "aliases": []}, # gemoji/Unicode is computer_mouse "1f5b1": {"canonical_name": "computer_mouse", "aliases": []}, "1f5b2": {"canonical_name": "trackball", "aliases": []}, # arcade seems like a reasonable addition "1f579": {"canonical_name": "joystick", "aliases": ["arcade"]}, # vise seems like a reasonable addition "1f5dc": {"canonical_name": "compression", "aliases": ["vise"]}, # gold record seems more useful, idea came from # https://11points.com/11-emoji-different-meanings-think/ "1f4bd": {"canonical_name": "gold_record", "aliases": ["minidisc"]}, "1f4be": {"canonical_name": "floppy_disk", "aliases": []}, "1f4bf": {"canonical_name": "cd", "aliases": []}, "1f4c0": {"canonical_name": "dvd", "aliases": []}, # videocassette from gemoji/Unicode "1f4fc": {"canonical_name": "vhs", "aliases": ["videocassette"]}, "1f4f7": {"canonical_name": "camera", "aliases": []}, # both of these seem more useful than camera_with_flash "1f4f8": {"canonical_name": "taking_a_picture", "aliases": ["say_cheese"]}, # video_recorder seems like a reasonable addition "1f4f9": {"canonical_name": "video_camera", "aliases": ["video_recorder"]}, "1f3a5": {"canonical_name": "movie_camera", "aliases": []}, # seems like the best emoji for movie "1f4fd": {"canonical_name": "projector", "aliases": ["movie"]}, "1f39e": {"canonical_name": "film", "aliases": []}, # both of these seem more useful than telephone_receiver "1f4de": {"canonical_name": "landline", "aliases": ["home_phone"]}, "260e": {"canonical_name": "phone", "aliases": ["telephone"]}, "1f4df": {"canonical_name": "pager", "aliases": []}, "1f4e0": {"canonical_name": "fax", "aliases": []}, "1f4fa": {"canonical_name": "tv", "aliases": ["television"]}, "1f4fb": {"canonical_name": "radio", "aliases": []}, "1f399": {"canonical_name": "studio_microphone", "aliases": []}, # volume seems more useful "1f39a": {"canonical_name": "volume", "aliases": ["level_slider"]}, "1f39b": {"canonical_name": "control_knobs", "aliases": []}, "23f1": {"canonical_name": "stopwatch", "aliases": []}, "23f2": {"canonical_name": "timer", "aliases": []}, "23f0": {"canonical_name": "alarm_clock", "aliases": []}, "1f570": {"canonical_name": "mantelpiece_clock", "aliases": []}, # times_up and time_ticking seem more useful than the hourglass names "231b": {"canonical_name": "times_up", "aliases": ["hourglass_done"]}, # seems like the better hourglass. Also see Objects/36 "23f3": {"canonical_name": "time_ticking", "aliases": ["hourglass"]}, "1f4e1": {"canonical_name": "satellite_antenna", "aliases": []}, # seems like a reasonable addition "1f50b": {"canonical_name": "battery", "aliases": ["full_battery"]}, "1f50c": {"canonical_name": "electric_plug", "aliases": []}, # light_bulb seems better and from Unicode/gemoji. idea seems like a good # addition "1f4a1": {"canonical_name": "light_bulb", "aliases": ["bulb", "idea"]}, "1f526": {"canonical_name": "flashlight", "aliases": []}, "1f56f": {"canonical_name": "candle", "aliases": []}, # seems like a reasonable addition "1f5d1": {"canonical_name": "wastebasket", "aliases": ["trash_can"]}, # https://www.iemoji.com/view/emoji/1173/objects/oil-drum "1f6e2": {"canonical_name": "oil_drum", "aliases": ["commodities"]}, # losing money from https://emojipedia.org/money-with-wings/, # easy_come_easy_go seems like a reasonable addition "1f4b8": { "canonical_name": "losing_money", "aliases": ["easy_come_easy_go", "money_with_wings"], }, # I think the _bills, _banknotes etc versions of these are arguably more # fun to use in chat, and certainly match the glyphs better "1f4b5": {"canonical_name": "dollar_bills", "aliases": []}, "1f4b4": {"canonical_name": "yen_banknotes", "aliases": []}, "1f4b6": {"canonical_name": "euro_banknotes", "aliases": []}, "1f4b7": {"canonical_name": "pound_notes", "aliases": []}, "1f4b0": {"canonical_name": "money", "aliases": []}, "1f4b3": {"canonical_name": "credit_card", "aliases": ["debit_card"]}, "1f48e": {"canonical_name": "gem", "aliases": ["crystal"]}, # justice seems more useful "2696": {"canonical_name": "justice", "aliases": ["scales", "balance"]}, # fixing, at_work, and working_on_it seem like useful concepts for # workplace chat "1f527": {"canonical_name": "fixing", "aliases": ["wrench"]}, "1f528": {"canonical_name": "hammer", "aliases": ["maintenance", "handyman", "handywoman"]}, "2692": {"canonical_name": "at_work", "aliases": ["hammer_and_pick"]}, # something that might be useful for chat.zulip.org, even "1f6e0": {"canonical_name": "working_on_it", "aliases": ["hammer_and_wrench", "tools"]}, "26cf": {"canonical_name": "mine", "aliases": ["pick"]}, # screw is somewhat inappropriate, but not openly so, so leaving it in "1f529": {"canonical_name": "nut_and_bolt", "aliases": ["screw"]}, "2699": {"canonical_name": "gear", "aliases": ["settings", "mechanical", "engineer"]}, "26d3": {"canonical_name": "chains", "aliases": []}, "1f52b": {"canonical_name": "gun", "aliases": []}, "1f4a3": {"canonical_name": "bomb", "aliases": []}, # betrayed from https://www.iemoji.com/view/emoji/786/objects/kitchen-knife "1f52a": {"canonical_name": "knife", "aliases": ["hocho", "betrayed"]}, # rated_for_violence from # https://www.iemoji.com/view/emoji/1085/objects/dagger. hate (also # suggested there) seems too strong, as does just "violence". "1f5e1": {"canonical_name": "dagger", "aliases": ["rated_for_violence"]}, "2694": {"canonical_name": "duel", "aliases": ["swords"]}, "1f6e1": {"canonical_name": "shield", "aliases": []}, "1f6ac": {"canonical_name": "smoking", "aliases": []}, "26b0": {"canonical_name": "coffin", "aliases": ["burial", "grave"]}, "26b1": {"canonical_name": "funeral_urn", "aliases": ["cremation"]}, # amphora is too obscure, I think "1f3fa": {"canonical_name": "vase", "aliases": ["amphora"]}, "1f52e": {"canonical_name": "crystal_ball", "aliases": ["oracle", "future", "fortune_telling"]}, "1f4ff": {"canonical_name": "prayer_beads", "aliases": []}, "1f488": {"canonical_name": "barber", "aliases": ["striped_pole"]}, # alchemy seems more useful and less obscure "2697": {"canonical_name": "alchemy", "aliases": ["alembic"]}, "1f52d": {"canonical_name": "telescope", "aliases": []}, # science seems useful to have. scientist inspired by # https://www.iemoji.com/view/emoji/787/objects/microscope "1f52c": {"canonical_name": "science", "aliases": ["microscope", "scientist"]}, "1f573": {"canonical_name": "hole", "aliases": []}, "1f48a": {"canonical_name": "medicine", "aliases": ["pill"]}, "1f489": {"canonical_name": "injection", "aliases": ["syringe"]}, "1f321": {"canonical_name": "temperature", "aliases": ["thermometer", "warm"]}, "1f6bd": {"canonical_name": "toilet", "aliases": []}, "1f6b0": {"canonical_name": "potable_water", "aliases": ["tap_water", "drinking_water"]}, "1f6bf": {"canonical_name": "shower", "aliases": []}, "1f6c1": {"canonical_name": "bathtub", "aliases": []}, "1f6c0": {"canonical_name": "bath", "aliases": []}, # reception and services from # https://www.iemoji.com/view/emoji/1169/objects/bellhop-bell "1f6ce": {"canonical_name": "bellhop_bell", "aliases": ["reception", "services", "ding"]}, "1f511": {"canonical_name": "key", "aliases": []}, # encrypted from https://www.iemoji.com/view/emoji/1081/objects/old-key, # secret from https://mashable.com/2015/10/23/ios-9-1-emoji-guide/ "1f5dd": { "canonical_name": "secret", "aliases": ["dungeon", "old_key", "encrypted", "clue", "hint"], }, "1f6aa": {"canonical_name": "door", "aliases": []}, "1f6cb": { "canonical_name": "living_room", "aliases": ["furniture", "couch_and_lamp", "lifestyles"], }, "1f6cf": {"canonical_name": "bed", "aliases": ["bedroom"]}, # guestrooms from iemoji, would add hotel but taken by Places/94 "1f6cc": {"canonical_name": "in_bed", "aliases": ["accommodations", "guestrooms"]}, "1f5bc": {"canonical_name": "picture", "aliases": ["framed_picture"]}, "1f6cd": {"canonical_name": "shopping_bags", "aliases": []}, # https://trends.google.com/trends/explore?q=shopping%20cart,shopping%20trolley "1f6d2": {"canonical_name": "shopping_cart", "aliases": ["shopping_trolley"]}, "1f381": {"canonical_name": "gift", "aliases": ["present"]}, # seemed like the best celebration "1f388": {"canonical_name": "balloon", "aliases": ["celebration"]}, # from gemoji/Unicode "1f38f": {"canonical_name": "carp_streamer", "aliases": ["flags"]}, "1f380": {"canonical_name": "ribbon", "aliases": ["decoration"]}, "1f38a": {"canonical_name": "confetti", "aliases": ["party_ball"]}, "1f389": {"canonical_name": "tada", "aliases": []}, "1f38e": {"canonical_name": "dolls", "aliases": []}, "1f3ee": {"canonical_name": "lantern", "aliases": ["izakaya_lantern"]}, "1f390": {"canonical_name": "wind_chime", "aliases": []}, "2709": {"canonical_name": "email", "aliases": ["envelope", "mail"]}, # seems useful for chat? "1f4e9": {"canonical_name": "mail_sent", "aliases": ["sealed"]}, "1f4e8": {"canonical_name": "mail_received", "aliases": []}, "1f4e7": {"canonical_name": "e-mail", "aliases": []}, "1f48c": {"canonical_name": "love_letter", "aliases": []}, "1f4e5": {"canonical_name": "inbox", "aliases": []}, "1f4e4": {"canonical_name": "outbox", "aliases": []}, "1f4e6": {"canonical_name": "package", "aliases": []}, # price_tag from iemoji "1f3f7": {"canonical_name": "label", "aliases": ["tag", "price_tag"]}, "1f4ea": {"canonical_name": "closed_mailbox", "aliases": []}, "1f4eb": {"canonical_name": "mailbox", "aliases": []}, "1f4ec": {"canonical_name": "unread_mail", "aliases": []}, "1f4ed": {"canonical_name": "inbox_zero", "aliases": ["empty_mailbox", "no_mail"]}, "1f4ee": {"canonical_name": "mail_dropoff", "aliases": []}, "1f4ef": {"canonical_name": "horn", "aliases": []}, "1f4dc": {"canonical_name": "scroll", "aliases": []}, # receipt seems more useful? "1f4c3": {"canonical_name": "receipt", "aliases": []}, "1f4c4": {"canonical_name": "document", "aliases": ["paper", "file", "page"]}, "1f4d1": {"canonical_name": "place_holder", "aliases": []}, "1f4ca": {"canonical_name": "bar_chart", "aliases": []}, # seems like the best chart "1f4c8": {"canonical_name": "chart", "aliases": ["upwards_trend", "growing", "increasing"]}, "1f4c9": {"canonical_name": "downwards_trend", "aliases": ["shrinking", "decreasing"]}, "1f5d2": {"canonical_name": "spiral_notepad", "aliases": []}, # '1f5d3': {'canonical_name': 'X', 'aliases': ['spiral_calendar_pad']}, # swapped the following two largely due to the emojione glyphs "1f4c6": {"canonical_name": "date", "aliases": []}, "1f4c5": {"canonical_name": "calendar", "aliases": []}, "1f4c7": {"canonical_name": "rolodex", "aliases": ["card_index"]}, "1f5c3": {"canonical_name": "archive", "aliases": []}, "1f5f3": {"canonical_name": "ballot_box", "aliases": []}, "1f5c4": {"canonical_name": "file_cabinet", "aliases": []}, "1f4cb": {"canonical_name": "clipboard", "aliases": []}, # don't need two file_folders, so made this organize "1f4c1": {"canonical_name": "organize", "aliases": ["file_folder"]}, "1f4c2": {"canonical_name": "folder", "aliases": []}, "1f5c2": {"canonical_name": "sort", "aliases": []}, "1f5de": {"canonical_name": "newspaper", "aliases": ["swat"]}, "1f4f0": {"canonical_name": "headlines", "aliases": []}, "1f4d3": {"canonical_name": "notebook", "aliases": ["composition_book"]}, "1f4d4": {"canonical_name": "decorative_notebook", "aliases": []}, "1f4d2": {"canonical_name": "ledger", "aliases": ["spiral_notebook"]}, # the glyphs here are the same as Objects/147-149 (with a different color), # for all but Google "1f4d5": {"canonical_name": "red_book", "aliases": ["closed_book"]}, "1f4d7": {"canonical_name": "green_book", "aliases": []}, "1f4d8": {"canonical_name": "blue_book", "aliases": []}, "1f4d9": {"canonical_name": "orange_book", "aliases": []}, "1f4da": {"canonical_name": "books", "aliases": []}, "1f4d6": {"canonical_name": "book", "aliases": ["open_book"]}, "1f516": {"canonical_name": "bookmark", "aliases": []}, "1f517": {"canonical_name": "link", "aliases": []}, "1f4ce": {"canonical_name": "paperclip", "aliases": ["attachment"]}, # office_supplies from https://mashable.com/2015/10/23/ios-9-1-emoji-guide/ "1f587": {"canonical_name": "office_supplies", "aliases": ["paperclip_chain", "linked"]}, "1f4d0": {"canonical_name": "carpenter_square", "aliases": ["triangular_ruler"]}, "1f4cf": {"canonical_name": "ruler", "aliases": ["straightedge"]}, "1f4cc": {"canonical_name": "push_pin", "aliases": ["thumb_tack"]}, "1f4cd": {"canonical_name": "pin", "aliases": ["sewing_pin"]}, "2702": {"canonical_name": "scissors", "aliases": []}, "1f58a": {"canonical_name": "pen", "aliases": ["ballpoint_pen"]}, "1f58b": {"canonical_name": "fountain_pen", "aliases": []}, # three of the four emoji sets just have a rightwards-facing objects/162 # '2712': {'canonical_name': 'X', 'aliases': ['black_nib']}, "1f58c": {"canonical_name": "paintbrush", "aliases": []}, "1f58d": {"canonical_name": "crayon", "aliases": []}, "1f4dd": {"canonical_name": "memo", "aliases": ["note"]}, "270f": {"canonical_name": "pencil", "aliases": []}, "1f50d": {"canonical_name": "search", "aliases": ["find", "magnifying_glass"]}, # '1f50e': {'canonical_name': 'X', 'aliases': ['mag_right']}, # https://emojipedia.org/lock-with-ink-pen/ "1f50f": { "canonical_name": "privacy", "aliases": ["key_signing", "digital_security", "protected"], }, "1f510": { "canonical_name": "secure", "aliases": ["lock_with_key", "safe", "commitment", "loyalty"], }, "1f512": {"canonical_name": "locked", "aliases": []}, "1f513": {"canonical_name": "unlocked", "aliases": []}, # seems the best glyph for love and love_you "2764": {"canonical_name": "heart", "aliases": ["love", "love_you"]}, "1f49b": {"canonical_name": "yellow_heart", "aliases": ["heart_of_gold"]}, "1f49a": {"canonical_name": "green_heart", "aliases": ["envy"]}, "1f499": {"canonical_name": "blue_heart", "aliases": []}, "1f49c": {"canonical_name": "purple_heart", "aliases": ["bravery"]}, "1f5a4": {"canonical_name": "black_heart", "aliases": []}, "1f494": {"canonical_name": "broken_heart", "aliases": ["heartache"]}, "2763": {"canonical_name": "heart_exclamation", "aliases": []}, "1f495": {"canonical_name": "two_hearts", "aliases": []}, "1f49e": {"canonical_name": "revolving_hearts", "aliases": []}, "1f493": {"canonical_name": "heartbeat", "aliases": []}, "1f497": {"canonical_name": "heart_pulse", "aliases": ["growing_heart"]}, "1f496": {"canonical_name": "sparkling_heart", "aliases": []}, "1f498": {"canonical_name": "cupid", "aliases": ["smitten", "heart_arrow"]}, "1f49d": {"canonical_name": "gift_heart", "aliases": []}, "1f49f": {"canonical_name": "heart_box", "aliases": []}, "262e": {"canonical_name": "peace", "aliases": []}, "271d": {"canonical_name": "cross", "aliases": ["christianity"]}, "262a": {"canonical_name": "star_and_crescent", "aliases": ["islam"]}, "1f549": {"canonical_name": "om", "aliases": ["hinduism"]}, "2638": {"canonical_name": "wheel_of_dharma", "aliases": ["buddhism"]}, "2721": {"canonical_name": "star_of_david", "aliases": ["judaism"]}, # can't find any explanation of this at all. Is an alternate star of david? # '1f52f': {'canonical_name': 'X', 'aliases': ['six_pointed_star']}, "1f54e": {"canonical_name": "menorah", "aliases": []}, "262f": {"canonical_name": "yin_yang", "aliases": []}, "2626": {"canonical_name": "orthodox_cross", "aliases": []}, "1f6d0": {"canonical_name": "place_of_worship", "aliases": []}, "26ce": {"canonical_name": "ophiuchus", "aliases": []}, "2648": {"canonical_name": "aries", "aliases": []}, "2649": {"canonical_name": "taurus", "aliases": []}, "264a": {"canonical_name": "gemini", "aliases": []}, "264b": {"canonical_name": "cancer", "aliases": []}, "264c": {"canonical_name": "leo", "aliases": []}, "264d": {"canonical_name": "virgo", "aliases": []}, "264e": {"canonical_name": "libra", "aliases": []}, "264f": {"canonical_name": "scorpius", "aliases": []}, "2650": {"canonical_name": "sagittarius", "aliases": []}, "2651": {"canonical_name": "capricorn", "aliases": []}, "2652": {"canonical_name": "aquarius", "aliases": []}, "2653": {"canonical_name": "pisces", "aliases": []}, "1f194": {"canonical_name": "id", "aliases": []}, "269b": {"canonical_name": "atom", "aliases": ["physics"]}, "2622": {"canonical_name": "radioactive", "aliases": ["nuclear"]}, "2623": {"canonical_name": "biohazard", "aliases": []}, "1f4f4": {"canonical_name": "phone_off", "aliases": []}, "1f4f3": {"canonical_name": "vibration_mode", "aliases": []}, # Japanese symbol. `canonical_name` taken from emojipedia.org. "1f236": {"canonical_name": "japanese_not_free_of_charge_button", "aliases": ["u6709"]}, "1f250": {"canonical_name": "japanese_bargain_button", "aliases": ["ideograph_advantage"]}, "1f251": {"canonical_name": "japanese_acceptable_button", "aliases": ["accept"]}, "1f21a": {"canonical_name": "japanese_free_of_charge_button", "aliases": ["u7121"]}, "1f238": {"canonical_name": "japanese_application_button", "aliases": ["u7533"]}, "1f23a": {"canonical_name": "japanese_open_for_business_button", "aliases": ["u55b6"]}, "1f237": {"canonical_name": "japanese_monthly_amount_button", "aliases": ["u6708"]}, "3299": {"canonical_name": "japanese_secret_button", "aliases": ["secret"]}, "3297": {"canonical_name": "japanese_congratulations_button", "aliases": ["congratulations"]}, "1f234": {"canonical_name": "japanese_passing_grade_button", "aliases": ["u5408"]}, "1f235": {"canonical_name": "japanese_no_vacancy_button", "aliases": ["u6e80"]}, "1f239": {"canonical_name": "japanese_discount_button", "aliases": ["u5272"]}, "1f232": {"canonical_name": "japanese_prohibited_button", "aliases": ["u7981"]}, # End of Japanese symbol. "2734": {"canonical_name": "eight_pointed_star", "aliases": []}, "1f19a": {"canonical_name": "vs", "aliases": []}, "1f4ae": {"canonical_name": "white_flower", "aliases": []}, "1f170": {"canonical_name": "a", "aliases": []}, "1f171": {"canonical_name": "b", "aliases": []}, "1f18e": {"canonical_name": "ab", "aliases": []}, "1f191": {"canonical_name": "cl", "aliases": []}, "1f17e": {"canonical_name": "o", "aliases": []}, "1f198": {"canonical_name": "sos", "aliases": []}, # Symbols/105 seems like a better x, and looks more like the other letters "274c": {"canonical_name": "cross_mark", "aliases": ["incorrect", "wrong"]}, "2b55": {"canonical_name": "circle", "aliases": []}, "1f6d1": {"canonical_name": "stop_sign", "aliases": ["octagonal_sign"]}, "26d4": {"canonical_name": "no_entry", "aliases": ["wrong_way"]}, "1f4db": {"canonical_name": "name_badge", "aliases": []}, "1f6ab": {"canonical_name": "prohibited", "aliases": ["not_allowed"]}, "1f4af": {"canonical_name": "100", "aliases": ["hundred"]}, "1f4a2": {"canonical_name": "anger", "aliases": ["bam", "pow"]}, "2668": {"canonical_name": "hot_springs", "aliases": []}, "1f6b7": {"canonical_name": "no_pedestrians", "aliases": []}, "1f6af": {"canonical_name": "do_not_litter", "aliases": []}, "1f6b3": {"canonical_name": "no_bicycles", "aliases": []}, "1f6b1": {"canonical_name": "non-potable_water", "aliases": []}, "1f51e": {"canonical_name": "underage", "aliases": ["nc17"]}, "1f4f5": {"canonical_name": "no_phones", "aliases": []}, "1f6ad": {"canonical_name": "no_smoking", "aliases": []}, "2757": {"canonical_name": "exclamation", "aliases": []}, "2755": {"canonical_name": "grey_exclamation", "aliases": []}, "2753": {"canonical_name": "question", "aliases": []}, "2754": {"canonical_name": "grey_question", "aliases": []}, "203c": {"canonical_name": "bangbang", "aliases": ["double_exclamation"]}, "2049": {"canonical_name": "interrobang", "aliases": []}, "1f505": {"canonical_name": "low_brightness", "aliases": ["dim"]}, "1f506": {"canonical_name": "brightness", "aliases": ["high_brightness"]}, "303d": {"canonical_name": "part_alternation", "aliases": []}, "26a0": {"canonical_name": "warning", "aliases": ["caution", "danger"]}, "1f6b8": { "canonical_name": "children_crossing", "aliases": ["school_crossing", "drive_with_care"], }, "1f531": {"canonical_name": "trident", "aliases": []}, "269c": {"canonical_name": "fleur_de_lis", "aliases": []}, "1f530": {"canonical_name": "beginner", "aliases": []}, "267b": {"canonical_name": "recycle", "aliases": []}, # seems like the best check "2705": {"canonical_name": "check", "aliases": ["all_good", "approved"]}, # '1f22f': {'canonical_name': 'X', 'aliases': ['u6307']}, # stock_market seemed more useful "1f4b9": {"canonical_name": "stock_market", "aliases": []}, "2747": {"canonical_name": "sparkle", "aliases": []}, "2733": {"canonical_name": "eight_spoked_asterisk", "aliases": []}, "274e": {"canonical_name": "x", "aliases": []}, "1f310": {"canonical_name": "www", "aliases": ["globe"]}, "1f4a0": {"canonical_name": "cute", "aliases": ["kawaii", "diamond_with_a_dot"]}, "24c2": {"canonical_name": "metro", "aliases": ["m"]}, "1f300": {"canonical_name": "cyclone", "aliases": ["hurricane", "typhoon"]}, "1f4a4": {"canonical_name": "zzz", "aliases": []}, "1f3e7": {"canonical_name": "atm", "aliases": []}, "1f6be": {"canonical_name": "wc", "aliases": ["water_closet"]}, "267f": {"canonical_name": "accessible", "aliases": ["wheelchair", "disabled"]}, "1f17f": {"canonical_name": "parking", "aliases": ["p"]}, # '1f233': {'canonical_name': 'X', 'aliases': ['u7a7a']}, # '1f202': {'canonical_name': 'X', 'aliases': ['sa']}, "1f6c2": {"canonical_name": "passport_control", "aliases": ["immigration"]}, "1f6c3": {"canonical_name": "customs", "aliases": []}, "1f6c4": {"canonical_name": "baggage_claim", "aliases": []}, "1f6c5": {"canonical_name": "locker", "aliases": ["locked_bag"]}, "1f6b9": {"canonical_name": "mens", "aliases": []}, "1f6ba": {"canonical_name": "womens", "aliases": []}, # seems more in line with the surrounding bathroom symbols "1f6bc": {"canonical_name": "baby_change_station", "aliases": ["nursery"]}, "1f6bb": {"canonical_name": "restroom", "aliases": []}, "1f6ae": {"canonical_name": "put_litter_in_its_place", "aliases": []}, "1f3a6": {"canonical_name": "cinema", "aliases": ["movie_theater"]}, "1f4f6": {"canonical_name": "cell_reception", "aliases": ["signal_strength", "signal_bars"]}, # '1f201': {'canonical_name': 'X', 'aliases': ['koko']}, "1f523": {"canonical_name": "symbols", "aliases": []}, "2139": {"canonical_name": "info", "aliases": []}, "1f524": {"canonical_name": "abc", "aliases": []}, "1f521": {"canonical_name": "abcd", "aliases": ["alphabet"]}, "1f520": {"canonical_name": "capital_abcd", "aliases": ["capital_letters"]}, "1f196": {"canonical_name": "ng", "aliases": []}, # from Unicode/gemoji. Saving ok for People/111 "1f197": {"canonical_name": "squared_ok", "aliases": []}, # from Unicode, and to parallel Symbols/135. Saving up for Symbols/171 "1f199": {"canonical_name": "squared_up", "aliases": []}, "1f192": {"canonical_name": "cool", "aliases": []}, "1f195": {"canonical_name": "new", "aliases": []}, "1f193": {"canonical_name": "free", "aliases": []}, "0030-20e3": {"canonical_name": "zero", "aliases": []}, "0031-20e3": {"canonical_name": "one", "aliases": []}, "0032-20e3": {"canonical_name": "two", "aliases": []}, "0033-20e3": {"canonical_name": "three", "aliases": []}, "0034-20e3": {"canonical_name": "four", "aliases": []}, "0035-20e3": {"canonical_name": "five", "aliases": []}, "0036-20e3": {"canonical_name": "six", "aliases": []}, "0037-20e3": {"canonical_name": "seven", "aliases": []}, "0038-20e3": {"canonical_name": "eight", "aliases": []}, "0039-20e3": {"canonical_name": "nine", "aliases": []}, "1f51f": {"canonical_name": "ten", "aliases": []}, "1f522": {"canonical_name": "1234", "aliases": ["numbers"]}, "0023-20e3": {"canonical_name": "hash", "aliases": []}, "002a-20e3": {"canonical_name": "asterisk", "aliases": []}, "25b6": {"canonical_name": "play", "aliases": []}, "23f8": {"canonical_name": "pause", "aliases": []}, "23ef": {"canonical_name": "play_pause", "aliases": []}, # stop taken by People/118 "23f9": {"canonical_name": "stop_button", "aliases": []}, "23fa": {"canonical_name": "record", "aliases": []}, "23ed": {"canonical_name": "next_track", "aliases": ["skip_forward"]}, "23ee": {"canonical_name": "previous_track", "aliases": ["skip_back"]}, "23e9": {"canonical_name": "fast_forward", "aliases": []}, "23ea": {"canonical_name": "rewind", "aliases": ["fast_reverse"]}, "23eb": {"canonical_name": "double_up", "aliases": ["fast_up"]}, "23ec": {"canonical_name": "double_down", "aliases": ["fast_down"]}, "25c0": {"canonical_name": "play_reverse", "aliases": []}, "1f53c": {"canonical_name": "upvote", "aliases": ["up_button", "increase"]}, "1f53d": {"canonical_name": "downvote", "aliases": ["down_button", "decrease"]}, "27a1": {"canonical_name": "right", "aliases": ["east"]}, "2b05": {"canonical_name": "left", "aliases": ["west"]}, "2b06": {"canonical_name": "up", "aliases": ["north"]}, "2b07": {"canonical_name": "down", "aliases": ["south"]}, "2197": {"canonical_name": "upper_right", "aliases": ["north_east"]}, "2198": {"canonical_name": "lower_right", "aliases": ["south_east"]}, "2199": {"canonical_name": "lower_left", "aliases": ["south_west"]}, "2196": {"canonical_name": "upper_left", "aliases": ["north_west"]}, "2195": {"canonical_name": "up_down", "aliases": []}, "2194": {"canonical_name": "left_right", "aliases": ["swap"]}, "21aa": {"canonical_name": "forward", "aliases": ["right_hook"]}, "21a9": {"canonical_name": "reply", "aliases": ["left_hook"]}, "2934": {"canonical_name": "heading_up", "aliases": []}, "2935": {"canonical_name": "heading_down", "aliases": []}, "1f500": {"canonical_name": "shuffle", "aliases": []}, "1f501": {"canonical_name": "repeat", "aliases": []}, "1f502": {"canonical_name": "repeat_one", "aliases": []}, "1f504": {"canonical_name": "counterclockwise", "aliases": ["return"]}, "1f503": {"canonical_name": "clockwise", "aliases": []}, "1f3b5": {"canonical_name": "music", "aliases": []}, "1f3b6": {"canonical_name": "musical_notes", "aliases": []}, "2795": {"canonical_name": "plus", "aliases": ["add"]}, "2796": {"canonical_name": "minus", "aliases": ["subtract"]}, "2797": {"canonical_name": "division", "aliases": ["divide"]}, "2716": {"canonical_name": "multiplication", "aliases": ["multiply"]}, "1f4b2": {"canonical_name": "dollars", "aliases": []}, # There is no other exchange, so might as well generalize this "1f4b1": {"canonical_name": "exchange", "aliases": []}, "2122": {"canonical_name": "tm", "aliases": ["trademark"]}, "3030": {"canonical_name": "wavy_dash", "aliases": []}, "27b0": {"canonical_name": "loop", "aliases": []}, # https://emojipedia.org/double-curly-loop/ "27bf": {"canonical_name": "double_loop", "aliases": ["voicemail"]}, "1f51a": {"canonical_name": "end", "aliases": []}, "1f519": {"canonical_name": "back", "aliases": []}, "1f51b": {"canonical_name": "on", "aliases": []}, "1f51d": {"canonical_name": "top", "aliases": []}, "1f51c": {"canonical_name": "soon", "aliases": []}, "2714": {"canonical_name": "check_mark", "aliases": []}, "2611": {"canonical_name": "checkbox", "aliases": []}, "1f518": {"canonical_name": "radio_button", "aliases": []}, "26aa": {"canonical_name": "white_circle", "aliases": []}, "26ab": {"canonical_name": "black_circle", "aliases": []}, "1f534": {"canonical_name": "red_circle", "aliases": []}, "1f535": {"canonical_name": "blue_circle", "aliases": []}, "1f53a": {"canonical_name": "red_triangle_up", "aliases": []}, "1f53b": {"canonical_name": "red_triangle_down", "aliases": []}, "1f538": {"canonical_name": "small_orange_diamond", "aliases": []}, "1f539": {"canonical_name": "small_blue_diamond", "aliases": []}, "1f536": {"canonical_name": "large_orange_diamond", "aliases": []}, "1f537": {"canonical_name": "large_blue_diamond", "aliases": []}, "1f533": {"canonical_name": "black_and_white_square", "aliases": []}, "1f532": {"canonical_name": "white_and_black_square", "aliases": []}, "25aa": {"canonical_name": "black_small_square", "aliases": []}, "25ab": {"canonical_name": "white_small_square", "aliases": []}, "25fe": {"canonical_name": "black_medium_small_square", "aliases": []}, "25fd": {"canonical_name": "white_medium_small_square", "aliases": []}, "25fc": {"canonical_name": "black_medium_square", "aliases": []}, "25fb": {"canonical_name": "white_medium_square", "aliases": []}, "2b1b": {"canonical_name": "black_large_square", "aliases": []}, "2b1c": {"canonical_name": "white_large_square", "aliases": []}, "1f508": {"canonical_name": "speaker", "aliases": []}, "1f507": {"canonical_name": "mute", "aliases": ["no_sound"]}, "1f509": {"canonical_name": "softer", "aliases": []}, "1f50a": {"canonical_name": "louder", "aliases": ["sound"]}, "1f514": {"canonical_name": "notifications", "aliases": ["bell"]}, "1f515": {"canonical_name": "mute_notifications", "aliases": []}, "1f4e3": {"canonical_name": "megaphone", "aliases": ["shout"]}, "1f4e2": {"canonical_name": "loudspeaker", "aliases": ["bullhorn"]}, "1f4ac": {"canonical_name": "umm", "aliases": ["speech_balloon"]}, "1f5e8": {"canonical_name": "speech_bubble", "aliases": []}, "1f4ad": {"canonical_name": "thought", "aliases": ["dream"]}, "1f5ef": {"canonical_name": "anger_bubble", "aliases": []}, "2660": {"canonical_name": "spades", "aliases": []}, "2663": {"canonical_name": "clubs", "aliases": []}, "2665": {"canonical_name": "hearts", "aliases": []}, "2666": {"canonical_name": "diamonds", "aliases": []}, "1f0cf": {"canonical_name": "joker", "aliases": []}, "1f3b4": {"canonical_name": "playing_cards", "aliases": []}, "1f004": {"canonical_name": "mahjong", "aliases": []}, # The only use I can think of for so many clocks is to be able to use them # to vote on times and such in emoji reactions. But a) the experience is # not that great (the images are too small), b) there are issues with # 24-hour time (used in many countries), like what is 00:30 or 01:00 # called, c) it's hard to make the compose typeahead experience great, and # d) we should have a dedicated time voting widget that takes care of # timezone and locale issues, and uses a digital representation. # '1f550': {'canonical_name': 'X', 'aliases': ['clock1']}, # '1f551': {'canonical_name': 'X', 'aliases': ['clock2']}, # '1f552': {'canonical_name': 'X', 'aliases': ['clock3']}, # '1f553': {'canonical_name': 'X', 'aliases': ['clock4']}, # '1f554': {'canonical_name': 'X', 'aliases': ['clock5']}, # '1f555': {'canonical_name': 'X', 'aliases': ['clock6']}, # '1f556': {'canonical_name': 'X', 'aliases': ['clock7']}, # seems like the best choice for time "1f557": {"canonical_name": "time", "aliases": ["clock"]}, # '1f558': {'canonical_name': 'X', 'aliases': ['clock9']}, # '1f559': {'canonical_name': 'X', 'aliases': ['clock10']}, # '1f55a': {'canonical_name': 'X', 'aliases': ['clock11']}, # '1f55b': {'canonical_name': 'X', 'aliases': ['clock12']}, # '1f55c': {'canonical_name': 'X', 'aliases': ['clock130']}, # '1f55d': {'canonical_name': 'X', 'aliases': ['clock230']}, # '1f55e': {'canonical_name': 'X', 'aliases': ['clock330']}, # '1f55f': {'canonical_name': 'X', 'aliases': ['clock430']}, # '1f560': {'canonical_name': 'X', 'aliases': ['clock530']}, # '1f561': {'canonical_name': 'X', 'aliases': ['clock630']}, # '1f562': {'canonical_name': 'X', 'aliases': ['clock730']}, # '1f563': {'canonical_name': 'X', 'aliases': ['clock830']}, # '1f564': {'canonical_name': 'X', 'aliases': ['clock930']}, # '1f565': {'canonical_name': 'X', 'aliases': ['clock1030']}, # '1f566': {'canonical_name': 'X', 'aliases': ['clock1130']}, # '1f567': {'canonical_name': 'X', 'aliases': ['clock1230']}, "1f3f3": {"canonical_name": "white_flag", "aliases": ["surrender"]}, "1f3f4": {"canonical_name": "black_flag", "aliases": []}, "1f3c1": {"canonical_name": "checkered_flag", "aliases": ["race", "go", "start"]}, "1f6a9": {"canonical_name": "triangular_flag", "aliases": []}, # solidarity from iemoji "1f38c": {"canonical_name": "crossed_flags", "aliases": ["solidarity"]}, }
eeshangarg/zulip
tools/setup/emoji/emoji_names.py
Python
apache-2.0
95,930
[ "CRYSTAL", "Octopus" ]
cfb6554224f432a6f44864d83ab326f000a9ca7f7e3c32abd455ca7359f27f6f
# # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import bigdl.orca.automl.hp as hp AUTO_MODEL_SUPPORT_LIST = ["lstm", "tcn", "seq2seq"] AUTO_MODEL_DEFAULT_SEARCH_SPACE = { "lstm": {"minimal": {"hidden_dim": hp.grid_search([16, 32]), "layer_num": hp.randint(1, 2), "lr": hp.loguniform(0.001, 0.005), "dropout": hp.uniform(0.1, 0.2)}, "normal": {"hidden_dim": hp.grid_search([16, 32, 64]), "layer_num": hp.grid_search([1, 2]), "lr": hp.loguniform(0.0005, 0.01), "dropout": hp.uniform(0, 0.2)}, "large": {"hidden_dim": hp.grid_search([16, 32, 64, 128]), "layer_num": hp.grid_search([1, 2, 3, 4]), "lr": hp.loguniform(0.0005, 0.01), "dropout": hp.uniform(0, 0.3)}}, "tcn": {"minimal": {"hidden_units": hp.grid_search([16, 32]), "levels": hp.randint(4, 6), "kernel_size": 3, "lr": hp.loguniform(0.001, 0.005), "dropout": hp.uniform(0.1, 0.2)}, "normal": {"hidden_units": hp.grid_search([16, 32, 48]), "levels": hp.grid_search([6, 8]), "kernel_size": hp.grid_search([3, 5]), "lr": hp.loguniform(0.001, 0.01), "dropout": hp.uniform(0, 0.2)}, "large": {"hidden_units": hp.grid_search([16, 32, 48, 64]), "levels": hp.grid_search([4, 5, 6, 7, 8]), "kernel_size": hp.grid_search([3, 5, 7]), "lr": hp.loguniform(0.0005, 0.015), "dropout": hp.uniform(0, 0.25)}}, "seq2seq": {"minimal": {"lr": hp.loguniform(0.001, 0.005), "lstm_hidden_dim": hp.grid_search([16, 32]), "lstm_layer_num": hp.randint(1, 2), "dropout": hp.uniform(0, 0.3), "teacher_forcing": False}, "normal": {"lr": hp.loguniform(0.001, 0.005), "lstm_hidden_dim": hp.grid_search([16, 32, 64]), "lstm_layer_num": hp.grid_search([1, 2]), "dropout": hp.uniform(0, 0.3), "teacher_forcing": hp.grid_search([True, False])}, "large": {"lr": hp.loguniform(0.0005, 0.005), "lstm_hidden_dim": hp.grid_search([16, 32, 64, 128]), "lstm_layer_num": hp.grid_search([1, 2, 4]), "dropout": hp.uniform(0, 0.3), "teacher_forcing": hp.grid_search([True, False])}} } class AutoModelFactory: @staticmethod def create_auto_model(name, search_space): name = name.lower() if name == "lstm": from .auto_lstm import AutoLSTM revised_search_space = search_space.copy() assert revised_search_space["future_seq_len"] == 1, \ "future_seq_len should be set to 1 if you choose lstm model." del revised_search_space["future_seq_len"] # future_seq_len should always be 1 return AutoLSTM(**revised_search_space) if name == "tcn": from .auto_tcn import AutoTCN return AutoTCN(**search_space) if name == "seq2seq": from .auto_seq2seq import AutoSeq2Seq return AutoSeq2Seq(**search_space) return NotImplementedError(f"{AUTO_MODEL_SUPPORT_LIST} are supported for auto model,\ but get {name}.") @staticmethod def get_default_search_space(model, computing_resource="normal"): ''' This function should be called internally to get a default search_space experimentally. :param model: model name, only tcn, lstm and seq2seq are supported :param mode: one of "minimal", "normal", "large" ''' model = model.lower() if model in AUTO_MODEL_SUPPORT_LIST: return AUTO_MODEL_DEFAULT_SEARCH_SPACE[model][computing_resource] return NotImplementedError(f"{AUTO_MODEL_SUPPORT_LIST} are supported for auto model,\ but get {model}.")
intel-analytics/BigDL
python/chronos/src/bigdl/chronos/autots/model/__init__.py
Python
apache-2.0
4,916
[ "ORCA" ]
2c7b7ef22dff89165707fd1ae93ba053ab200848a728ae7896f4b9f68d5b49d7
#!/usr/bin/env python # ---------------------------------------- # scikit-ribo # ---------------------------------------- # pre-processing module # ---------------------------------------- # author: Han Fang # contact: hanfang.cshl@gmail.com # website: hanfang.github.io # date: 3/28/2017 # ---------------------------------------- from __future__ import print_function, division import os import sys import argparse import pybedtools as pbt import pysam import pandas as pd import numpy as np import csv import errno from datetime import datetime import scikit_ribo from gtf_preprocess import GtfPreProcess from process_rnafold import ProcessRnafold from merge_df import MergeDF def log_status(gtf_fn, ref_fn, prefix, rnafold_fn, tpm_fn, out_dir): """ Logging the status :param gtf_fn: str, gtf file :param ref_fn: str, ref fasta file :param prefix: str, prefix :param rnafold_fn: str, rnafold file path :param tpm_fn: str, tpm file path :param out_dir: str, output directory :return: None """ # create output folder cmd = 'mkdir -p ' + out_dir os.system(cmd) print("[status]\tStarted the pre-processing module", file=sys.stderr) print("[status]\tImport the gtf file: " + gtf_fn, file=sys.stderr) print("[status]\tImport the ref genome fasta file: " + ref_fn, file=sys.stderr) print("[status]\tImport RNAfold file: " + rnafold_fn, file=sys.stderr) print("[status]\tImport TPM file of RNAseq sample: " + tpm_fn, file=sys.stderr) print("[setting]\tPrefix to use: " + prefix, file=sys.stderr) print("[setting]\tOutput path: " + out_dir, file=sys.stderr) sys.stderr.flush() def module_gtf(gtf_fn, ref_fn, prefix, out_dir): """ Module for processing gtf and ref :param gtf_fn: str :param ref_fn: str :param prefix: str :param out_dir: str :return: None """ worker = GtfPreProcess(gtf_fn, ref_fn, prefix, out_dir) print("[execute]\tLoading the the gtf file in to sql db", file=sys.stderr) worker.convertGtf() print("[execute]\tCalculating the length of each chromosome", file=sys.stderr) worker.getChrLen() print("[execute]\tExtracting the start codons' positions from the gtf db", file=sys.stderr) worker.getStartCodon() print("[execute]\tExtracting the sequences for each gene", file=sys.stderr) worker.getSeq() print("[execute]\tBuilding the index for each position at the codon level", file=sys.stderr) worker.getCodons() worker.getNts() print("[execute]\tCreating the codon table for the coding region", file=sys.stderr) worker.createCodonTable() print("[status]\tGtf processing module finished", file=sys.stderr) sys.stderr.flush() def module_merge(prefix, tpm_fn, rnafold_fn, out_dir): """ merge data :param prefix: prefix for the files :param tpm_fn: tmp file name :param rnafold_fn: rnafold file path :param out_dir: output directory :return: """ bed = out_dir + "/" + prefix + ".codons.bed" # execute dat = MergeDF(bed, rnafold_fn, tpm_fn, out_dir) print("[execute]\tTransforming the dataframe of RNA secondary structure pairing probabilities", file=sys.stderr) dat.transformPairProb() print("[execute]\tLoading tpm", file=sys.stderr) dat.loadTpm() print("[execute]\tMerging all the df together", file=sys.stderr) dat.mergeDf() sys.stderr.flush() def scikit_ribo_build(gtf_fn, ref_fn, prefix, rnafold_fn, tpm_fn, out): """ :param gtf_fn: :param ref_fn: :param prefix: :param rnafold_fn: :param tpm_fn: :param out: :return: None """ log_status(gtf_fn, ref_fn, prefix, rnafold_fn, tpm_fn, out) module_gtf(gtf_fn, ref_fn, prefix, out) module_merge(prefix, tpm_fn, rnafold_fn, out) print("[status]\tPre-processing module finished", file=sys.stderr) sys.stderr.flush() # ---------------------------------------- # parse input arguments # ---------------------------------------- if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-g", help="Gtf file, required") parser.add_argument("-f", help="Fasta file, required") parser.add_argument("-p", help="Prefix to use, required") parser.add_argument("-r", help="Path to the Rnafold file, required") parser.add_argument("-t", help="TPM of RNAseq sample, required") parser.add_argument("-o", help="Output path of the built indexes, required") # check if there is any argument if len(sys.argv[1:]) == 0: parser.print_help() parser.exit() if len(sys.argv) <= 1: parser.print_usage() sys.exit(1) else: args = parser.parse_args() # process the file if the input files exist if args.g != None and args.f != None and args.p != None and args.r != None and args.t != None and args.o != None: sys.stderr.write("[status]\tReading the input file: " + args.g + "\n") gtf = args.g fasta = args.f pre = args.p rnafold = args.r tpm = args.t output = args.o scikit_ribo_build(gtf, fasta, pre, rnafold, tpm, output) else: print("[error]\tmissing argument", file=sys.stderr) parser.print_usage()
hanfang/scikit-ribo
scikit_ribo/scikit-ribo-build.py
Python
gpl-2.0
5,250
[ "pysam" ]
3a4251db7257aa8b90fe2134343a776cbaed6d540f02a866daa4747f5d2e228b
######################################################################## # $HeadURL$ # File : InputDataByProtocol.py # Author : Stuart Paterson ######################################################################## """ The Input Data By Protocol module wraps around the Replica Management components to provide access to datasets by available site protocols as defined in the CS for the VO. """ __RCSID__ = "$Id$" from DIRAC.Core.DISET.RPCClient import RPCClient from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC import S_OK, S_ERROR, gLogger COMPONENT_NAME = 'InputDataByProtocol' class InputDataByProtocol( object ): ############################################################################# def __init__( self, argumentsDict ): """ Standard constructor """ self.name = COMPONENT_NAME self.log = gLogger.getSubLogger( self.name ) self.inputData = argumentsDict['InputData'] self.configuration = argumentsDict['Configuration'] self.fileCatalogResult = argumentsDict['FileCatalog'] self.jobID = None # This is because replicas contain SEs and metadata keys! # FIXME: the structure of the dictionary must be fixed to avoid this mess self.metaKeys = set( ['ChecksumType', 'Checksum', 'NumberOfLinks', 'Mode', 'GUID', 'Status', 'ModificationDate', 'CreationDate', 'Size', 'Owner', 'OwnerGroup', 'GID', 'UID', 'FileID'] ) ############################################################################# def execute( self, dataToResolve = None ): """This method is called to obtain the TURLs for all requested input data firstly by available site protocols and redundantly via TURL construction. If TURLs are missing these are conveyed in the result to """ # Define local configuration options present at every site localSEList = self.configuration['LocalSEList'] self.jobID = self.configuration.get( 'JobID' ) allReplicas = self.configuration.get( 'AllReplicas', False ) if allReplicas: self.log.info( 'All replicas will be used in the resolution' ) if dataToResolve: self.log.verbose( 'Data to resolve passed directly to InputDataByProtocol module' ) self.inputData = dataToResolve # e.g. list supplied by another module self.inputData = [x.replace( 'LFN:', '' ) for x in self.inputData] self.log.verbose( 'InputData requirement to be resolved by protocol is:\n%s' % '\n'.join( self.inputData ) ) # First make a check in case replicas have been removed or are not accessible # from the local site (remove these from consideration for local protocols) replicas = self.fileCatalogResult['Value']['Successful'] self.log.debug( 'File Catalogue result is:\n%s' % str( replicas ) ) # First get the preferred replica: requestedProtocol = self.configuration.get( 'Protocol', '' ) result = self.__resolveReplicas( localSEList, replicas, requestedProtocol = requestedProtocol ) if not result['OK']: return result success = result['Value']['Successful'] if not allReplicas: bestReplica = {} for lfn in success: bestReplica[lfn] = success[lfn][0] return S_OK( {'Successful': bestReplica, 'Failed':result['Value']['Failed']} ) # If all replicas are requested, get results for other SEs seList = set() localSESet = set( localSEList ) for lfn in replicas.keys(): extraSEs = set( replicas[lfn] ) - localSESet # If any extra SE, add it to the set, othewise don't consider that file if extraSEs: seList.update( extraSEs ) else: replicas.pop( lfn ) seList -= self.metaKeys if seList: requestedProtocol = self.configuration.get( 'RemoteProtocol', '' ) result = self.__resolveReplicas( seList, replicas, ignoreTape = True, requestedProtocol = requestedProtocol ) if not result['OK']: return result for lfn in result['Value']['Successful']: success.setdefault( lfn, [] ).extend( result['Value']['Successful'][lfn] ) # Only consider failed the files that are not successful as well failed = [lfn for lfn in result['Value']['Failed'] if lfn not in success] return S_OK( {'Successful': success, 'Failed':failed} ) def __resolveReplicas( self, seList, replicas, ignoreTape = False, requestedProtocol = '' ): diskSEs = set() tapeSEs = set() if not seList: return S_OK( {'Successful': {}, 'Failed': []} ) for localSE in seList: seStatus = StorageElement( localSE ).getStatus()['Value'] if seStatus['Read'] and seStatus['DiskSE']: diskSEs.add( localSE ) elif seStatus['Read'] and seStatus['TapeSE']: tapeSEs.add( localSE ) # For the case that a file is found on two SEs at the same site # disk-based replicas are favoured. # Problematic files will be returned and can be handled by another module failedReplicas = set() newReplicasDict = {} for lfn, reps in replicas.items(): if lfn in self.inputData: # Check that all replicas are on a valid local SE if not [se for se in reps if se in diskSEs.union( tapeSEs )]: failedReplicas.add( lfn ) else: sreps = set( reps ) for seName in diskSEs & sreps: newReplicasDict.setdefault( lfn, [] ).append( seName ) if not newReplicasDict.get( lfn ) and not ignoreTape: for seName in tapeSEs & sreps: newReplicasDict.setdefault( lfn, [] ).append( seName ) # Check that all LFNs have at least one replica and GUID if failedReplicas: # in principle this is not a failure but depends on the policy of the VO # datasets could be downloaded from another site self.log.info( 'The following file(s) were found not to have replicas on any of %s:\n%s' % ( str( seList ), '\n'.join( sorted( failedReplicas ) ) ) ) # Need to group files by SE in order to stage optimally # we know from above that all remaining files have a replica # (preferring disk if >1) in the local storage. # IMPORTANT, only add replicas for input data that is requested # since this module could have been executed after another. seFilesDict = {} for lfn, seList in newReplicasDict.items(): for seName in seList: seFilesDict.setdefault( seName, [] ).append( lfn ) sortedSEs = sorted( [ ( len( lfns ), seName ) for seName, lfns in seFilesDict.items() ], reverse = True ) trackLFNs = {} for _len, seName in sortedSEs: for lfn in seFilesDict[seName]: if 'Size' in replicas[lfn] and 'GUID' in replicas[lfn]: trackLFNs.setdefault( lfn, [] ).append( { 'pfn': replicas.get( lfn, {} ).get( seName, lfn ), 'se': seName, 'size': replicas[lfn]['Size'], 'guid': replicas[lfn]['GUID'] } ) self.log.debug( 'Files grouped by SEs are:\n%s' % str( seFilesDict ) ) for seName, lfns in seFilesDict.items(): self.log.info( ' %s LFNs found from catalog at SE %s' % ( len( lfns ), seName ) ) self.log.verbose( '\n'.join( lfns ) ) # Can now start to obtain TURLs for files grouped by localSE # for requested input data for seName, lfns in seFilesDict.items(): if not lfns: continue failedReps = set() result = StorageElement( seName ).getFileMetadata( lfns ) if not result['OK']: self.log.error( "Error getting metadata.", result['Message'] + ':\n%s' % '\n'.join( lfns ) ) # If we can not get MetaData, most likely there is a problem with the SE # declare the replicas failed and continue failedReps.update( lfns ) continue failed = result['Value']['Failed'] if failed: # If MetaData can not be retrieved for some PFNs # declared them failed and go on for lfn in failed: lfns.remove( lfn ) if type( failed ) == type( {} ): self.log.error( failed[ lfn ], lfn ) failedReps.add( lfn ) for lfn, metadata in result['Value']['Successful'].items(): if metadata['Lost']: error = "File has been Lost by the StorageElement %s" % seName elif metadata['Unavailable']: error = "File is declared Unavailable by the StorageElement %s" % seName elif seName in tapeSEs and not metadata['Cached']: error = "File is no longer in StorageElement %s Cache" % seName else: error = '' if error: lfns.remove( lfn ) self.log.error( error, lfn ) # If PFN is not available # declared it failed and go on failedReps.add( lfn ) if None in failedReps: failedReps.remove( None ) if not failedReps: self.log.info( 'Preliminary checks OK, getting TURLS at %s for:\n%s' % ( seName, '\n'.join( lfns ) ) ) else: self.log.warn( "Errors during preliminary checks for %d files" % len( failedReps ) ) result = StorageElement( seName ).getURL( lfns, protocol = requestedProtocol ) if not result['OK']: self.log.error( "Error getting TURLs", result['Message'] ) return result badTURLCount = 0 badTURLs = [] seResult = result['Value'] for lfn, cause in seResult['Failed'].items(): badTURLCount += 1 badTURLs.append( 'Failed to obtain TURL for %s: %s' % ( lfn, cause ) ) failedReps.add( lfn ) if badTURLCount: self.log.warn( 'Found %s problematic TURL(s) for job %s' % ( badTURLCount, self.jobID ) ) param = '\n'.join( badTURLs ) self.log.info( param ) result = self.__setJobParam( 'ProblematicTURLs', param ) if not result['OK']: self.log.warn( "Error setting job param", result['Message'] ) failedReplicas.update( failedReps ) for lfn, turl in seResult['Successful'].items(): for track in trackLFNs[lfn]: if track['se'] == seName: track['turl'] = turl break self.log.info( 'Resolved input data\n>>>> SE: %s\n>>>>LFN: %s\n>>>>TURL: %s' % ( seName, lfn, turl ) ) ##### End of loop on SE ####### # Check if the files were actually resolved (i.e. have a TURL) # If so, remove them from failed list for lfn, mdataList in trackLFNs.items(): for mdata in list( mdataList ): if 'turl' not in mdata: mdataList.remove( mdata ) self.log.info( 'No TURL resolved for %s at %s' % ( lfn, mdata['se'] ) ) if not mdataList: trackLFNs.pop( lfn, None ) failedReplicas.add( lfn ) elif lfn in failedReplicas: failedReplicas.remove( lfn ) self.log.debug( 'All resolved data', sorted( trackLFNs ) ) self.log.debug( 'All failed data', sorted( failedReplicas ) ) return S_OK( {'Successful': trackLFNs, 'Failed': sorted( failedReplicas )} ) ############################################################################# def __setJobParam( self, name, value ): """Wraps around setJobParameter of state update client """ if not self.jobID: return S_ERROR( 'JobID not defined' ) self.log.verbose( 'setJobParameter(%s, %s, %s)' % ( self.jobID, name, value ) ) return RPCClient( 'WorkloadManagement/JobStateUpdate', timeout = 120 ).setJobParameter( int( self.jobID ), str( name ), str( value ) ) # EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
vmendez/DIRAC
WorkloadManagementSystem/Client/InputDataByProtocol.py
Python
gpl-3.0
11,603
[ "DIRAC" ]
0fca41e35828c004ac1d9ec65b2d72c647abb6d2a62e90dd616d5d664810595a
from __future__ import division, print_function import contextlib import os import random import shutil import subprocess import tempfile import numpy import scipy.linalg as linalg import sympy from opt_utils import rand_matrix class SDP: """Class to generate and test SDP problems. Normally, only methods under 'main components' heading should be called from external code. """ def __init__(self, A=None, B=None, C=None, D=None): """Generate internal variables. The spectrahedron is the surface det(xA + yB + zC + D) = 0 All points are represented as lists of floats A, B, C, D: represented as numpy ndarrays matrices: [A, B, C, D], collected for convenience mins: list of minimizing points of randomly-generated SDPs pmins: list indicating points with multiplicities Each element of pmins takes the form [location, occurances, eigenvalues] nodes: list of spectrahedral nodes, in the form [location, fractional occurances, eigenvalues]. Nodes are sorted in descending order by frequency. spec_nodes: nodes on surface of spectrahedron sym_nodes: other real nodes on symmetroid complex_nodes: nodes with nonzero imaginary parts all nodes represented as [location, eigenvalues] total_nodes: total number of nodes (including complex) trials: number of calls to cvx psd_spec: whether spectrahedron contains psd component nsd_spec: ditto for nsd fully_bounded_directions (fully_unbounded_directions): number of directions in which optimizations on both spectrahedra are bounded (unbounded) """ self.mins = [] self.pmins = [] self.nodes = [] self.spec_nodes = [] self.sym_nodes = [] self.complex_nodes = [] self.total_nodes = 0 self.trials = 0 self.psd_spec = True self.nsd_spec = True self.fully_bounded_directions = 0 self.fully_unbounded_directions = 0 if A is None: self.A = rand_matrix(5,5,symmetric=True,integer=True) else: self.A = A if B is None: self.B = rand_matrix(5,5,symmetric=True,integer=True) else: self.B = B if C is None: self.C = rand_matrix(5,5,symmetric=True,integer=True) else: self.C = C if D is None: self.D = numpy.identity(5, dtype=int) else: self.D = D self.matrices = [self.A, self.B, self.C, self.D] @classmethod def from_file(cls, filename): """Initialize an instance from an output file.""" with open(filename) as f: lines = f.readlines() A = numpy.array(eval(lines[6])).reshape(5,5) B = numpy.array(eval(lines[13])).reshape(5,5) C = numpy.array(eval(lines[20])).reshape(5,5) D = numpy.array(eval(lines[27])).reshape(5,5) return cls(A,B,C,D) # # Utility functions # def matrix(self, vector): """Return (xA+yB+zC+D) at the point designated by vector.""" vec = vector[:] vec.append(1) return sum([vec[i] * self.matrices[i] for i in range(len(self.matrices))]) def eigenvalues(self, vector): """Return the eigenvalues of (xA+yB+zC+D) at a point.""" svd = linalg.svd(self.matrix(vector)) eivals = svd[1] for i in range(len(eivals)): if svd[0][i,i] * svd[2][i,i] < 0: eivals[i] *= -1 return eivals def cvx_solve(self, obj, verbose=False): """Solve an objective function with cvx. obj: vector representing the linear objective to be minimized verbose: whether cvx should print verbose output to stdout Returns a pair representing the optimum of the psd and nsd components (None if that component is either infeasible or unbounded along the optimization direction). Also sets psd_spec, nsd_spec, and fully_(un)bounded_directions. """ import cvxpy as cvx x = cvx.Variable(name='x') y = cvx.Variable(name='y') z = cvx.Variable(name='z') # dummy variable to code semidefinite constraint T = cvx.semidefinite(5,name='T') spec = self.A * x + self.B * y + self.C * z + self.D objective = cvx.Minimize(obj[0]*x + obj[1]*y + obj[2]*z) out_psd = out_nsd = None # check PSD component if self.psd_spec: psd = cvx.Problem(objective, [T == spec]) psd.solve(verbose=verbose) if psd.status == cvx.OPTIMAL: out_psd = [x.value, y.value, z.value] elif psd.status == cvx.INFEASIBLE: self.psd_spec = False # check NSD component if self.nsd_spec: nsd = cvx.Problem(objective, [T == -spec]) nsd.solve(verbose=verbose) if nsd.status == cvx.OPTIMAL: out_nsd = [x.value, y.value, z.value] if self.psd_spec and psd.status == cvx.OPTIMAL: self.fully_bounded_directions += 1 elif nsd.status == cvx.UNBOUNDED \ and self.psd_spec and psd.status == cvx.UNBOUNDED: self.fully_unbounded_directions += 1 elif nsd.status == cvx.INFEASIBLE: self.nsd_spec = False return out_psd, out_nsd # # functions for singular handler # def get_nodes_from_singular(self): """Determine location of nodes with singular. Returns list of real nodes. """ with tempfile.NamedTemporaryFile() as f: self.print_singular_script(file=f) f.flush() output = subprocess.check_output(['singular',f.name]) return self.parse_singular_output(output) def matrix_to_singular(self, matrix): """Format a matrix for input into singular. matrix: matrix to format Returns string usable in singular script. """ # Singular expects matrices in a flattened form without any # decoration. E.g., a 2x2 matrix would be initialized by ## matrix m[2][2] = m11, m12, m21, m22; return str([i for i in matrix.flat])[1:-1] def print_singular_script(self, template="data/singular_script", file=None): """Create a singular script suitable for execution from template. template: template file from which to generate script file: where to write out script """ with open(template) as f: for line in f.readlines(): print(line.format(A=self.matrix_to_singular(self.A), B=self.matrix_to_singular(self.B), C=self.matrix_to_singular(self.C), D=self.matrix_to_singular(self.D)), end='',file=file) def parse_singular_output(self, string): """Parse the output from singular and return list of nodes. string: raw output from singular call Returns list of real nodes and sets total_nodes. """ # Singular uses a tree-like structure for its output, displaying # solution n as ## [n]: ## [1]: ## var1 ## [2]: ## var2 ## [3]: ## var3 # where vari is the value of the i'th variable. Complex numbers # are represented in the format ## (re+i*im) split = string[string.find('[1]'):].splitlines() vectors = [] for i in range(0,len(split),7): self.total_nodes += 1 if '(' in split[i+2] or '(' in split[i+4] or '(' in split[i+6]: continue vectors.append([float(split[i+j]) for j in range(2,8,2)]) return vectors # # functions for bertini handler # def get_nodes_from_bertini(self, verbose=False): """Determine location of nodes with bertini. verbose: set to True to print Bertini output to stdout default is false (suppress Bertini output) Returns list of all nodes. """ @contextlib.contextmanager def temp_directory(): tmpdir = tempfile.mkdtemp() yield tmpdir shutil.rmtree(tmpdir) with temp_directory() as tmpdir: self.print_bertini_script(tmpdir) cwd = os.getcwd() os.chdir(tmpdir) if verbose: subprocess.call(['bertini']) else: with open(os.devnull) as null: subprocess.call(['bertini'], stdout=null, stderr=null) os.chdir(cwd) retval = self.parse_bertini_output(tmpdir) return retval def print_bertini_script(self, directory, template="data/bertini_input"): """Create a bertini script suitable for execution from template. directory: working directory for bertini template: template file from which to generate script """ x, y, z = sympy.symbols('x y z') det = sympy.det( x * sympy.Matrix(self.A) + y * sympy.Matrix(self.B) + z * sympy.Matrix(self.C) + sympy.Matrix(self.D) ) difx = sympy.diff(det,x) dify = sympy.diff(det,y) difz = sympy.diff(det,z) with open(template) as inp: with open(directory + '/input', mode='w') as out: for line in inp.readlines(): print(line.format( F=str(det).replace('**','^'), G=str(difx).replace('**','^'), H=str(dify).replace('**','^'), I=str(difz).replace('**','^') ), file=out, end='') def parse_bertini_output(self, directory): """Parse output from bertini and return list of nodes. directory: working directory for bertini Returns list of all nodes and sets total_nodes. """ with open(directory + '/finite_solutions') as f: lines = f.readlines() # The file finite_solutions contains the number of solutions, # followed by a blank line, followed by the solutions. The # value of each variable is listed on its own line in the form # 're im', and solutions are separated by blank lines. # Graphically this is: # ## n_solutions ## ## x1.re x1.im ## y1.re y1.im ## z1.re z1.im ## ## x2, etc ... # trim trailing newlines while lines[-1] == '\n': lines = lines[:-1] # list of vectors of complex numbers represented as [re, im] complex_vecs = [] for line in lines: if line == '\n': complex_vecs.append([]) continue line = line[:-1].split() if len(line) > 1: complex_vecs[-1].append([float(x) for x in line]) else: self.total_nodes = int(line[0]) # detect real vectors, and convert complex ones to native format vecs = [] for vec in complex_vecs: re, im = list(zip(*vec)) re = list(re) im = list(im) for i in xrange(len(re)): if abs(re[i]) < 1e-10: re[i] = 0 if abs(im[i]) < 1e-10: im[i] = 0 if any([abs(im[i]) for i in range(len(im))]) == 0: vecs.append(list(re)) else: vecs.append([complex(v[0],v[1]) for v in vec]) return vecs # # main components # def print_params(self, file=None): """Print the matrix parameters. file: file to print to (default: stdout) """ print('A:', file=file) print(self.A, file=file) print([a for a in self.A.flat], file=file) print('B:', file=file) print(self.B, file=file) print([b for b in self.B.flat], file=file) print('C:', file=file) print(self.C, file=file) print([c for c in self.C.flat], file=file) print('D:', file=file) print(self.D, file=file) print([d for d in self.D.flat], file=file) print('', file=file) def solve(self, n=1, verbose=False): """Solve optimization problems. n: number of optimizations verbose: whether cvx should print verbose output to stdout Appends results to mins, plus additional side effects described in cvx_solve(). """ for i in range(n): c, = rand_matrix(1,3) psd, nsd = self.cvx_solve(c, verbose) if psd is not None: self.mins.append(psd) if nsd is not None: self.mins.append(nsd) self.trials += n def plot(self, ntheta=10, nphi=20, verbose=False): """Generate a plot of the spectrahedron. Sampling is done using objectives evenly spaced in spherical coordinates, with ntheta and nphi controlling the number of subdivisions along the respective axis. The resulting plot is displayed interactively. Also invokes side effects of cvx_solve(). """ from mayavi import mlab dphi = 2*numpy.pi/nphi dtheta = numpy.pi/ntheta phi,theta = numpy.mgrid[0:numpy.pi+dphi*1.5:dphi, 0:2*numpy.pi+dtheta*1.5:dtheta] Xp = numpy.zeros_like(theta) Yp = numpy.zeros_like(theta) Zp = numpy.zeros_like(theta) Xn = numpy.zeros_like(theta) Yn = numpy.zeros_like(theta) Zn = numpy.zeros_like(theta) for i in range(len(phi)): for j in range(len(phi[i])): obj = [numpy.cos(phi[i,j])*numpy.sin(theta[i,j]), numpy.sin(phi[i,j])*numpy.sin(theta[i,j]), numpy.cos(theta[i,j])] psd, nsd = self.cvx_solve(obj, verbose) if psd is not None: Xp[i,j], Yp[i,j], Zp[i,j] = psd if nsd is not None: Xn[i,j], Yn[i,j], Zn[i,j] = nsd if self.psd_spec: mlab.mesh(Xp, Yp, Zp, colormap='Greys') if self.nsd_spec: mlab.mesh(Xn, Yn, Zn, colormap='Greys') mlab.axes() mlab.show() def get_nodes(self, handler=None): """Determine location of real nodes, and classify them. handler() must output nodes as lists of points. Sets spec_nodes, sym_nodes, and complex_nodes. """ if handler is None: handler = self.get_nodes_from_bertini for vector in handler(): e = self.eigenvalues(vector) if all([v.conjugate() == v for v in vector]): if min([v >= 0 for v in e[:-2]]) \ or min([v <= 0 for v in e[:-2]]): self.spec_nodes.append([vector,e]) else: self.sym_nodes.append([vector,e]) else: self.complex_nodes.append([vector,e]) # define a canonical ordering on nodes for ease of comparison self.spec_nodes.sort(key = lambda x: x[0][0]) self.sym_nodes.sort(key = lambda x: x[0][0]) self.complex_nodes.sort(key = lambda x: x[0][0].real) def process(self, tolerance=1e-3): """Process minima to determine number of occurances. Points x and y are considered identical if norm(x-y)/max(norm(z)) is less than tolerance, where the maximum is over locations of spectrahedral nodes. Calls get_nodes if necessary, sets self.pmins, and clears self.mins. """ if not self.total_nodes: self.get_nodes() if self.spec_nodes: if not self.pmins: self.pmins = [[node[0], 0, node[1]] for node in self.spec_nodes] maxdelta = tolerance * max([linalg.norm(y[0]) for y in self.pmins]) for y in self.pmins: yy = numpy.array(y[0]) for x in self.mins: delta = linalg.norm(numpy.array(x)-yy) if delta <= maxdelta: y[1] += 1 # zero out mins once all elements are processed self.mins = [] def gen_nodes(self): """Fetch all nodes with percent of minima occuring at each. Calls process if necessary, and sets self.nodes. threshold: minimum number of points to be considered a node. If |x-y|/|x| < rel_threshold, discard whichever of x and y has fewer points. """ if self.mins != [] or not self.total_nodes: self.process() self.nodes = [] if self.trials is not 0: for i in self.pmins: self.nodes.append([i[0], i[1] / self.trials, i[2]]) self.nodes.sort(key=lambda x: x[1], reverse=True) else: for i in self.pmins: self.nodes.append([i[0], 0, i[2]]) def print_results(self, file=None): """Print results of optimization to file (default: stdout).""" if self.nodes == []: self.gen_nodes() print("spectrahedral nodes: {0}".format(len(self.pmins)), file=file) print("symmetroid nodes: {0}".format( len(self.sym_nodes) + len(self.pmins) ), file=file) print("total nodes: {0}".format(self.total_nodes), file=file) # Flag this file if any computed node is not a double root # of the determinant polynomial. invalid_node = False for node in self.spec_nodes: if node[1][3]/node[1][2] > 1e-5: invalid_node = True for node in self.sym_nodes: if node[1][3]/node[1][2] > 1e-5: invalid_node = True if invalid_node: print("invalid node detected", file=file) print("", file=file) if self.trials is not 0: print("has psd component: {0}".format(self.psd_spec), file=file) print("has nsd component: {0}".format(self.nsd_spec), file=file) if self.psd_spec and self.nsd_spec: print("fraction of twice-solvable objectives: {0}".format( self.fully_bounded_directions / self.trials ), file=file) print("fraction of twice-unbounded objectives: {0}".format( self.fully_unbounded_directions / self.trials ), file=file) print("", file=file) for i in range(len(self.nodes)): print("node {0}:".format(i+1), file=file) print("location: {0}".format(self.nodes[i][0]), file=file) if self.trials is not 0: print("probability: {0}".format(self.nodes[i][1]), file=file) print("eigenvalues:", file=file) print(self.nodes[i][2], file=file) print('', file=file) for i in range(len(self.sym_nodes)): print("symmetroid node {0}:".format(i+1), file=file) print("location: {0}".format(self.sym_nodes[i][0]), file=file) print("eigenvalues:", file=file) print(self.sym_nodes[i][1], file=file) print("", file=file) for i in range(len(self.complex_nodes)): print("complex node {0}:".format(i+1), file=file) print("location: {0}".format(self.complex_nodes[i][0]), file=file) print("eigenvalues:", file=file) print(self.complex_nodes[i][1], file=file) print("", file=file)
jre21/SDP
sdp.py
Python
gpl-3.0
19,989
[ "Mayavi" ]
e20ee7862c8057834449bb70f06d1aada3fda589a62b4cf187156a50eea86c1d
# -*- coding: utf-8 -*- """ Contains GandiModule and GandiContextHelper classes. GandiModule class is used by commands modules. GandiContextHelper class is used as click context for commands. """ from __future__ import print_function import os import sys import time import os.path from datetime import datetime from subprocess import check_call, Popen, PIPE, CalledProcessError import click from click.exceptions import UsageError from .client import XMLRPCClient, APICallFailed, DryRunException, JsonClient from .conf import GandiConfig class MissingConfiguration(Exception): """ Raise when no configuration was found. """ class GandiModule(GandiConfig): """ Base class for modules. Manage - initializing xmlrpc connection - execute remote api calls """ _op_scores = {'BILL': 0, 'WAIT': 1, 'RUN': 2, 'DONE': 3} verbose = 0 _api = None # frequency of api calls when polling for operation progress _poll_freq = 1 @classmethod def get_api_connector(cls): """ Initialize an api connector for future use.""" if cls._api is None: # pragma: no cover cls.load_config() cls.debug('initialize connection to remote server') apihost = cls.get('api.host') if not apihost: raise MissingConfiguration() apienv = cls.get('api.env') if apienv and apienv in cls.apienvs: apihost = cls.apienvs[apienv] cls._api = XMLRPCClient(host=apihost, debug=cls.verbose) return cls._api @classmethod def call(cls, method, *args, **kwargs): """ Call a remote api method and return the result.""" api = None empty_key = kwargs.pop('empty_key', False) try: api = cls.get_api_connector() apikey = cls.get('api.key') if not apikey and not empty_key: cls.echo("No apikey found, please use 'gandi setup' " "command") sys.exit(1) except MissingConfiguration: if api and empty_key: apikey = '' elif not kwargs.get('safe'): cls.echo("No configuration found, please use 'gandi setup' " "command") sys.exit(1) else: return [] # make the call cls.debug('calling method: %s' % method) for arg in args: cls.debug('with params: %r' % arg) try: resp = api.request(method, apikey, *args, **{'dry_run': kwargs.get('dry_run', False), 'return_dry_run': kwargs.get('return_dry_run', False)}) cls.dump('responded: %r' % resp) return resp except APICallFailed as err: if kwargs.get('safe'): return [] if err.code == 530040: cls.echo("Error: It appears you haven't purchased any credits " "yet.\n" "Please visit https://www.gandi.net/credit/buy to " "learn more and buy credits.") sys.exit(1) if err.code == 510150: cls.echo("Invalid API key, please use 'gandi setup' command.") sys.exit(1) if isinstance(err, DryRunException): if kwargs.get('return_dry_run', False): return err.dry_run else: for msg in err.dry_run: # TODO use trads with %s cls.echo(msg['reason']) cls.echo('\t' + ' '.join(msg['attr'])) sys.exit(1) error = UsageError(err.errors) setattr(error, 'code', err.code) raise error @classmethod def safe_call(cls, method, *args): """ Call a remote api method but don't raise if an error occurred.""" return cls.call(method, *args, safe=True) @classmethod def json_call(cls, method, url, **kwargs): """ Call a remote api using json format """ # retrieve api key if needed empty_key = kwargs.pop('empty_key', False) send_key = kwargs.pop('send_key', True) return_header = kwargs.pop('return_header', False) try: apikey = cls.get('apirest.key') if not apikey and not empty_key: cls.echo("No apikey found for REST API, please use " "'gandi setup' command") sys.exit(1) if send_key: if 'headers' in kwargs: kwargs['headers'].update({'X-Api-Key': apikey}) else: kwargs['headers'] = {'X-Api-Key': apikey} except MissingConfiguration: if not empty_key: return [] # make the call cls.debug('calling url: %s %s' % (method, url)) cls.debug('with params: %r' % kwargs) try: resp, resp_headers = JsonClient.request(method, url, **kwargs) cls.dump('responded: %r' % resp) if return_header: return resp, resp_headers return resp except APICallFailed as err: cls.echo('An error occured during call: %s' % err.errors) sys.exit(1) @classmethod def json_get(cls, url, **kwargs): """ Helper for GET json request """ return cls.json_call('GET', url, **kwargs) @classmethod def json_post(cls, url, **kwargs): """ Helper for POST json request """ return cls.json_call('POST', url, **kwargs) @classmethod def json_put(cls, url, **kwargs): """ Helper for PUT json request """ return cls.json_call('PUT', url, **kwargs) @classmethod def json_delete(cls, url, **kwargs): """ Helper for DELETE json request """ return cls.json_call('DELETE', url, **kwargs) @classmethod def intty(cls): """ Check if we are in a tty. """ # XXX: temporary hack until we can detect if we are in a pipe or not return True if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): return True return False @classmethod def echo(cls, message): """ Display message. """ if cls.intty(): if message is not None: print(message) @classmethod def pretty_echo(cls, message): """ Display message using pretty print formatting. """ if cls.intty(): if message: from pprint import pprint pprint(message) @classmethod def separator_line(cls, sep='-', size=10): """ Display a separator line. """ if cls.intty(): cls.echo(sep * size) @classmethod def separator_sub_line(cls, sep='-', size=10): """ Display a separator line. """ if cls.intty(): cls.echo("\t" + sep * size) @classmethod def dump(cls, message): """ Display dump message if verbose level allows it. """ if cls.verbose > 2: msg = '[DUMP] %s' % message cls.echo(msg) @classmethod def debug(cls, message): """ Display debug message if verbose level allows it. """ if cls.verbose > 1: msg = '[DEBUG] %s' % message cls.echo(msg) @classmethod def log(cls, message): """ Display info message if verbose level allows it. """ if cls.verbose > 0: msg = '[INFO] %s' % message cls.echo(msg) @classmethod def deprecated(cls, message): print('[deprecated]: %s' % message, file=sys.stderr) @classmethod def error(cls, msg): """ Raise click UsageError exception using msg. """ raise UsageError(msg) @classmethod def execute(cls, command, shell=True): """ Execute a shell command. """ cls.debug('execute command (shell flag:%r): %r ' % (shell, command)) try: check_call(command, shell=shell) return True except CalledProcessError: return False @classmethod def exec_output(cls, command, shell=True, encoding='utf-8'): """ Return execution output :param encoding: charset used to decode the stdout :type encoding: str :return: the return of the command :rtype: unicode string """ proc = Popen(command, shell=shell, stdout=PIPE) stdout, _stderr = proc.communicate() if proc.returncode == 0: return stdout.decode(encoding) return '' @classmethod def update_progress(cls, progress, starttime): """ Display an ascii progress bar while processing operation. """ width, _height = click.get_terminal_size() if not width: return duration = datetime.utcnow() - starttime hours, remainder = divmod(duration.seconds, 3600) minutes, seconds = divmod(remainder, 60) size = int(width * .6) status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = 'error: progress var must be float\n' cls.echo(type(progress)) if progress < 0: progress = 0 status = 'Halt...\n' if progress >= 1: progress = 1 # status = 'Done...\n' block = int(round(size * progress)) text = ('\rProgress: [{0}] {1:.2%} {2} {3:0>2}:{4:0>2}:{5:0>2} ' ''.format('#' * block + '-' * (size - block), progress, status, hours, minutes, seconds)) sys.stdout.write(text) sys.stdout.flush() @classmethod def display_progress(cls, operations): """ Display progress of Gandi operations. polls API every 1 seconds to retrieve status. """ start_crea = datetime.utcnow() # count number of operations, 3 steps per operation if not isinstance(operations, (list, tuple)): operations = [operations] count_operations = len(operations) * 3 updating_done = False while not updating_done: op_score = 0 for oper in operations: op_ret = cls.call('operation.info', oper['id']) op_step = op_ret['step'] if op_step in cls._op_scores: op_score += cls._op_scores[op_step] else: cls.echo('') msg = 'step %s unknown, exiting' % op_step if op_step == 'ERROR': msg = ('An error has occured during operation ' 'processing: %s' % op_ret['last_error']) elif op_step == 'SUPPORT': msg = ('An error has occured during operation ' 'processing, you must contact Gandi support.') cls.echo(msg) sys.exit(1) cls.update_progress(float(op_score) / count_operations, start_crea) if op_score == count_operations: updating_done = True time.sleep(cls._poll_freq) cls.echo('\r') class GandiContextHelper(GandiModule): """ Gandi context helper. Import module classes from modules directory upon initialization. """ _modules = {} def __init__(self, verbose=-1): """ Initialize variables and api connection. """ GandiModule.verbose = verbose GandiModule.load_config() # only load modules once if not self._modules: self.load_modules() def __getattribute__(self, item): """ Return module from internal imported modules dict. """ if item in object.__getattribute__(self, '_modules'): return object.__getattribute__(self, '_modules')[item] return object.__getattribute__(self, item) def load_modules(self): """ Import CLI commands modules. """ module_folder = os.path.join(os.path.dirname(__file__), '..', 'modules') module_dirs = { 'gandi.cli': module_folder } if 'GANDICLI_PATH' in os.environ: for _path in os.environ.get('GANDICLI_PATH').split(':'): # remove trailing separator if any path = _path.rstrip(os.sep) module_dirs[os.path.basename(path)] = os.path.join(path, 'modules') for module_basename, dir in list(module_dirs.items()): for filename in sorted(os.listdir(dir)): if filename.endswith('.py') and '__init__' not in filename: submod = filename[:-3] module_name = module_basename + '.modules.' + submod __import__(module_name, fromlist=[module_name]) # save internal map of loaded module classes for subclass in GandiModule.__subclasses__(): self._modules[subclass.__name__.lower()] = subclass
grigouze/gandi.cli
gandi/cli/core/base.py
Python
gpl-3.0
13,404
[ "VisIt" ]
7f1737133b0b7b43880f198f646e39cf905c56cd6eb9d2163e63093edaca4694
import imp import re _NOT_USED1 = None NOT_USED2 = None def getModules(n = 0, j = 3) : "Return list of modules by removing .py from each entry." for m in unknownList : pass def jjj(self) : import sys print sys.argv def jjj2(a, b = None, c = None) : pass def ddd(a, *args): jjj2() jjj2(1) jjj2(1, 2) jjj2(1, 2, 3) jjj2(1, 2, 3, 4) def ppp(): ddd() ddd(1) ddd(1, 2) ddd(1, 2, 3) class X: def __init__(self) : print sys.argv print self.__class__, self.__doc__, self.__dict__, self.__x__, self.x self.y = 0 print self.y def r(sf): nofunc() for i in range(0, len(self.a)) : jjj(1, 2, 3, k=5) class Y(X): def xxx(self, adf) : asdf = adf # jjjj doesn't exist j = jjjj # z() doesn't exist self.z() adf.mmm.kkk() # j doesn't exist self.j = 0 self.xxx(1, 2) def uuu(): a=1+2 return a[0], [['a', 'b'], [1,2,3,4]] def renderElement(a, b=2, c=3, **kw): contents = kw print contents def renderItem(text): return renderElement(1, contents=text, z=1, y=2, x=3) def test_kw_lambda(a, b, c): return renderElement(a, ff=lambda value: '=' + renderItem(b)) str = '53' _ = "blah, don't care, shouldn't warn" def getOneImageFromPath(k, v): d = [] d.append(id=k, original_flag=v)
stanlyxiang/incubator-hawq
tools/bin/pythonSrc/pychecker-0.8.18/test_input/test1.py
Python
apache-2.0
1,403
[ "ADF" ]
565fd40e2d6b6bb5b81f10fb9888d33827308ebb0cd5bc26d27b8344b47207b1
from toontown.toonbase.TTLocalizerEnglishProperty import * from toontown.catalog import CatalogAccessoryItemGlobals from otp.otpbase import OTPLocalizer as OL OL.SpeedChatStaticText = OL.SpeedChatStaticTextToontown.copy() for key in OL.SpeedChatStaticTextCommon.iterkeys(): OL.SpeedChatStaticText[key] = OL.SpeedChatStaticTextCommon[key] commitmantst = 'kptmptest - removable' InterfaceFont = 'phase_3/models/fonts/ImpressBT.ttf' ToonFont = 'phase_3/models/fonts/ImpressBT.ttf' SuitFont = 'phase_3/models/fonts/vtRemingtonPortable.ttf' SignFont = 'phase_3/models/fonts/MickeyFont' MinnieFont = 'phase_3/models/fonts/MinnieFont' FancyFont = 'phase_3/models/fonts/Comedy' BuildingNametagFont = 'phase_3/models/fonts/MickeyFont' BuildingNametagShadow = None NametagFonts = ( 'phase_3/models/fonts/ImpressBT.ttf', 'phase_3/models/fonts/AnimGothic.bam', 'phase_3/models/fonts/Aftershock.bam', 'phase_3/models/fonts/JiggeryPokery.bam', 'phase_3/models/fonts/Ironwork.bam', 'phase_3/models/fonts/HastyPudding.bam', 'phase_3/models/fonts/Comedy.bam', 'phase_3/models/fonts/Humanist.bam', 'phase_3/models/fonts/Portago.bam', 'phase_3/models/fonts/Musicals.bam', 'phase_3/models/fonts/Scurlock.bam', 'phase_3/models/fonts/Danger.bam', 'phase_3/models/fonts/Alie.bam', 'phase_3/models/fonts/OysterBar.bam', 'phase_3/models/fonts/RedDogSaloon.bam', 'phase_3/models/fonts/PBN.ttf', 'phase_3/models/fonts/SomethingStrange.ttf', 'phase_3/models/fonts/DinosaursAreAlive.ttf', 'phase_3/models/fonts/Friends.ttf' ) NametagFontNames = ( 'Basic', 'Plain', 'Shivering', 'Wonky', 'Fancy', 'Silly', 'Zany', 'Practical', 'Nautical', 'Whimsical', 'Spooky', 'Action', 'Poetic', 'Boardwalk', 'Western', 'Pixelated', 'Metal', 'Dinosaurs', 'Friends' ) NametagLabel = ' Nametag' UnpaidNameTag = 'Basic' ScreenshotPath = 'screenshots/' GM_NAMES = ('TOON COUNCIL', 'TOON TROOPER', 'RESISTANCE RANGER', 'GC') ProductPrefix = 'TT' Mickey = 'Mickey' VampireMickey = 'VampireMickey' Minnie = 'Minnie' WitchMinnie = 'WitchMinnie' Donald = 'Donald' DonaldDock = 'DonaldDock' FrankenDonald = 'FrankenDonald' Daisy = 'Daisy' SockHopDaisy = 'SockHopDaisy' Goofy = 'Goofy' SuperGoofy = 'SuperGoofy' Pluto = 'Pluto' WesternPluto = 'WesternPluto' Flippy = 'Flippy' Chip = 'Chip' Dale = 'Dale' JailbirdDale = 'JailbirdDale' PoliceChip = 'PoliceChip' lTheBrrrgh = 'The Brrrgh' lDaisyGardens = 'Daisy Gardens' lDonaldsDock = "Donald's Dock" lDonaldsDreamland = "Donald's Dreamland" lMinniesMelodyland = "Minnie's Melodyland" lToontownCentral = 'Toontown Central' lToonHQ = 'Toon HQ' lSellbotHQ = 'Sellbot HQ' lGoofySpeedway = 'Goofy Speedway' lOutdoorZone = "Chip 'n Dale's Acorn Acres" lGolfZone = "Chip 'n Dale's MiniGolf" lPartyHood = 'Party Grounds' GlobalStreetNames = {20000: ('to', 'on', 'Tutorial Terrace'), 1000: ('to the', 'in the', 'Playground'), 1100: ('to', 'on', 'Barnacle Boulevard'), 1200: ('to', 'on', 'Seaweed Street'), 1300: ('to', 'on', 'Lighthouse Lane'), 2000: ('to the', 'in the', 'Playground'), 2100: ('to', 'on', 'Silly Street'), 2200: ('to', 'on', 'Loopy Lane'), 2300: ('to', 'on', 'Punchline Place'), 3000: ('to the', 'in the', 'Playground'), 3100: ('to', 'on', 'Walrus Way'), 3200: ('to', 'on', 'Sleet Street'), 3300: ('to', 'on', 'Polar Place'), 4000: ('to the', 'in the', 'Playground'), 4100: ('to', 'on', 'Alto Avenue'), 4200: ('to', 'on', 'Baritone Boulevard'), 4300: ('to', 'on', 'Tenor Terrace'), 4400: ('to', 'on', 'Soprano Street'), 5000: ('to the', 'in the', 'Playground'), 5100: ('to', 'on', 'Elm Street'), 5200: ('to', 'on', 'Maple Street'), 5300: ('to', 'on', 'Oak Street'), 5400: ('to', 'on', 'Rose Valley'), 9000: ('to the', 'in the', 'Playground'), 9100: ('to', 'on', 'Lullaby Lane'), 9200: ('to', 'on', 'Pajama Place'), 10000: ('to', 'in', 'Bossbot HQ Country Club'), 10100: ('to the', 'in the', 'Bossbot HQ Clubhouse Lobby'), 10200: ('to the', 'in the', 'Clubhouse'), 10500: ('to the', 'in the', 'Front Three'), 10600: ('to the', 'in the', 'Middle Six'), 10700: ('to the', 'in the', 'Back Nine'), 11000: ('to the', 'in the', 'Sellbot HQ Junkyard'), 11100: ('to the', 'in the', 'Sellbot HQ Towers Lobby'), 11200: ('to the', 'in the', 'Sellbot Factory Exterior'), 11500: ('to the', 'in the', 'Sellbot Factory'), 12000: ('to', 'in', 'Cashbot Train Yard'), 12100: ('to the', 'in the', 'Cashbot HQ Cashbot Vault Lobby'), 12500: ('to the', 'in the', 'Cashbot Coin Mint'), 12600: ('to the', 'in the', 'Cashbot Dollar Mint'), 12700: ('to the', 'in the', 'Cashbot Bullion Mint'), 13000: ('to', 'in', 'Lawbot HQ Courtyard'), 13100: ('to the', 'in the', 'Courthouse Lobby'), 13200: ('to the', 'in the', "DA's Office Lobby"), 13300: ('to the', 'in the', 'Lawbot A Office'), 13400: ('to the', 'in the', 'Lawbot B Office'), 13500: ('to the', 'in the', 'Lawbot C Office'), 13600: ('to the', 'in the', 'Lawbot D Office')} DonaldsDock = ('to', 'in', lDonaldsDock) ToontownCentral = ('to', 'in', lToontownCentral) TheBrrrgh = ('to', 'in', lTheBrrrgh) MinniesMelodyland = ('to', 'in', lMinniesMelodyland) DaisyGardens = ('to', 'in', lDaisyGardens) OutdoorZone = ('to', 'in', lOutdoorZone) FunnyFarm = ('to the', 'in the', '???') GoofySpeedway = ('to', 'in', lGoofySpeedway) DonaldsDreamland = ('to', 'in', lDonaldsDreamland) BossbotHQ = ('to', 'in', 'Bossbot HQ') SellbotHQ = ('to', 'in', 'Sellbot HQ') CashbotHQ = ('to', 'in', 'Cashbot HQ') LawbotHQ = ('to', 'in', 'Lawbot HQ') Tutorial = ('to the', 'in the', 'Toon-torial') MyEstate = ('to', 'in', 'your house') WelcomeValley = ('to', 'in', 'Welcome Valley') GolfZone = ('to', 'in', lGolfZone) PartyHood = ('to the', 'in the', lPartyHood) Factory = 'Factory' Headquarters = 'Headquarters' SellbotFrontEntrance = 'Front Entrance' SellbotSideEntrance = 'Side Entrance' Office = 'Office' FactoryNames = {0: 'Factory Mockup', 11500: 'Sellbot Cog Factory', 13300: 'Lawbot Cog Office'} FactoryTypeLeg = 'Leg' FactoryTypeArm = 'Arm' FactoryTypeTorso = 'Torso' MintFloorTitle = 'Floor %s' lCancel = 'Cancel' lClose = 'Close' lOK = 'OK' lNext = 'Next' lQuit = 'Quit' lYes = 'Yes' lNo = 'No' sleep_auto_reply = '%s is sleeping right now' lHQOfficerF = 'HQ Officer' lHQOfficerM = 'HQ Officer' MickeyMouse = 'Mickey Mouse' AIStartDefaultDistrict = 'Sillyville' Cog = 'Cog' Cogs = 'Cogs' ACog = 'a Cog' TheCogs = 'The Cogs' ASkeleton = 'a Skelecog' Skeleton = 'Skelecog' SkeletonP = 'Skelecogs' Av2Cog = 'a Version 2.0 Cog' v2Cog = 'Version 2.0 Cog' v2CogP = 'Version 2.0 Cogs' ASkeleton = 'a Skelecog' Foreman = 'Factory Foreman' ForemanP = 'Factory Foremen' AForeman = 'a Factory Foreman' CogVP = Cog + ' V.P.' CogVPs = "Cog V.P.'s" ACogVP = ACog + ' V.P.' Supervisor = 'Mint Supervisor' SupervisorP = 'Mint Supervisors' ASupervisor = 'a Mint Supervisor' President = 'Club President' PresidentP = 'Club Presidents' APresident = 'a Club President' Clerk = 'Clerk' ClerkP = 'Clerks' AClerk = 'a Clerk' CogCFO = Cog + ' C.F.O.' CogCFOs = "Cog C.F.O.'s" ACogCFO = ACog + ' C.F.O.' TheFish = 'the Fish' AFish = 'a fish' Level = 'Level' QuestsCompleteString = 'Complete' QuestsNotChosenString = 'Not chosen' Period = '.' Laff = 'Laff' QuestInLocationString = ' %(inPhrase)s %(location)s' QuestsDefaultGreeting = ('Hello, _avName_!', 'Hi, _avName_!', 'Hey there, _avName_!', 'Say there, _avName_!', 'Welcome, _avName_!', 'Howdy, _avName_!', 'How are you, _avName_?', 'Greetings _avName_!') QuestsDefaultIncomplete = ("How's that task coming, _avName_?", 'Looks like you still have more work to do on that task!', 'Keep up the good work, _avName_!', 'Keep trying to finish that task. I know you can do it!', 'Keep trying to complete that task, we are counting on you!', 'Keep working on that ToonTask!') QuestsDefaultIncompleteProgress = ('You came to the right place, but you need to finish your ToonTask first.', 'When you are finished with that ToonTask, come back here.', 'Come back when you are finished with your ToonTask.') QuestsDefaultIncompleteWrongNPC = ('Nice work on that ToonTask. You should go visit _toNpcName_._where_', 'Looks like you are ready to finish your ToonTask. Go see _toNpcName_._where_.', 'Go see _toNpcName_ to finish your ToonTask._where_') QuestsDefaultComplete = ('Nice work! Here is your reward...', 'Great job, _avName_! Take this reward...', 'Wonderful job, _avName_! Here is your reward...') QuestsDefaultLeaving = ('Bye!', 'Goodbye!', 'So long, _avName_.', 'See ya, _avName_!', 'Good luck!', 'Have fun in Toontown!', 'See you later!') QuestsDefaultReject = ('Heya, _avName_!', 'Whatcha need?', 'Hello! How are you doing?', 'Hi there.', "Sorry _avName_, I'm a bit busy right now.", 'Yes?', 'Howdy, _avName_.', 'Welcome, _avName_!', "Hey, _avName_! How's it hanging?", "Need any help?", "Hi _avName_, what brings you here?", "These new gags from Goofy's Gag Shop are pretty nifty.", "I just bought a new gag earlier. That'll show those Cogs!", "I heard that Soggy Nell's building was taken over by the cogs. That could never happen here... right?", "I've heard rumors of gigantic Cog HQs being made on the outskirts of Toontown. I sure hope they are only rumors.") QuestsDefaultTierNotDone = ('Hello, _avName_! You must finish your current ToonTasks before getting a new one.', 'Hi there! You need to finish the ToonTasks you are working on in order to get a new one.', 'Hi, _avName_! Before I can give you a new ToonTask, you need to finish the ones you have.') QuestsDefaultQuest = None QuestsDefaultVisitQuestDialog = ('I heard _toNpcName_ is looking for you._where_', 'Stop by and see _toNpcName_ when you get a chance._where_', 'Pay a visit to _toNpcName_ next time you are over that way._where_', 'If you get a chance, stop in and say hi to _toNpcName_._where_', '_toNpcName_ will give you your next ToonTask._where_') QuestsLocationArticle = '' def getLocalNum(num): return str(num) QuestsItemNameAndNum = '%(num)s %(name)s' QuestsCogQuestProgress = '%(progress)s of %(numCogs)s defeated' QuestsCogQuestHeadline = 'WANTED' QuestsCogQuestSCStringS = 'I need to defeat %(cogName)s%(cogLoc)s.' QuestsCogQuestSCStringP = 'I need to defeat some %(cogName)s%(cogLoc)s.' QuestsCogQuestDefeat = 'Defeat %s' QuestsCogQuestDefeatDesc = '%(numCogs)s %(cogName)s' QuestsCogNewNewbieQuestObjective = 'Help a new Toon defeat %s' QuestsCogNewNewbieQuestCaption = 'Help a new Toon %d Laff or less' QuestsCogOldNewbieQuestObjective = 'Help a Toon with %(laffPoints)d Laff or less defeat %(objective)s' QuestsCogOldNewbieQuestCaption = 'Help a Toon %d Laff or less' QuestsCogNewbieQuestAux = 'Defeat:' QuestsNewbieQuestHeadline = 'APPRENTICE' QuestsCogTrackQuestProgress = '%(progress)s of %(numCogs)s defeated' QuestsCogTrackQuestHeadline = 'WANTED' QuestsCogTrackQuestSCStringS = 'I need to defeat %(cogText)s%(cogLoc)s.' QuestsCogTrackQuestSCStringP = 'I need to defeat some %(cogText)s%(cogLoc)s.' QuestsCogTrackQuestDefeat = 'Defeat %s' QuestsCogTrackDefeatDesc = '%(numCogs)s %(trackName)s' QuestsCogLevelQuestProgress = '%(progress)s of %(numCogs)s defeated' QuestsCogLevelQuestHeadline = 'WANTED' QuestsCogLevelQuestDefeat = 'Defeat %s' QuestsCogLevelQuestDesc = 'a Level %(level)s+ %(name)s' QuestsCogLevelQuestDescC = '%(count)s Level %(level)s+ %(name)s' QuestsCogLevelQuestDescI = 'some Level %(level)s+ %(name)s' QuestsCogLevelQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsBuildingQuestFloorNumbers = ('', 'two+', 'three+', 'four+', 'five+', 'six') QuestsBuildingQuestBuilding = 'Building' QuestsBuildingQuestBuildings = 'Buildings' QuestsBuildingQuestHeadline = 'DEFEAT' QuestsBuildingQuestProgressString = '%(progress)s of %(num)s defeated' QuestsBuildingQuestString = 'Defeat %s' QuestsBuildingQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsBuildingQuestDesc = 'a %(type)s Building' QuestsBuildingQuestDescF = 'a %(floors)s story %(type)s Building' QuestsBuildingQuestDescC = '%(count)s %(type)s Buildings' QuestsBuildingQuestDescCF = '%(count)s %(floors)s story %(type)s Buildings' QuestsBuildingQuestDescI = 'some %(type)s Buildings' QuestsBuildingQuestDescIF = 'some %(floors)s story %(type)s Buildings' QuestsCogdoQuestCogdo = 'Field Office' QuestsCogdoQuestCogdos = 'Field Offices' QuestsCogdoQuestHeadline = 'DEFEAT' QuestsCogdoQuestProgressString = '%(progress)s of %(num)s defeated' QuestsCogdoQuestString = 'Defeat %s' QuestsCogdoQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsCogdoQuestDesc = 'a %(type)s Field Office' QuestsCogdoQuestDescC = '%(count)s %(type)s Field Offices' QuestsCogdoQuestDescI = 'some %(type)s Field Offices' QuestFactoryQuestFactory = 'Factory' QuestsFactoryQuestFactories = 'Factories' QuestsFactoryQuestHeadline = 'INFILTRATE' QuestsFactoryQuestProgressString = '%(progress)s of %(num)s defeated' QuestsFactoryQuestString = 'Defeat %s' QuestsFactoryQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsFactoryQuestDesc = 'a %(type)s Factory' QuestsFactoryQuestDescC = '%(count)s %(type)s Factories' QuestsFactoryQuestDescI = 'some %(type)s Factories' QuestMintQuestMint = 'Mint' QuestsMintQuestMints = 'Mints' QuestsMintQuestHeadline = 'INFILTRATE' QuestsMintQuestProgressString = '%(progress)s of %(num)s defeated' QuestsMintQuestString = 'Defeat %s' QuestsMintQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsMintQuestDesc = 'a Cog Mint' QuestsMintQuestDescC = '%(count)s Cog Mints' QuestsMintQuestDescI = 'some Cog Mints' QuestStageQuestStage = 'District Attorney Office' QuestsStageQuestStages = 'District Attorney Offices' QuestsStageQuestHeadline = 'INFILTRATE' QuestsStageQuestProgressString = '%(progress)s of %(num)s defeated' QuestsStageQuestString = 'Defeat %s' QuestsStageQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsStageQuestDesc = 'a District Attorney Office' QuestsStageQuestDescC = '%(count)s District Attorney Offices' QuestsStageQuestDescI = 'some District Attorney Offices' QuestClubQuestClub = 'Club' QuestsClubQuestClubs = 'Cog Golf Courses' QuestsClubQuestHeadline = 'INFILTRATE' QuestsClubQuestProgressString = '%(progress)s of %(num)s defeated' QuestsClubQuestString = 'Defeat %s' QuestsClubQuestSCString = 'I need to defeat %(objective)s%(location)s.' QuestsClubQuestDesc = 'a Cog Golf Course' QuestsClubQuestDescC = '%(count)s Cog Golf Courses' QuestsClubQuestDescI = 'some Cog Golf Courses' QuestsRescueQuestProgress = '%(progress)s of %(numToons)s rescued' QuestsRescueQuestHeadline = 'RESCUE' QuestsRescueQuestSCStringS = 'I need to rescue a Toon%(toonLoc)s.' QuestsRescueQuestSCStringP = 'I need to rescue some Toons%(toonLoc)s.' QuestsRescueQuestRescue = 'Rescue %s' QuestsRescueQuestRescueDesc = '%(numToons)s Toons' QuestsRescueQuestToonS = 'a Toon' QuestsRescueQuestToonP = 'Toons' QuestsRescueQuestAux = 'Rescue:' QuestsRescueNewNewbieQuestObjective = 'Help a new Toon rescue %s' QuestsRescueOldNewbieQuestObjective = 'Help a Toon with %(laffPoints)d Laff or less rescue %(objective)s' QuestCogPartQuestCogPart = 'Cog Suit Part' QuestsCogPartQuestFactories = 'Factories' QuestsCogPartQuestHeadline = 'RETRIEVE' QuestsCogPartQuestProgressString = '%(progress)s of %(num)s retrieved' QuestsCogPartQuestString = 'Retrieve %s' QuestsCogPartQuestSCString = 'I need to retrieve %(objective)s%(location)s.' QuestsCogPartQuestAux = 'Retrieve:' QuestsCogPartQuestDesc = 'a Cog Suit Part' QuestsCogPartQuestDescC = '%(count)s Cog Suit Parts' QuestsCogPartQuestDescI = 'some Cog Suit Parts' QuestsCogPartNewNewbieQuestObjective = 'Help a new Toon retrieve %s' QuestsCogPartOldNewbieQuestObjective = 'Help a Toon with %(laffPoints)d Laff or less retrieve %(objective)s' QuestsDeliverGagQuestProgress = '%(progress)s of %(numGags)s delivered' QuestsDeliverGagQuestHeadline = 'DELIVER' QuestsDeliverGagQuestToSCStringS = 'I need to deliver %(gagName)s.' QuestsDeliverGagQuestToSCStringP = 'I need to deliver some %(gagName)s.' QuestsDeliverGagQuestSCString = 'I need make a delivery.' QuestsDeliverGagQuestString = 'Deliver %s' QuestsDeliverGagQuestStringLong = 'Deliver %s to _toNpcName_.' QuestsDeliverGagQuestInstructions = 'You can buy this gag in the Gag Shop once you earn access to it.' QuestsDeliverItemQuestProgress = '' QuestsDeliverItemQuestHeadline = 'DELIVER' QuestsDeliverItemQuestSCString = 'I need to deliver %(article)s%(itemName)s.' QuestsDeliverItemQuestString = 'Deliver %s' QuestsDeliverItemQuestStringLong = 'Deliver %s to _toNpcName_.' QuestsVisitQuestProgress = '' QuestsVisitQuestHeadline = 'VISIT' QuestsVisitQuestStringShort = 'Visit' QuestsVisitQuestStringLong = 'Visit _toNpcName_' QuestsVisitQuestSeeSCString = 'I need to see %s.' QuestsRecoverItemQuestProgress = '%(progress)s of %(numItems)s recovered' QuestsRecoverItemQuestHeadline = 'RECOVER' QuestsRecoverItemQuestSeeHQSCString = 'I need to see an ' + lHQOfficerM + '.' QuestsRecoverItemQuestReturnToHQSCString = 'I need to return %s to an ' + lHQOfficerM + '.' QuestsRecoverItemQuestReturnToSCString = 'I need to return %(item)s to %(npcName)s.' QuestsRecoverItemQuestGoToHQSCString = 'I need to go to a Toon HQ.' QuestsRecoverItemQuestGoToPlaygroundSCString = 'I need to go to %s Playground.' QuestsRecoverItemQuestGoToStreetSCString = 'I need to go %(to)s %(street)s in %(hood)s.' QuestsRecoverItemQuestVisitBuildingSCString = 'I need to visit %s%s.' QuestsRecoverItemQuestWhereIsBuildingSCString = 'Where is %s%s?' QuestsRecoverItemQuestRecoverFromSCString = 'I need to recover %(item)s from %(holder)s%(loc)s.' QuestsRecoverItemQuestString = 'Recover %(item)s from %(holder)s' QuestsRecoverItemQuestHolderString = '%(level)s %(holder)d+ %(cogs)s' QuestsTrackChoiceQuestHeadline = 'CHOOSE' QuestsTrackChoiceQuestSCString = 'I need to choose a gag track.' QuestsTrackChoiceQuestString = 'Choose a gag track' QuestsFriendQuestHeadline = 'FRIEND' QuestsFriendQuestSCString = 'I need to make a friend.' QuestsFriendQuestString = 'Make a friend' QuestsMailboxQuestHeadline = 'MAIL' QuestsMailboxQuestSCString = 'I need to check my mail.' QuestsMailboxQuestString = 'Check your mail' QuestsPhoneQuestHeadline = 'CLARABELLE' QuestsPhoneQuestSCString = 'I need to call Clarabelle.' QuestsPhoneQuestString = 'Call Clarabelle' QuestsFriendNewbieQuestString = 'Make %d friends %d laff or less' QuestsFriendNewbieQuestProgress = '%(progress)s of %(numFriends)s made' QuestsFriendNewbieQuestObjective = 'Make friends with %d new Toons' QuestsTrolleyQuestHeadline = 'TROLLEY' QuestsTrolleyQuestSCString = 'I need to ride the trolley.' QuestsTrolleyQuestString = 'Ride on the trolley' QuestsTrolleyQuestStringShort = 'Ride the trolley' QuestsMinigameNewbieQuestString = '%d Minigames' QuestsMinigameNewbieQuestProgress = '%(progress)s of %(numMinigames)s Played' QuestsMinigameNewbieQuestObjective = 'Play %d minigames with new Toons' QuestsMinigameNewbieQuestSCString = 'I need to play minigames with new Toons.' QuestsMinigameNewbieQuestCaption = 'Help a new Toon %d laff or less' QuestsMinigameNewbieQuestAux = 'Play:' QuestsMaxHpReward = 'Your Laff limit has been increased by %s.' QuestsMaxHpRewardPoster = 'Reward: %s point Laff boost' QuestsMoneyRewardSingular = 'You get 1 jellybean.' QuestsMoneyRewardPlural = 'You get %s Jellybeans.' QuestsMoneyRewardPosterSingular = 'Reward: 1 jellybean' QuestsMoneyRewardPosterPlural = 'Reward: %s Jellybeans' QuestsMaxMoneyRewardSingular = 'You can now carry 1 jellybean.' QuestsMaxMoneyRewardPlural = 'You can now carry %s Jellybeans.' QuestsMaxMoneyRewardPosterSingular = 'Reward: Carry 1 jellybean' QuestsMaxMoneyRewardPosterPlural = 'Reward: Carry %s Jellybeans' QuestsMaxGagCarryReward = 'You get a %(name)s. You can now carry %(num)s gags.' QuestsMaxGagCarryRewardPoster = 'Reward: %(name)s (%(num)s)' QuestsMaxQuestCarryReward = 'You can now have %s ToonTasks.' QuestsMaxQuestCarryRewardPoster = 'Reward: Carry %s ToonTasks' QuestsTeleportReward = 'You now have teleport access to %s.' QuestsTeleportRewardPoster = 'Reward: Teleport access to %s' QuestsTrackTrainingReward = 'You can now train for "%s" gags.' QuestsTrackTrainingRewardPoster = 'Reward: Gag training' QuestsTrackProgressReward = 'You now have frame %(frameNum)s of the %(trackName)s track animation.' QuestsTrackProgressRewardPoster = 'Reward: "%(trackName)s" track animation frame %(frameNum)s' QuestsTrackCompleteReward = 'You may now carry and use "%s" gags.' QuestsTrackCompleteRewardPoster = 'Reward: Final %s track training' QuestsClothingTicketReward = 'You can change your clothes' QuestsClothingTicketRewardPoster = 'Reward: Clothing Ticket' TIPQuestsClothingTicketReward = 'You can change your shirt for a TIP shirt' TIPQuestsClothingTicketRewardPoster = 'Reward: TIP Clothing Ticket' QuestsCheesyEffectRewardPoster = 'Reward: %s' QuestsCogSuitPartReward = 'You now have a %(cogTrack)s %(part)s Cog Suit Part.' QuestsCogSuitPartRewardPoster = 'Reward: %(cogTrack)s %(part)s Part' QuestsBetaKeyRewardPoster = 'Reward: Town Toon Wacky Silly 3 Beta Key' QuestsBetaKeyReward = 'You may now invite a friend to play TTR! To view this key, visit the "Account" section of the website.' QuestsStreetLocationThisPlayground = 'in this playground' QuestsStreetLocationThisStreet = 'on this street' QuestsStreetLocationNamedPlayground = 'in the %s playground' QuestsStreetLocationNamedStreet = 'on %(toStreetName)s in %(toHoodName)s' QuestsLocationString = '%(string)s%(location)s' QuestsLocationBuilding = "%s's building is called" QuestsLocationBuildingVerb = 'which is' QuestsLocationParagraph = '\x07%(building)s "%(buildingName)s"...\x07...%(buildingVerb)s %(street)s.' QuestsGenericFinishSCString = 'I need to finish a ToonTask.' QuestsMediumPouch = 'Medium Pouch' QuestsLargePouch = 'Large Pouch' QuestsSmallBag = 'Small Bag' QuestsMediumBag = 'Medium Bag' QuestsLargeBag = 'Large Bag' QuestsSmallBackpack = 'Small Backpack' QuestsMediumBackpack = 'Medium Backpack' QuestsLargeBackpack = 'Large Backpack' QuestsItemDict = {1: ['Pair of Glasses', 'Pairs of Glasses', 'a '], 2: ['Key', 'Keys', 'a '], 3: ['Blackboard', 'Blackboards', 'a '], 4: ['Book', 'Books', 'a '], 5: ['Candy Bar', 'Candy Bars', 'a '], 6: ['Piece of Chalk', 'Pieces of Chalk', 'a '], 7: ['Toon-Up Gags', 'Toon-Up Gags', 'some '], 8: ['Note', 'Notes', 'a '], 9: ['Adding machine', 'Adding machines', 'an '], 10: ['Clown car tire', 'Clown car tires', 'a '], 11: ['Air pump', 'Air pumps', 'an '], 12: ['Octopus ink', 'Octopus inks', 'some '], 13: ['Package', 'Package', 'a '], 14: ['Goldfish receipt', 'Goldfish receipts', 'a '], 15: ['Goldfish', 'Goldfish', 'a '], 16: ['Oil', 'Oils', 'some '], 17: ['Grease', 'Greases', 'some '], 18: ['Water', 'Waters', 'some '], 19: ['Gear report', 'Gear reports', 'a '], 20: ['Blackboard Eraser', 'Blackboard Erasers', 'a '], 21: ['Watercooler', 'Watercoolers', 'a '], 22: ['Bottled Can', 'Bottled Cans', 'a '], 23: ['Beret', 'Berets', 'a '], 24: ['Top Hat', 'Top Hats', 'a '], 25: ['Books', 'Books', 'some '], 26: ['Needle', 'Needles', 'a '], 27: ['Toxic Waste', 'Samples of Toxic Waste', 'some '], 28: ['Can of Tuna', 'Cans of Tuna', 'a '], 29: ['Passport', 'Passports', 'a '], 30: ['Gift', 'Gifts', 'a '], 31: ['Salt Shaker', 'Salt Shakers', 'a '], 32: ['Goods', 'Goods', 'some '], 33: ['Cabbage', 'Cabbages', 'a '], 34: ['Barrel of Jellybeans', 'Barrels of Jellybeans', 'a '], 35: ['Camera', 'Cameras', 'a '], 36: ['Paint Brush', 'Paint Brushes', 'a '], 37: ['Music Note', 'Music Notes', 'a '], 38: ['Memo From The Factory Foreman', 'Memos From The Factory Foreman', 'a '], 39: ['Glasses', 'Pairs of Glasses', 'Dr. Ivanna Cee\'s '], 40: ['Snow Globe', 'Snow Globes', 'a '], 41: ['Favorite Snow Globe', 'Favorite Snow Globes', 'Shakey\'s '], 42: ['Boarding Ticket', 'Boarding Tickets', 'a '], 43: ['Suitcase', 'Suitcases', 'a '], 44: ['Glasses', 'Pairs of Glasses', 'Dr. Friezeframe\'s '], 45: ['Bowl of Soup', 'Bowls of Soup', 'a '], 46: ['Ice Skates', 'Ice Skates', 'some '], 47: ['Broken Steering Wheel', 'Broken Steering Wheels', 'a '], 48: ['Repaired Steering Wheel', 'Repaired Steering Wheels', 'a '], 49: ['Glasses', 'Pairs of Glasses', 'Dr. Blinky\'s '], 50: ['Glasses', 'Pairs of Glasses', 'Dr. Bleary\'s '], 51: ['Bottle', 'Bottles', 'a '], 52: ['Donut', 'Donuts', 'a '], 53: ['Teleportation Access Memo', 'Teleportation Access Memos', 'a '], 54: ['Pair of Tap Dancing Shoes', 'Pairs of Tap Dancing Shoes', 'a '], 55: ['Pillows', 'Pillows', 'some '], 56: ['Watch', 'Watches', 'a '], 57: ['Record', 'Records', 'a '], 58: ['Power Generator', 'Power Generators', 'a '], 110: ['TIP Clothing Ticket', 'Clothing Tickets', 'a '], 1000: ['Clothing Ticket', 'Clothing Tickets', 'a '], 2001: ['Inner Tube', 'Inner Tubes', 'an '], 2002: ['Monocle Prescription', 'Monocle Prescriptions', 'a '], 2003: ['Eyeglass Frames', 'Eyeglass Frames', 'some '], 2004: ['Monocle', 'Monocles', 'a '], 2005: ['Big White Wig', 'Big White Wigs', 'a '], 2006: ['Bushel of Ballast', 'Bushels of Ballast', 'a '], 2007: ['Cog Gear', 'Cog Gears', 'a '], 2008: ['Sea Chart', 'Sea Charts', 'a '], 2009: ['Peanut Butter Sandwich', 'Peanut Butter Sandwich', 'a '], 2010: ['Won Ton Balls', 'Won Ton Balls', 'some '], 2011: ['Coffee Maker', 'Coffee Maker', 'a '], 2012: ['Bag of Flour', 'Bag of Flour', 'a '], 4001: ["Tina's Inventory", "Tina's Inventories", ''], 4002: ["Yuki's Inventory", "Yuki's Inventories", ''], 4003: ['Inventory Form', 'Inventory Forms', 'an '], 4004: ["Fifi's Inventory", "Fifi's Inventories", ''], 4005: ["Lumber Jack's Ticket", "Lumber Jack's Tickets", ''], 4006: ["Tabitha's Ticket", "Tabitha's Tickets", ''], 4007: ["Barry's Ticket", "Barry's Tickets", ''], 4008: ['Cloudy Castanet', 'Cloudy Castanets', ''], 4009: ['Blue Squid Ink', 'Blue Squid Ink', 'some '], 4010: ['Clear Castanet', 'Clear Castanets', 'a '], 4011: ["Leo's Lyrics", "Leo's Lyrics", ''], 5001: ['Silk necktie', 'Silk neckties', 'a '], 5002: ['Pinstripe Suit', 'Pinstripe Suits', 'a '], 5003: ['Pair of Scissors', 'Pairs of Scissors', 'a '], 5004: ['Postcard', 'Postcards', 'a '], 5005: ['Pen', 'Pens', 'a '], 5006: ['Inkwell', 'Inkwells', 'an '], 5007: ['Notepad', 'Notepads', 'a '], 5008: ['Office Lockbox', 'Office Lockboxes', 'an '], 5009: ['Bag of Bird Seed', 'Bags of Bird Seed', 'a '], 5010: ['Sprocket', 'Sprockets', 'a '], 5011: ['Salad', 'Salads', 'a '], 5012: ['Key to ' + lDaisyGardens, 'Keys to ' + lDaisyGardens, 'a '], 5013: [lSellbotHQ + ' Blueprints', lSellbotHQ + ' HQ Blueprints', 'some '], 5014: [lSellbotHQ + ' Memo', lSellbotHQ + ' Memos', 'a '], 5015: [lSellbotHQ + ' Memo', lSellbotHQ + ' Memos', 'a '], 5016: [lSellbotHQ + ' Memo', lSellbotHQ + ' Memos', 'a '], 5017: [lSellbotHQ + ' Memo', lSellbotHQ + ' Memos', 'a '], 3001: ['Soccer ball', 'Soccer balls', 'a '], 3002: ['Toboggan', 'Toboggans', 'a '], 3003: ['Ice cube', 'Ice cubes', 'an '], 3004: ['Love letter', 'Love letters', 'a '], 3005: ['Wiener dog', 'Wiener dogs', 'a '], 3006: ['Engagement ring', 'Engagement rings', 'an '], 3007: ['Sardine whiskers', 'Sardine whiskers', 'some '], 3008: ['Calming potion', 'Calming potion', 'a '], 3009: ['Broken tooth', 'Broken teeth', 'a '], 3010: ['Gold tooth', 'Gold teeth', 'a '], 3011: ['Pine cone bread', 'Pine cone breads', 'a '], 3012: ['Lumpy cheese', 'Lumpy cheeses', 'some '], 3013: ['Simple spoon', 'Simple spoons', 'a '], 3014: ['Talking toad', 'Talking toad', 'a '], 3015: ['Ice cream cone', 'Ice cream cones', 'an '], 3016: ['Wig powder', 'Wig powders', 'some '], 3017: ['Rubber ducky', 'Rubber duckies', 'a '], 3018: ['Fuzzy dice', 'Fuzzy dice', 'some '], 3019: ['Microphone', 'Microphones', 'a '], 3020: ['Electric keyboard', 'Electric keyboards', 'an '], 3021: ['Platform shoes', 'Platform shoes', 'some '], 3022: ['Caviar', 'Caviar', 'some '], 3023: ['Make-up powder', 'Make-up powders', 'some '], 3024: ['Yarn', 'Yarn', 'some '], 3025: ['Knitting Needle', 'Knitting Needles', 'a '], 3026: ['Alibi', 'Alibis', 'an '], 3027: ['External Temperature Sensor', 'External Temperature Sensors', 'an '], 6001: ['Cashbot HQ Plans', 'Cashbot HQ Plans', 'some '], 6002: ['Rod', 'Rods', 'a '], 6003: ['Drive Belt', 'Drive Belts', 'a '], 6004: ['Pair of Pincers', 'Pairs of Pincers', 'a '], 6005: ['Reading Lamp', 'Reading Lamps', 'a '], 6006: ['Zither', 'Zithers', 'a '], 6007: ['Zamboni', 'Zambonis', 'a '], 6008: ['Zebra Zabuton', 'Zebra Zabutons', 'a '], 6009: ['Zinnias', 'Zinnias', 'some '], 6010: ['Zydeco Records', 'Zydeco Records', 'some '], 6011: ['Zucchini', 'Zucchinis', 'a '], 6012: ['Zoot Suit', 'Zoot Suits', 'a '], 7001: ['Plain Bed', 'Plain Beds', 'a '], 7002: ['Fancy Bed', 'Fancy Beds', 'a '], 7003: ['Blue Bedspread', 'Blue Bedspreads', 'a '], 7004: ['Paisley Bedspread', 'Paisley Bedspreads', 'a '], 7005: ['Pillows', 'Pillows', 'some '], 7006: ['Hard Pillows', 'Hard Pillows', 'some '], 7007: ['Pajamas', 'Pajamas', 'a pair of '], 7008: ['Footie Pajamas', 'Footie Pajamas', 'a pair of '], 7009: ['Puce Footie Pajamas', 'Puce Footie Pajamas', 'a pair of '], 7010: ['Fuchsia Footie Pajamas', 'Fuchsia Footie Pajamas', 'a pair of '], 7011: ['Cauliflower Coral', 'Cauliflower Coral', 'some '], 7012: ['Slimy Kelp', 'Slimy Kelp', 'some '], 7013: ['Pestle', 'Pestles', 'a '], 7014: ['Jar of Wrinkle Cream', 'Jars of Wrinkle Cream', 'a ']} QuestsHQOfficerFillin = lHQOfficerM QuestsHQWhereFillin = '' QuestsHQBuildingNameFillin = lToonHQ QuestsHQLocationNameFillin = 'in any neighborhood' QuestsTailorFillin = 'Tailor' QuestsTailorWhereFillin = '' QuestsTailorBuildingNameFillin = 'Clothing Store' QuestsTailorLocationNameFillin = 'in any neighborhood' QuestsTailorQuestSCString = 'I need to see a Tailor.' QuestMovieQuestChoiceCancel = 'Come back later if you need a ToonTask! Bye!' QuestMovieTrackChoiceCancel = 'Come back when you are ready to decide! Bye!' QuestMovieQuestChoice = 'Choose a ToonTask.' QuestMovieTrackChoice = 'Ready to decide? Choose a track, or feel free to come back later.' GREETING = 0 QUEST = 1 INCOMPLETE = 2 INCOMPLETE_PROGRESS = 3 INCOMPLETE_WRONG_NPC = 4 COMPLETE = 5 LEAVING = 6 TheBrrrghTrackQuestDict = {GREETING: '', QUEST: 'Now you are ready.\x07Go out and walk the earth until you know which track you would like to choose.\x07Choose wisely, because this is your final track.\x07When you are certain, return to me.', INCOMPLETE_PROGRESS: 'Choose wisely.', INCOMPLETE_WRONG_NPC: 'Choose wisely.', COMPLETE: 'Very wise choice!', LEAVING: 'Good luck. Return to me when you have mastered your new skill.'} QuestDialog_3225 = {QUEST: "Oh, thanks for coming, _avName_!\x07The Cogs in the neighborhood frightened away my delivery person.\x07I don't have anyone to deliver this salad to _toNpcName_!\x07Can you do it for me? Thanks so much!_where_"} QuestDialog_2910 = {QUEST: 'Back so soon?\x07I need one more favor.\x07I need some flour.\x07Please ask _toNpcName_ if I may get some._where_'} QuestDialogDict = {160: {GREETING: '', QUEST: "Ok, now I think you are ready for something more rewarding.\x07If you can defeat 3 Bossbots I'll give you a little bonus.", INCOMPLETE_PROGRESS: TheCogs + ' are out in the streets, through the tunnels.', INCOMPLETE_WRONG_NPC: 'Good job defeating those Cogs. Now go to the Toon Headquarters for your next step!', COMPLETE: QuestsDefaultComplete, LEAVING: QuestsDefaultLeaving}, 161: {GREETING: '', QUEST: "Ok, now I think you are ready for something more rewarding.\x07Come back after you defeat 3 Lawbots and I'll have a little something for you.", INCOMPLETE_PROGRESS: TheCogs + ' are out in the streets, through the tunnels.', INCOMPLETE_WRONG_NPC: 'Good job defeating those Cogs. Now go to the Toon Headquarters for your next step!', COMPLETE: QuestsDefaultComplete, LEAVING: QuestsDefaultLeaving}, 162: {GREETING: '', QUEST: 'Ok, now I think you are ready for something more rewarding.\x07Defeat 3 Cashbots and come back here to claim the bounty.', INCOMPLETE_PROGRESS: TheCogs + ' are out in the streets, through the tunnels.', INCOMPLETE_WRONG_NPC: 'Good job defeating those Cogs. Now go to the Toon Headquarters for your next step!', COMPLETE: QuestsDefaultComplete, LEAVING: QuestsDefaultLeaving}, 163: {GREETING: '', QUEST: "Ok, now I think you are ready for something more rewarding.\x07Come see us after you defeat 3 Sellbots and we'll hook you up.", INCOMPLETE_PROGRESS: TheCogs + ' are out in the streets, through the tunnels.', INCOMPLETE_WRONG_NPC: 'Good job defeating those Cogs. Now go to the Toon Headquarters for your next step!', COMPLETE: QuestsDefaultComplete, LEAVING: QuestsDefaultLeaving}, 164: {QUEST: 'Phew, tired yet?\x07You know... You look like you could use some new gags.\x07Go see %s, maybe he can help you out._where_' % Flippy}, 165: {QUEST: 'Heya! I remember seeing you in the streets earlier.\x07I don\'t believe I formerly introduced myself...\x07I\'m Flippy, President of the Toon Council here in Toontown.\x07Hopefully we\'ll be seeing each other a lot more often!\x07It looks like you need to practice training your gags.\x07You see, every time you hit a Cog with one of your gags it increases your experience.\x07When you get enough experience, you\'ll be able to buy an even better gag.\x07Why not try it out?\x07To get some practice in, try defeating 4 of those Cogs on the streets.'}, 166: {QUEST: 'Oooh, nice work! Got a new gag yet?\x07You know, the Cogs come in five different types.\x07There are Sellbots for marketing...\x07Cashbots for accounting...\x07Lawbots for legal advice...\x07Bossbots to keep them all in line...\nAnd Marketingbots that represent them all...\x07They all wear different suits and nametags, so you\'ll be able to see the difference easily.\x07Check your Shticker Book if you need some help identifying them.\x07Here, let\'s practice. Go defeat 4 of those Bossbots I talked about!'}, 167: {QUEST: 'Oooh, nice work! Got a new gag yet?\x07You know, the Cogs come in five different types.\x07There are Sellbots for marketing...\x07Cashbots for accounting...\x07Lawbots for legal advice...\x07Bossbots to keep them all in line...\nAnd Marketingbots that represent them all...\x07They all wear different suits and nametags, so you\'ll be able to see the difference easily.\x07Check your Shticker Book if you need some help identifying them.\x07Here, let\'s practice. Go defeat 4 of those Lawbots I talked about!'}, 168: {QUEST: 'Oooh, nice work! Got a new gag yet?\x07You know, the Cogs come in five different types.\x07There are Sellbots for marketing...\x07Cashbots for accounting...\x07Lawbots for legal advice...\x07Bossbots to keep them all in lin...\nAnd Marketingbots that represent them all...e\x07They all wear different suits and nametags, so you\'ll be able to see the difference easily.\x07Check your Shticker Book if you need some help identifying them.\x07Here, let\'s practice. Go defeat 4 of those Sellbots I talked about!'}, 169: {QUEST: 'Oooh, nice work! Got a new gag yet?\x07You know, the Cogs come in five different types.\x07There are Sellbots for marketing...\x07Cashbots for accounting...\x07Lawbots for legal advice...\x07Bossbots to keep them all in line...\nAnd Marketingbots that represent them all...\x07They all wear different suits and nametags, so you\'ll be able to see the difference easily.\x07Check your Shticker Book if you need some help identifying them.\x07Here, let\'s practice. Go defeat 4 of those Cashbots I talked about!'}, 170: {QUEST: 'Oh good, you\'re back. I was getting worried that you got lost!\x07Do you understand the difference between the 5 Cogs now?\x07I think that you\'re ready to go ahead and start training for a new gag track.\x07_toNpcName_ is an expert on gags. He can give you some expert advice on your next track._where_'}, 171: {QUEST: 'Oh good, you\'re back. I was getting worried that you got lost!\x07Do you understand the difference between the 5 Cogs now?\x07I think that you\'re ready to go ahead and start training for a new gag track.\x07_toNpcName_ is an expert on gags. He can give you some expert advice on your next track._where_'}, 172: {QUEST: 'Oh good, you\'re back. I was getting worried that you got lost!\x07Do you understand the difference between the 5 Cogs now?\x07I think that you\'re ready to go ahead and start training for a new gag track.\x07_toNpcName_ is an expert on gags. She can give you some expert advice on your next track._where_'}, 400: {GREETING: '', QUEST: 'Throw and Squirt are great, but you\'re going to need more gags to fight those higher level Cogs.\x07When you team up with other Toons against the Cogs, you can combine your gags for even more giggles!\x07Try different combinations of gags to see what works best.\x07I understand it\'s a tough decision, so take your time to choose wisely.\x07You may want to ask a few friends what they think so you can plan strategies together.\x07When you are ready to decide, come back here and take your pick.', INCOMPLETE_PROGRESS: 'Back so soon? Are you ready to choose?', INCOMPLETE_WRONG_NPC: 'I heard that you\'re training for your next gag track. It\'s a tough pick!', COMPLETE: 'Ah, great decision!\x07Hang on a minute, I can\'t just GIVE you the gags. Didn\'t Flippy tell you about training?\x07Before you can buy those gags, you need to know how to use them by collecting film strips.\x07Toon HQ can give you a few ToonTasks to earn them.\x07There are 15 film strips, which form an animation to show you how to use your new gags.\x07When you collect all 15, you can get the Final Gag Training task that will allow you to use them.\x07You can check your progress in the Shticker Book.', LEAVING: 'That\'s about all I can tell you. Good luck on training!'}, 600: {QUEST: "There are many shop keepers out there who will require your help.\x07Those toons send help requests here to the Toon HQ, where we give the job to toons like you.\x07_toNpcName_ will help you get used to this habbit._where_"}, 601: {GREETING: '', QUEST: "Welcome, newcomer!\x07As you can tell, there are many citizens on the streets of Toontown who need help with simple or rough jobs.\x07Each job you complete for them, you will get a reward for it.\x07For me, I just want you to take out a couple of Cogs on this street.\x07Then, I will give you a second task carry slot.", LEAVING: '', COMPLETE: "See? It's not hard!\x07Here is your reward..."}, 1039: {QUEST: 'Visit _toNpcName_ if you want to get around town more easily._where_'}, 1040: {QUEST: 'Visit _toNpcName_ if you want to get around town more easily._where_'}, 1041: {QUEST: 'Hi! What brings you here?\x07Everybody uses their portable hole to travel around Toontown.\x07Why, you can teleport to your friends using the Friends List, or to any neighborhood using the map in the Shticker Book.\x07Of course, you have to earn that!\x07Say, I can turn on your teleport access to ' + lToontownCentral + ' if you help out a friend of mine.\x07Seems the Cogs are causing trouble. Go visit _toNpcName_._where_'}, 1042: {QUEST: 'Hi! What brings you here?\x07Everybody uses their portable hole to travel around Toontown.\x07Why, you can teleport to your friends using the Friends List, or to any neighborhood using the map in the Shticker Book.\x07Of course, you have to earn that!\x07Say, I can turn on your teleport access to ' + lToontownCentral + ' if you help out a friend of mine.\x07Seems the Cogs are causing trouble. Go visit _toNpcName_._where_'}, 1043: {QUEST: 'Hi! What brings you here?\x07Everybody uses their portable hole to travel around Toontown.\x07Why, you can teleport to your friends using the Friends List, or to any neighborhood using the map in the Shticker Book.\x07Of course, you have to earn that!\x07Say, I can turn on your teleport access to ' + lToontownCentral + ' if you help out a friend of mine.\x07Seems the Cogs are causing trouble. Go visit _toNpcName_._where_'}, 1044: {QUEST: 'Oh, thanks for stopping by. I really need some help.\x07A bunch of Cashbots keep breaking in and stealing all my toonup gags!\x07Whenever toons call me for help, I am never able to help them out now.\x07Can you do me a favor and recover some for me?', LEAVING: '', INCOMPLETE_PROGRESS: 'Any luck finding my recipes?'}, 1045: {QUEST: 'Thank you so much!\x07It won\'t be much longer before they come back in...\x07Oh, I have an idea!\x07Please deliver this note to Flippy. It\'s asking him for better protection.\x07I also asked him if he could give you your teleportation access while at it.', LEAVING: '', COMPLETE: 'Ah, yes. Look like your friend here needs some extra protection...\x07Says you need teleport access to ' + lToontownCentral + ' as well.\x07Well, consider it done.\x07Now you can teleport back to the playground from almost anywhere in Toontown.\x07Just open your map and click on ' + lToontownCentral + '.'}, 1046: {QUEST: '_toNpcName_ is having a shortage of water._where_'}, 1047: {QUEST: 'As you know, my store has an odd shortage of water.\x07I have a shipping of Bottled Cans that must be sent out with some fresh water.\x07I know!\x07Some Bottom Feeders carry around fresh Watercoolers with them to attack toons. If you could recover 7 of those, that\'d be great!', LEAVING: '', INCOMPLETE_PROGRESS: 'Still looking for adding machines?'}, 1048: {QUEST: 'As you know, my store has an odd shortage of water.\x07I have a shipping of Bottled Cans that must be sent out with some fresh water.\x07I know!\x07Some Short Changes carry around fresh Watercoolers with them to attack toons. If you could recover 7 of those, that\'d be great!', LEAVING: '', INCOMPLETE_PROGRESS: 'Still looking for adding machines?'}, 1049: {QUEST: "Good job collecting those Watercoolers!\x07Now you're going to think I'm crazy, but I was about to deliver these Bottled Cans until I realized there are none.\x07Plenty of Fishing Docks have littered Bottled Cans! I need just about 4.", LEAVING: '', INCOMPLETE_PROGRESS: 'Remember, I need 10 gears to fix the machines.'}, 1053: {QUEST: "Thank you for the Bottled Cans.\x07Now, as one final request, I would like 5 Glasses of Water for myself, mainly since I can't drink the water that needs to be delivered...", LEAVING: '', COMPLETE: "Whew! I thought for a second that I was going to parch!\x07Here is your reward..."}, 1054: {QUEST: 'We here at the Toon HQ are researching the new cog department, Marketingbots.\x07Our first target is the Penis Muncher.\x07We suspect that their berets contain many secrets.\x07Please recover a Beret from the Penis Munchers and report back to any HQ Officer.'}, 1055: {QUEST: "Now we'll need to look into the Top Hats owned by the Door to Door Salesmen.\x07Please recover one of those as well.", GREETING: 'Excellent work!', LEAVING: 'Cheerio!', INCOMPLETE_PROGRESS: 'Havin\' trouble fishing them out? Like I said, check that pond in " + lToontownCentral'}, 1056: {QUEST: 'Finally, we wish to look into the DNA of a Camera Head.\x07We\'ll need at least one Cog Gear from them in order to do that.', LEAVING: '', COMPLETE: 'Thanks for all your help.\x07We will definetally be able to learn more about the Marketingbots because of your help.\x07Here is your reward.'}, 1057: {QUEST: "Hi there. What can I do for you?\x07A tire pump you say? Huh.\x07I'll tell you what - clear out the street of some of those high-level Cogs...\x07And I'll let you have the pump.", LEAVING: '', INCOMPLETE_PROGRESS: 'Is that the best you can do?'}, 1058: {QUEST: "Ahh!\x07I was going to return my books when suddenly, a bunch of Flunkies came in here and took all my books!\x07I would go get them myself, but I'm stuck in glue, as usual.\x07If you could recover them and return them for me, that'd be great!", LEAVING: '', GREETING: '', COMPLETE: "Brilliant! Thanks for all your help!\x07Here is your reward."}, 1059: {QUEST: '_toNpcName_ has some customers with overdue books._where_'}, 1060: {QUEST: "I have a couple customers that have overdue books.\x07However, these customers are always on time when turning in their books which worries me a little bit.\x07I want you to check on _toNpcName_ first._where_", LEAVING: '', INCOMPLETE_PROGRESS: 'Are you having trouble fishing?'}, 1061: {QUEST: "Books?\x07Oh right, that completely slipped my mind.\x07Please return these to _toNpcName_.", LEAVING: 'Thanks!', INCOMPLETE_PROGRESS: 'I just saw some more Pencil Pushers.'}, 1062: {QUEST: "He simply forgot?\x07Haha, that's a first.\x07Next, I need you to go get some books from _toNpcName_._where_", LEAVING: '', INCOMPLETE_PROGRESS: 'I just saw some more Bloodsuckers.'}, 900: {QUEST: 'Now that you have all your tracks, it is time for your new gag.\x07Flippy has one final test to see if you are worthy of receiving them._where_'}, 1063: {QUEST: 'By now, you should have seen cogs of all departments: Bossbots, Lawbots, Cashbots, Sellbots, and Marketingbots.\x07I want you to start off by defeating 3 Bossbots.', LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding the package, huh?'}, 1067: {QUEST: "Up next, I need you to defeat 3 Lawbots.", GREETING: '', LEAVING: ''}, 1068: {QUEST: "Now, Cashbots.", LEAVING: '', GREETING: '', INCOMPLETE_PROGRESS: "My assistant isn't back yet."}, 1069: {QUEST: "You should've already guessed that Sellbots are up next.", LEAVING: '', GREETING: '', INCOMPLETE_PROGRESS: 'No luck finding the package, huh?'}, 1071: {QUEST: "Just some Marketingbots and you're all done!", LEAVING: '', COMPLETE: "You have proven to me that you can tell the difference between each cog department, just like when I first trained you.\x07You are ready to move on!", INCOMPLETE_PROGRESS: 'No luck finding the package, huh?'}, 1070: {QUEST: "Dr. Euphoric says he wasn't expecting a package either.\x07Unfortunately, a Bossbot stole it from my assistant on the way back.\x07Could you try and get it back?", LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding the package, huh?'}, 1072: {QUEST: 'Great - you got it back!\x07Maybe you should try _toNpcName_, it could be for him._where_', LEAVING: ''}, 1073: {QUEST: 'Oh, thanks for bringing me my packages.\x07Wait a second, I was expecting two. Could you check with _toNpcName_ and see if he has the other one?', INCOMPLETE: 'Were you able to find my other package?', LEAVING: ''}, 1074: {QUEST: 'He said there was another package? Maybe the Cogs stole it too.\x07Defeat Cogs until you find the second package.', LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding the other package, huh?'}, 1075: {QUEST: 'I guess there was a second package after all!\x07Hurry and take it over to _toNpcName_ with my apologies.', COMPLETE: 'Hey, my package is here!\x07Since you seem to be such a helpful Toon, this should come in handy.', LEAVING: ''}, 1076: {QUEST: "Professor Pete is conducting some research and needs some Cog Gears._where_"}, 1077: {QUEST: "I am conducting research on the strongest cogs that roam in Toontown Central.\x07I need you to recover several gears from certain cogs.\x07Start off with a Micromanager.", LEAVING: '', GREETING: '', INCOMPLETE_PROGRESS: 'Please return my goldfish to me.'}, 1078: {QUEST: "Now I need one from a Ambulance Chaser.", INCOMPLETE: 'What did _toNpcName_ have to say about the receipt?', GREETING: '', LEAVING: ''}, 1079: {QUEST: "Bean ready for this? Now I'll need one from a Bean Counter!", LEAVING: 'This is why I don\'t make puns...', GREETING: '', INCOMPLETE_PROGRESS: "I don't think there's anything else I can help you with.\x07Why don't you try and find that goldfish?"}, 1092: {QUEST: "I'm glad you are handling this task.", LEAVING: 'Now I\'m starting to sound like one of them...', GREETING: '', INCOMPLETE_PROGRESS: "I don't think there's anything else I can help you with.\x07Why don't you try and find that goldfish?"}, 1080: {QUEST: "One more left!\x07Just need one gear from an Assfucker.", LEAVING: '', GREETING: '', COMPLETE: 'Thanks for all your help.', INCOMPLETE_PROGRESS: 'Are you having trouble finding my fish? Oscar says they didn\'t swim too far.'}, 1081: {QUEST: 'Banker Bob keeps getting robbed.\x07_where_'}, 1082: {QUEST: "Pesky, pesky Cashbots!\x07It's always them!\x07I want some revenge!\x07Please defeat 10 Cashbot. It'll make them pay for what they have done.", LEAVING: '', GREETING: '', COMPLETE: 'Vengence is sweet!', INCOMPLETE_PROGRESS: 'Have you found the oil? I\'m beginning to boil!'}, 1083: {QUEST: "The oil helped a little, but I still cannot budge.\x07What else would help? It's too hard to judge.\x07That gives me an idea; it's worth a try at least...\x07Defeat those Lawbots and bring back some grease.", LEAVING: '', GREETING: '', INCOMPLETE_PROGRESS: 'Have you got any grease? I need to pay the lease!'}, 1084: {QUEST: "Nope, that didn't help. This is really not funny.\x07I put the grease right there on the money!\x07That gives me an idea! Now before I forget it...\x07Defeat some Cashbots; bring back water to wet it.", LEAVING: '', GREETING: '', COMPLETE: "Hooray! I'm free of this quick drying glue.\x07As a reward, I have a gift for you.\x07You can laugh a little longer while battling, and then...\x07Yipes! I'm already stuck here again!", INCOMPLETE_PROGRESS: 'Hurry, there really is no more time! I can\'t even think of another rhyme.'}, 1085: {QUEST: '_toNpcName_ is not ready to give patients their flu shots._where_'}, 1086: {QUEST: "I'm expecting a lot of patients next week for their flu shots, but a bunch of Lawbots took all my needles.\x07Please recover them for me, or my patients will have to deal without the shot!", LEAVING: '', GREETING: '', COMPLETE: 'Oh, thank you so much!\x07Here is your reward.', INCOMPLETE_PROGRESS: "Ah, yes. My research is going swimmingly. Have you found enough Gears yet?"}, 1089: {QUEST: "Ah ha! Let's take a look...\x07These are excellent specimens.\x07Mmmm...\x07Here's my report - No peeking!\x07Take this back to Toon Headquarters right away.", INCOMPLETE: 'You better not have looked at my report. Top secret, you know! Sort of.', COMPLETE: "He\'s done already?\x07Good work _avName_, we'll take this one from here.", LEAVING: ''}, 1090: {QUEST: 'Hey, _toNpcName_ has been looking for you.\x07They\'ve heard of your excellent Gag work around town and want to give you a bit of useful information._where_'}, 1091: {QUEST: 'Oh, hello! I bet you\'re here for the information Toon HQ told you about.\x07You see, I hear that Loony Labs is working on a sort of Cog Radar.\x07It will let you see if certain Cogs are on the street to keep better track of them.\x07That Cog Gallery in your Shticker Book is the key.\x07By defeating enough of them, you can tune into their signals and actually track where they are.\x07Based on what I\'ve heard about you, I bet it will be a huge help!\x07In the meantime, can you defeat a few of the bigger Cogs on the streets for me? It will certainly help with your radar.', COMPLETE: 'The Cog Radar, eh?\x07It\'s experimental, but definitely useful.\x07Here, you could probably use this...', LEAVING: QuestsDefaultLeaving}, 1300: {QUEST: 'You\'re ready to move on.\x07Visit _toNpcName_ and she\'ll get you started on your next gag track._where_'}, 1301: {QUEST: "You just got your first new gag track?\x07Congrats!\x07However, Donald's Dock is not as easy as Toontown Central.\x07Aside from that, I want you to know your way around this place.\x07On this street, Barnacle Boulevard, Bossbots are highly common. Go defeat 6 of them and return back to me once you've done that.", LEAVING: '', GREETING: ''}, 1302: {QUEST: "On Seaweed Street, you will find plenty of Cashbots and a small amount of Sellbots.\x07I would like you to defeat 7 Cashbots on Seaweed Street.", LEAVING: '', GREETING: ''}, 1303: {QUEST: "On Lighthouse Lane, Marketingbots and Lawbots are highly common.\x07Go defeat 8 Marketingbots on that street.", LEAVING: '', GREETING: ''}, 1304: {QUEST: "On Lighthouse Lane, Marketingbots and Lawbots are highly common.\x07Go defeat 8 Lawbots on that street.", LEAVING: '', GREETING: ''}, 1305: {QUEST: "Now that you know your way around this neighborhood, it's time I give you a new challenge.\x07You've seen the gray buildings on the streets?\x07Those are Cog Buildings.\x07They are really dangerous and they should not be attempted on your own.\x07Try to gather up some friends and take down a 2+ story one here in Donald's Dock.", LEAVING: '', GREETING: ''}, 1306: {QUEST: "By now, you should have level 4 throw and squirt, Whole Fruit Pie and Seltzer Bottle.\x07If you do not, I will not penalize you for that. However, those gags are very useful against the high level cogs here.\x07Anyways, I would like you to deliver a Squirt Gun as proof that you have done 'some' training.\x07Then, you may decide your next track.", LEAVING: '', GREETING: ''}, 1307: {QUEST: "By now, you should have level 4 throw and squirt, Whole Fruit Pie and Seltzer Bottle.\x07If you do not, I will not penalize you for that. However, those gags are very useful against the high level cogs here.\x07Anyways, I would like you to deliver a Cream Pie Slice as proof that you have done 'some' training.\x07Then, you may decide your next track.", LEAVING: '', GREETING: ''}, 401: {GREETING: '', QUEST: 'Now you get to choose the next gag track you want to learn.\x07Take your time deciding, and come back here when you are ready to choose.', INCOMPLETE_PROGRESS: 'Think about your decision before choosing.', INCOMPLETE_WRONG_NPC: 'Think about your decision before choosing.', COMPLETE: 'A wise decision...', LEAVING: QuestsDefaultLeaving}, 2216: {QUEST: '_toNpcName_ has a huge anger problem._where_'}, 2217: {QUEST: "I CAN'T STAND THOSE MARKETINGBOTS ANYMORE! THEY MAKE ME SO ANGRY!\x07PLEASE GO OUT AND DEFEAT 15 OF THEM! MAYBE IT'LL CALM ME DOWN!", LEAVING: "!!!!!", GREETING: "AHHH!", COMPLETE: "LESS MARKETINGBOTS MAKES ME LESS ANGRY.\x07TAKE YOUR REWARD AND GET OUT!"}, 2218: {QUEST: "_toNpcName_ requires some assistance._where_"}, 2219: {QUEST: "A bunch of Cogs broke in and tossed some of my cans of tuna into the nearest pond.\x07Can you please go find them? They were my only ones!", LEAVING: ''}, 2220: {QUEST: "Good job on getting those cans of tuna!\x07Now, can you defeat some of the high leveled cogs around here? They scare off my customers.", LEAVING: 'Good Luck!', COMPLETE: "Thank you."}, 2221: {QUEST: "We really don't know what's up with _toNpcName_._where_"}, 2222: {QUEST: "I'll tell you what's up!\x07I can't stand Downsizers!\x07Always busting in, downsizing me, making me pocket sized. I'm sick of them!\x07Go defeat 5 of them.", LEAVING: '', GREETING: 'What\'s Up, Dock?'}, 2223: {QUEST: "You know what else I don't like?\x07Backstabbers!\x07Always coming in, making a deal with me, then declining halfway through. I'm sick of them!\x07Go defeat 5 of them.", LEAVING: '', GREETING: 'What\'s Up, Dock?', COMPLETE: "Thanks for taking care of my issues."}, 2224: {QUEST: "_toNpcName_ is having some trouble crossing the overseas.\x07Can you go help him?_where_"}, 2225: {QUEST: "Thanks for stopping by. I need your help.\x07The Short Changes here won't let me leave my shop, ever.\x07Could you rid this street of some of them?"}, 2226: {QUEST: "Awesome! Less Short Changes means I can go traveling again!\x07Wait a second, my passport is missing.\x07Yikes! One of the Cashbots that took over my building must've taken it!\x07Can you go recover it? The cog should be on this street.", COMPLETE: "Great! I'll plan my next trip soon!\x07Here is your reward."}, 2227: {QUEST: "Halfway done!\x07_toNpcName_ is your checkpoint to getting your next Gag Track._where_"}, 2228: {QUEST: "You've almost got your new gags.\x07However, if you can't take down a couple big Cog Buildings, you shouldn't bother to continue.\x07The best way to take down a building is to go with other toons.", COMPLETE: "You've proven me wrong."}, 2229: {QUEST: "_toNpcName_'s customers have had many complaints about the store having none of their glasses._where_"}, 2230: {QUEST: "Oh, this is bad.\x07Moments ago, a bunch of Flunkies stole several Eyeglass Frames.\x07They should still be on this street!"}, 2231: {QUEST: "Good job recovering those frames.\x07I think you can handle this next job.\x07Awhile back, several Door to Door Salesmen stole my Monocles that the fancy toons like to buy.\x07I don't know what street they may be, but I'm sure they're here in Donald's Dock.", COMPLETE: "Thanks for your cooperation."}, 2232: {QUEST: "The seventh inning stretch!\x07You're nearly done. Just visit _toNpcName_ for a close-finishing checkpoint._where_"}, 2233: {QUEST: "In order to be eligable for a new gag track, you must be able to defeat high leveled cogs.\x07However, I will only make you defeat, at a minimum, level 5 cogs.\x07Go out and defeat 10 of them.", COMPLETE: "Good job."}, 2201: {QUEST: 'Just starting Gag Training?\x07_toNpcName_ is where you get your first track._where_'}, 2202: {QUEST: "Yes, that's correct. I hand out the first track for your gag training.\x07Normally, the Toon HQs hand out the gag frame tasks, but some shopkeepers, like myself, have been given authority to hand out these kinds of tasks.\x07Anyways, could you possibly reduce the Cashbot population on this street?", LEAVING: 'Cheers!', INCOMPLETE_PROGRESS: 'Any luck finding my inner tube?', COMPLETE: 'Awesome! Here you go.'}, 2203: {QUEST: "Hmm.\x07_toNpcName_ has been acting suspicious._where_"}, 2204: {QUEST: "Eurekra!\x07I've finally completed my research on a battery that can never die!\x07Hey, could you do me a huge favor while you're here?\x07For my battery to work, I'll need a couple samples of Toxic Waste from the Viral Marketers.", GREETING: '', LEAVING: ''}, 2205: {QUEST: "Thanks for recovering that acid.\x07My sister, _toNpcName_ has also been working on this with me.\x07Could you take the waste to her place?_where_", LEAVING: '', INCOMPLETE_PROGRESS: 'Deliver the Toxic Waste to _toNpcName_!'}, 2206: {QUEST: 'Hey, thanks for that toxic waste.\x07However, this is a top secret project we\'re working on.\x07The Assfuckers around here will find it suspicious that the toons are taking some toxic waste.\x07Please defeat a few before the word gets out!', GREETING: '', LEAVING: '', COMPLETE: "Awesome!\x07Thanks to you, we're nearly done with the battery.\x07Here's your reward."}, 2207: {QUEST: "_toNpcName_ has some gifts to send out, but has been robbed._where_"}, 2208: {QUEST: "All year round, once a week, a group of Sellbots storm my shop and steal my gifts that I need to send out.\x07Can you go recover 10 of them? I need to send them out pronto!", LEAVING: '', GREETING: '', INCOMPLETE_PROGRESS: "Still haven't found him?\x07He's tall and has a pointy head", COMPLETE: "You found them!?!?\x07Awesome!\x07You've more than earned this..."}, 2209: {QUEST: 'Porter Hole thinks you\'re good enough for teleportation access to Donald\'s Dock._where_'}, 2210: {QUEST: "Ah, so you need teleportation access?\x07First, you gotta provide me with some assistance.\x07I want you to reduce the number of Marketingbots on this street as my first request.", GREETING: 'Howdy, _avName_', LEAVING: ''}, 2211: {QUEST: "Now, some Lawbots...", INCOMPLETE_PROGRESS: 'No, silly! I said FIVE micromanagers...', GREETING: '', LEAVING: ''}, 2212: {QUEST: "Next, I need some of _toNpcName_'s world famous salt._where_", GREETING: '', LEAVING: ''}, 2213: {QUEST: "Some salt?\x07Sure, but first, I need you to defeat some high leveled cogs on this street. I just can't stand them!", GREETING: '', LEAVING: ''}, 2214: {QUEST: "You know, it's kind of funny.\x07A high leveled cog stole my last salt shaker while you were away...", INCOMPLETE_PROGRESS: "", GREETING: '', LEAVING: ''}, 2215: {QUEST: "Good job! Now go return it to Porter!", GREETING: '', LEAVING: '', COMPLETE: "Well, a promise is a promise."}, 901: {QUEST: "_toNpcName_ wants to get her restaurant started._where_"}, 2902: {QUEST: "Arrrrgh!\x07I'm hosting a dinner event next week for all customers and I don't have anything to offer.\x07I wonder if _toNpcName_ can make some sandwiches for me?_where_"}, 2903: {QUEST: "Some peanut butter sandwiches?\x07I stopped making sandwiches ever since a powerful cog took my best sandwich.\x07If you can get it, you can keep it.\x07If you do find it, tell Dinah to let me know if she wants me to make more.", LEAVING: 'Good Luck!'}, 2904: {QUEST: 'So he said if I liked the sandwich, he\'d make me more?\x07Nom Nom Nom.\x07This tastes splendid! I\'ll ask him to make me more on my own time.\x07Next, I need to ask _toNpcName_ if I can get some of his world famous Won Ton Balls!_where_'}, 2905: {QUEST: "You want some won ton balls?\x07I hate to inform you, but a Backstabber that ran off to Lighthouse Lane took a fresh batch I just made..."}, 2906: {QUEST: "Guests like coffee, right?\x07That's what I need next.\x07Please go ask _toNpcName_ if I can borrow his Coffee Maker._where_"}, 2907: {QUEST: "Dinah needs my Coffee Maker?\x07You'll have to do me a favor first.\x07There's one thing I hate down on this street: High Leveled Cogs.\x07Go defeat some, then come back.", LEAVING: 'Bon Voyage!'}, 2911: {QUEST: "Flour?\x07A Camera Head seemed to have taken all my flour the other day...", INCOMPLETE_PROGRESS: 'I still think you need to make the streets safer.'}, 2916: {QUEST: 'Flour?\x07A Number Cruncher seemed to have taken all my flour the other day...', INCOMPLETE_PROGRESS: 'Not yet. Defeat some more Sellbots.'}, 2921: {QUEST: "Flour?\x07A Downsizer seemed to have taken all my flour the other day...", INCOMPLETE_PROGRESS: "I don't think its safe yet..."}, 2925: {QUEST: "Perfect! Tell Dinah to return this once she's done with it._where_"}, 2926: {QUEST: "Thanks so much! You are doing amazing!\x07May I just ask one more favor?\x07I don't want the guests to be intimidated by Cog Buildings around here.\x07Please defeat a few 2+ Story Buildings for me.\x07I will give you your reward afterwards.", INCOMPLETE_PROGRESS: 'Still no power. How about that building?', COMPLETE: 'Well, I guess a deal is a deal.'}, 3200: {QUEST: "_toNpcName_ has some SHARP business._where_"}, 3203: {QUEST: 'Oh, thanks for coming!\x07I need someone to take this new silk tie to _toNpcName_.\x07Would you be able to do that for me?_where_'}, 3201: {QUEST: 'My store is called PETAL PUSHER Bicycles!\x07The Pencil Pushers seem to confuse that with their own name.\x07Can you defeat some Pencil Pushers here in Daisy\'s Garden? That may stop them from taking over my store.', LEAVING: '', INCOMPLETE_PROGRESS: "Have you found my suit yet? I'm sure the Cogs took it!", COMPLETE: 'Thank you.\x07Here is your reward...'}, 3204: {QUEST: "_toNpcName_ can't keep ahold of her cabbage._where_"}, 3205: {QUEST: "A Name Dropper just stole my cabbage!\x07Please go get it for me!", LEAVING: '', INCOMPLETE_PROGRESS: 'Are you still looking for my scissors?', COMPLETE: 'My cabbage! Thank you so much! Here is your reward...'}, 3206: {QUEST: 'It sounds like _toNpcName_ is having problems with some Cogs._where_'}, 3207: {QUEST: 'Toons love this place to sell and buy used goods, but the Cogs always steal these used goods.\x07If you could recover some for me, that\'d be fantastic.', INCOMPLETE_PROGRESS: "That's not enough postcards! Keep looking!", COMPLETE: 'Now people\'s goods won\'t go to waste!\x07Thanks for you help.\x07Here is your reward...'}, 3208: {QUEST: "We've been getting complaints from the residents lately about all of the Cold Callers.\x07See if you can defeat 10 Cold Callers to help out your fellow Toons in " + lDaisyGardens + '.'}, 3209: {QUEST: 'Thanks for taking care of those Cold Callers!\x07But now the Telemarketers have gotten out of hand.\x07Defeat 10 Telemarketers in ' + lDaisyGardens + ' and come back here for your reward.'}, 3247: {QUEST: "We've been getting complaints from the residents lately about all of the Bloodsuckers.\x07See if you can defeat 20 Bloodsuckers to help out your fellow Toons in " + lDaisyGardens + '.'}, 3210: {QUEST: 'Oh no, The Squirting Flower on Maple Street just ran out of flowers!\x07Take them ten of your own squirting flowers to help out.\x07Make sure you have 10 squirting flowers in your inventory first.', LEAVING: '', INCOMPLETE_PROGRESS: "I need to have 10 squirting flowers. You don't have enough!"}, 3211: {QUEST: "Oh, thank you so much! Those squirting flowers will save the day.\x07But I'm scared of the Cogs outside.\x07Can you help me out and defeat some of those Cogs?\x07Come back to me after you have defeated 20 Cogs on this street.", INCOMPLETE_PROGRESS: 'There are still Cogs out there to defeat! Keep it up!', COMPLETE: 'Oh, thank you! That helps a lot. Your reward is...'}, 3212: {QUEST: '_toNpcName_ needs some help looking for something she lost.\x07Go visit her and see what you can do._where_'}, 3213: {QUEST: 'Hi, _avName_. Can you help me?\x07I seem to have misplaced my pen. I think maybe some Cogs took it.\x07Defeat Cogs to find my stolen pen.', INCOMPLETE_PROGRESS: 'Have you found my pen yet?'}, 3214: {QUEST: "Yes, that's my pen! Thanks so much!\x07But while you were gone I realized my inkwell was missing too.\x07Defeat Cogs to find my inkwell.", INCOMPLETE_PROGRESS: "I'm still looking for my inkwell!"}, 3215: {QUEST: "Great! Now I have my pen and my inkwell back!\x07But wouldn't you know it?\x07My notepad is gone! They must have stolen it too!\x07Defeat Cogs to find my stolen notepad, and then bring it back for your reward.", INCOMPLETE_PROGRESS: 'Any word on that notepad yet?'}, 3216: {QUEST: "That's my notepad! Hooray! Your reward is...\x07Hey! Where did it go?\x07I had your reward right here in my office lockbox. But the whole lockbox is gone!\x07Can you believe it? Those Cogs stole your reward!\x07Defeat Cogs to recover my lockbox.\x07When you bring it back to me I'll give you your reward.", INCOMPLETE_PROGRESS: 'Keep looking for that lockbox! It has your reward inside it!', COMPLETE: 'Finally! I had your new gag bag in that lockbox. Here it is...'}, 3217: {QUEST: "We've been performing some studies on Sellbot mechanics.\x07We still need to study some pieces more closely.\x07Bring us a sprocket from a Name Dropper.\x07You can catch one when the Cog is exploding."}, 3218: {QUEST: 'Good job! Now we need a sprocket from a Glad Hander for comparison.\x07These sprockets are harder to catch, so keep trying.'}, 3219: {QUEST: 'Great! Now we need just one more sprocket.\x07This time, we need a sprocket from a Mover & Shaker.\x07You might need to look inside some Sellbot buildings to find these Cogs.\x07When you catch one, bring it back for your reward.'}, 3244: {QUEST: "We've been performing some studies on Lawbot mechanics.\x07We still need to study some pieces more closely.\x07Bring us a sprocket from an Ambulance Chaser.\x07You can catch one when the Cog is exploding."}, 3245: {QUEST: 'Good job! Now we need a sprocket from a Back Stabber for comparison.\x07These sprockets are harder to catch, so keep trying.'}, 3246: {QUEST: 'Great! Now we need just one more sprocket.\x07This time, we need a sprocket from a Spin Doctor.\x07When you catch one, bring it back for your reward.'}, 3220: {QUEST: "I just heard that _toNpcName_ was asking around for you.\x07Why don't you drop by and see what she wants?_where_"}, 3221: {QUEST: 'Hi, _avName_! There you are!\x07I heard you were quite an expert in squirt attacks.\x07I need someone to set a good example for all the Toons in ' + lDaisyGardens + '.\x07Use your squirt attacks to defeat a bunch of Cogs.\x07Encourage your friends to use squirt too.\x07When you have defeated 20 Cogs, come back here for a reward!'}, 3222: {QUEST: "_toNpcName_ is trying to help Donald Frump with his campaign._where_"}, 3223: {QUEST: 'Hello, fellow toon.\x07I am trying to raise some beans and gain some support for Donald Frump.\x07Donald Frump is a mouse who spends his time on Polar Place, The Brrrgh.\x07I\'d love to contribute some jellybeans, but I\'m broke.\x07Maybe you could get some barrels of beans in the ponds where the rich trash their leftover beans?'}, 3224: {QUEST: 'Thank you so much.\x07Donald Frump wants his fellow toon\'s buildings protected.\x07Why don\'t you take down a couple of buildings? Maybe that\'d earn some support for him.\x07After that, I will give you your reward.', COMPLETE: 'You seem to care for your fellow toons. Maybe you should run for President of Toontown?\x07Here is your reward...', GREETING: ''}, 3225: {QUEST: "_toNpcName_ says she needs some help.\x07Why don't you go see what you can do to help out?_where_"}, 3235: {QUEST: "Oh, this is the salad I ordered!\x07Thank you for bringing it to me.\x07All those Cogs must have frightened away _toNpcName_'s regular delivery person again.\x07Why don't you do us a favor and defeat some of the Cogs out there?\x07Defeat 10 Cogs in " + lDaisyGardens + ' and then report back to _toNpcName_.', INCOMPLETE_PROGRESS: "You're working on defeating Cogs for me?\x07That's wonderful! Keep up the good work!", COMPLETE: 'Oh, thank you so much for defeating those Cogs!\x07Now maybe I can keep my regular delivery schedule.\x07Your reward is...', INCOMPLETE_WRONG_NPC: "Go tell _toNpcName_ about the Cogs you've defeated._where_"}, 3236: {QUEST: 'There are far too many Lawbots out there.\x07You can do your part to help!\x07Defeat 3 Lawbot buildings.'}, 3237: {QUEST: 'Great job on those Lawbot buildings!\x07But now there are too many Sellbots!\x07Defeat 3 Sellbot buildings, then come back for your reward.'}, 3238: {QUEST: '_toNpcName_ and a bunch of Penis Munchers are at war._where_'}, 3239: {QUEST: "Oh, a customer, no?\x07Ahh, you have heard of the war going between the Penis Munchers and I!\x07Those Penis Munchers stole un beret of mine, and I cannot find it!\x07S'il vous plait, you must find it!", LEAVING: 'Au Revoir'}, 3240: {QUEST: "Oui, that iz' it!\x07Now, I need you to get all ze brushes they have stolen upon from me.", LEAVING: 'Au Revoir.', COMPLETE: "Fantastic!\x07You, sire, are ze best assistant un artist can ask for.\x07'Ere iz' your reward..."}, 3243: {QUEST: "You found a key all right, but it isn't the right one!\x07We need the Key to " + lDaisyGardens + '.\x07Keep looking! A Legal Eagle Cog still has it!'}, 3242: {QUEST: "I've just heard from _toNpcName_ that a Legal Eagle stole a bag of his bird seed.\x07Defeat Legal Eagles until you recover Bud's bird seed, and take it to him.\x07Legal Eagles are only found inside Lawbot buildings._where_", COMPLETE: 'Oh, thank you so much for finding my bird seed!\x07Your reward is...', INCOMPLETE_WRONG_NPC: 'Good job getting that bird seed back!\x07Now take it to _toNpcName_._where_'}, 3241: {QUEST: 'Some of the Cog buildings out there are getting too tall for our comfort.\x07See if you can bring down some of the tallest buildings.\x07Rescue 5 3-story buildings or taller and come back for your reward.'}, 3250: {QUEST: '_toNpcName_ has suspicion of a BIIIIIG scoop and needs your help investigating._where_'}, 3251: {GREETING: 'Heya, what\'s the scoop, buddy?', QUEST: "There's a big scoop out there! I just know it!\x07Rumor has it that _toNpcName_'s furniture ACTUALLY contains poison and that's why some toons end up in the hospital.\x07Why don't you go find out more?_where_", LEAVING: "Good luck, buddy!"}, 3252: {QUEST: "Poison furniture?\x07I refuse to say anything!\x07Maybe I'll talk if you defeat some of those pesky Back Stabbers on this street...", LEAVING: ''}, 3253: {QUEST: "No, I still won't speak!\x07I want you to take down a few Lawbot Buildings around here, then perhaps I'll speak.", LEAVING: ''}, 3254: {QUEST: "Alright I'll speak!\x07Yes, some of my furniture contains real poison, but that's what brings out the 'Shine' in them!\x07I did try to stop the people who ship my furniture from putting poison in it, but they just wouldn't listen...", LEAVING: '', COMPLETE: "Heya, what's the scoop, buddy?\x07Mhm, wowza!\x07THIS HAS GOT TO BE THE BEST SCOOP I'VE EVER HEARD!\x07Thank you so much, buddy! Maybe you should work for me? You can really get a good scoop on things!"}, 3256: {QUEST: '_toNpcName_ is investigating Sellbot Headquarters.\x07Go see if you can help._where_'}, 3257: {QUEST: '_toNpcName_ wants you to have more knowledge about the corporate ladder._where_'}, 3258: {QUEST: 'Ya seen them level 6 cogs?\x07Them Two-Faces start off at that level.\x07Other than Two-Faces, there are other cogs that start at level 6 and go as high up as level 10! Wowza!\x07There are cogs higher up than these, even more dangerous, but they tend to spend thems\' time in all them facilities.\x07Anyways, how\'s \'bout ya get some of \'em Two-Faces in this \'ere playground?', GREETING: 'Yahooooo!', LEAVING: '\'Cya!'}, 3259: {QUEST: 'Another cog of this rank around \'ere is them Head Hunters.\x07How\'s about ya defeat a small portion of \'em?', GREETING: 'Yahooooo!', LEAVING: '\'Cya!'}, 3260: {QUEST: 'Next, ya need to defeat some of \'em Spin Doctors.', GREETING: 'Yahooooo!', LEAVING: '\'Cya!'}, 3261: {QUEST: "Finally, I want ya to defeat some of 'em Money Bags.\x07Don't go lookin' for too many though! They're pretty uncommon around 'ere.", GREETING: 'Yahooooo!', LEAVING: '\'Cya!', COMPLETE: '\'Ya done good, partner!\x07\'Ere is ya reward.'}, 3255: {QUEST: "Finally, I want ya to defeat some of 'em Camera Heads.\x07Don't go lookin' for too many though! They're pretty uncommon around 'ere.", GREETING: 'Yahooooo!', LEAVING: '\'Cya!', COMPLETE: '\'Ya done good, partner!\x07\'Ere is ya reward.'}, 3262: {QUEST: "_toNpcName_ has a emergency!\x07Go see what his emergency is._where_"}, 3263: {GREETING: '', QUEST: "Argh!\x07Those Lawbots are always stealing my cameras and I'm sick of it!\x07Can you do me a favor and recover the ones stolen on this street?", LEAVING: 'Thanks!', COMPLETE: 'Awesome!\x07Here is your reward...'}, 3264: {QUEST: "Checkpoint!\x07_toNpcName_ wants to make sure you're strong enough to continue._where_"}, 3265: {QUEST: "Heya, _avName_!\x07You're halfway done with Gag Training for this playground.\x07As a challenge, I want you to take down, at minimum, a Three Story Building.\x07If you can't do that, you shouldn't bother finishing your training.", LEAVING: '', COMPLETE: "I stand corrected."}, 3266: {QUEST: "The final stretch!\x07See _toNpcName_ for more training._where_"}, 3267: {QUEST: "You're almost done with Daisy Gardens.\x07However, I want you to defeat one of the large buildings out there, Four Story at minimum.\x07If you can't defeat one of those, you shouldn't continue Gag Training anyways.", LEAVING: '', COMPLETE: "I stand corrected."}, 4001: {GREETING: '', QUEST: 'Now you get to choose the next gag track you want to learn.\x07Take your time deciding, and come back here when you are ready to choose.', INCOMPLETE_PROGRESS: 'Think about your decision before choosing.', INCOMPLETE_WRONG_NPC: 'Think about your decision before choosing.', COMPLETE: 'A wise decision...', LEAVING: QuestsDefaultLeaving}, 4002: {GREETING: '', QUEST: 'Now you get to choose the next gag track you want to learn.\x07Take your time deciding, and come back here when you are ready to choose.', INCOMPLETE_PROGRESS: 'Think about your decision before choosing.', INCOMPLETE_WRONG_NPC: 'Think about your decision before choosing.', COMPLETE: 'A wise decision...', LEAVING: QuestsDefaultLeaving}, 4200: {QUEST: "_toNpcName_ has a wicked broadcast about Skelecogs!_where_"}, 4201: {GREETING: '', QUEST: "Breaker, breaker! We've got a breaking news report here!\x07Skelecogs now roam the exterior of Sellbot Headquarters.\x07We've got _avName_ here to investigate on the case!\x07Please go find and defeat 5 Skelecogs that roam just outside the factory!"}, 4202: {QUEST: "Breaker, breaker! Wowza, what a scoop!\x07Gee whiz, there were really Skelecogs out there?\x07I wonder if they differ from the ones in the factory...", GREETING: '', LEAVING: '', COMPLETE: 'I guess they aren\'t that different...\x07Here is your reward...'}, 4203: {QUEST: "Great! One down...\x07Now swing by and get Yuki's._where_"}, 4204: {QUEST: 'Oh! The inventory!\x07I forgot all about it.\x07I bet I can have it done by the time you defeat 10 Cogs.\x07Stop in after that and I promise it will be ready.', INCOMPLETE_PROGRESS: '31, 32... DOH!\x07You made me lose count!', GREETING: ''}, 4205: {QUEST: 'Ah, there you are.\x07Thanks for giving me some time.\x07Take this to Tom and tell him I said Hello._where_'}, 4206: {QUEST: "Hmmm, very interesting.\x07Now we are getting somewhere.\x07Ok, the last inventory is Fifi's._where_"}, 4207: {QUEST: "Inventory?\x07How can I do an inventory if I don't have the form?\x07Go see Cleff and see if he has one for me._where_", INCOMPLETE_PROGRESS: 'Any sign of that form yet?'}, 4208: {QUEST: "Sure I got an inventory form, mon!\x07But dey ain't free, you know.\x07I'll tell you woht. I trade you for a fire hose.", GREETING: 'Hey, mon!', LEAVING: 'Cool runnings...', INCOMPLETE_PROGRESS: "A seltzer bottle won't do.\x07I be thirsty, mon. I need de fire hose."}, 4209: {GREETING: '', QUEST: 'Mmmm...\x07Dem mighty nice!\x07Here be your form for Fifi._where_'}, 4210: {GREETING: '', QUEST: "Thank you. That's a big help.\x07Let's see...Fiddles: 2\x07All done! Off you go!_where_", COMPLETE: "Great work, _avName_.\x07I'm sure I'll get to the bottom of these thefts now.\x07Why don't you get to the bottom of this!"}, 4211: {QUEST: 'We know it\'s a pain to go from Minnie\'s Melodyland and Sellbot HQ and back.\x07_toNpcName_ has a job for you to earn your early teleportation access._where_'}, 4212: {QUEST: "You need teleportation access?\x07Well, I want you to do a few favors for me.\x07First, can you reduce the Marketingbot population on this street?", INCOMPLETE_PROGRESS: 'Still no customers. But keep it up!'}, 4213: {QUEST: "As my second request, a bunch of the pesky Assfuckers disturb my private business.\x07Can you reduce the amount of them on this street?", INCOMPLETE_PROGRESS: "I know twenty is a lot. But I'm sure it's going to pay off in spades."}, 4214: {GREETING: '', LEAVING: '', QUEST: "Lastly, I want you to take down a big building on this street.\x07Then you may have teleportation access.", INCOMPLETE_PROGRESS: 'Oh, please! Just one little building...', COMPLETE: "Amazing job!\x07Here is your reward..."}, 4215: {QUEST: "_toNpcName_ is investigating on the Factory Foreman and needs some assistance._where_"}, 4216: {QUEST: "Thanks for stopping by, _avName_.\x07I am doing some research on what the Factory Foreman has planned.\x07Can you defeat him and report back to me if he has anything to say?", INCOMPLETE_PROGRESS: 'Those Glad Handers could be anywhere now...'}, 4217: {QUEST: "Mhmm...\x07So he dropped off the memo to one of his goons in Sellbot HQ...\x07There's no time to waste! Find it quickly!", COMPLETE: "Let's see what this says.\x07\"Dear Fellow Sellbots,\"\x07\"As you know, the V.P. has been having issues with toons breaking in. This is because of the Cog pieces dropped in the Sellbot Factory.\"\x07\"There is no way from stopping them from collecting all ten Sellbot pieces. Please be on the lookout for toons in disguise.\"\x07\"Signed, The Foreman.\"\x07So, shutting down the Sellbot Factory ten times will get you your Cog disguise! Good to know...\x07Well, here is your reward..."}, 4218: {QUEST: "Great Googely Moogely!\x07Alaska here I come!\x07I can't take these infernal Cogs anymore.\x07Say, I think Anna needs you again._where_"}, 4219: {QUEST: "Yup, you guessed it.\x07I need you to shake down those pesky Glad Handers for Tabitha's ticket to Jazzfest.\x07You know the procedure...", INCOMPLETE_PROGRESS: "There's more out there somewhere..."}, 4220: {QUEST: 'Sweet!\x07Could you swing this one by his place for me too?_where_'}, 4221: {GREETING: '', LEAVING: 'Be cool...', QUEST: "Cool, daddio!\x07Now I'm in fat city, _avName_.\x07Before you split, you better go check out Anna Banana again..._where_"}, 4222: {QUEST: "This is the last one, I promise!\x07Now you are looking for Barry's ticket to the big singing contest.", INCOMPLETE_PROGRESS: "C'mon, _avName_.\x07Barry is counting on you."}, 4223: {QUEST: "This should put a smile on Barry's face._where_"}, 4224: {GREETING: '', LEAVING: '', QUEST: 'Hello, Hello, HELLO!\x07Terrific!\x07I just know me and the boys are going to clean up this year.\x07Anna says to swing back by and get your reward._where_\x07Goodbye, Goodbye, GOODBYE!', COMPLETE: 'Thanks for all your help, _avName_.\x07You really are an asset here in Toontown.\x07Speaking of assets...'}, 4225: {GREETING: '', QUEST: '_toNpcName_ is conducting research on Sellbot Headquarters._where_', LEAVING: ''}, 4226: {QUEST: 'Yes, I believe the Sellbots are constructing something highly dangerous.\x07I\'ll need a memo from one of each cog, starting with a Cold Caller.'}, 4227: {QUEST: 'Let\'s see what it says.\x07\"Security is dire, we need more goons!\"\x07Well that isn\'t helpful.\x07Try getting a memo from a Telemarketer.'}, 4228: {QUEST: "\"Dear Mingler,\"\x07\"I have never been able to tell you my true feelings for you. I have always loved you and I hope we can go on a date someday.\"\x07\"Signed, Telemarketer.\"\x07Well, a love letter doesn't do us any good.\x07Try getting a memo from a Name Dropper."}, 4229: {QUEST: "\"Attention All Cold Callers,\"\x07\"I have spoken to Mr. Hollywood during my lunch break. He was able to fill out your request for more security goons and they should be ported over promptly.\"\x07\"Signed, Name Dropper.\"\x07Now, try getting something from a Glad Hander."}, 4230: {QUEST: "\"Dear Mr. Hollywood,\"\x07\"You are my role model. I love you.\"\x07\"Signed, Glad Hander.\"\x07Well, more fan mail doesn't help. Maybe a Mover & Shaker will have some helpful information?"}, 4231: {QUEST: "\"What do you call a fish with no eyes?\"\x07\"FSH.\"\x07THIS ISN'T A MEMO, THIS IS A JOKE!\x07I think this has to do with the Jokes being taken in Field Offices.\x07Maybe a Two-Face contains a Memo with serious information.", COMPLETE: "\"Dear Vice President,\"\x07\"The shipment of goons has been destroyed by the Toons. Most of our deliveries have been stopped by them somehow. We have no leads of how they are doing it.\"\x07\"Signed, Two-Face.\"\x07Well, that's that. The toons have came through again.\x07Here is your reward..."}, 4232: {QUEST: "_toNpcName_ feels like this town is \"Out of Pitch.\"_where_"}, 4233: {GREETING: 'Hello, hello, helloooo!', QUEST: "This town just doesn't seem the same! The Cogs are throwing it out of pitch!\x07Take out some Level Four cogs or higher on this street, maybe that'll help it!", LEAVING: 'Good-bye, good-bye, goooooooood-bye!!!'}, 4234: {GREETING: '', QUEST: "Now the pitch feels toooooooo high!\x07Maybe removing some higher up Cogs on Baritone Boulevard will lower the pitch a little bit.", LEAVING: 'Good-bye, good-bye, goooooooood-bye!!!'}, 4235: {GREETING: '', QUEST: "The pitch of the town is nearly perfect!\x07Just a few 7+ Cogs on Tenor Terrace will do it!\x07I believe you can do it!", LEAVING: 'Good-bye, good-bye, goooooooood-bye!!!', COMPLETE: "This pitch...\x07IT'S PERRRRRRRRRRRRRRRRRRRRRRRFECT!!!!"}, 4236: {QUEST: "The melody around here is decreasing and _toNpcName_ needs your help getting it back._where_"}, 4237: {GREETING: '', QUEST: "The melody of Minnie's Melodyland is decreasing!\x07The Cogs around here tend to take away the music notes all around the playground, which reduces the melody of this town.\x07Please get some back before this whole town loses its melody!", LEAVING: '', COMPLETE: "Everything sounds better!"}, 902: {QUEST: '_toNpcName_ needs to see you before giving you your new gag._where_'}, 4903: {QUEST: 'One way to be able to fight the Cogs without too many issues is by having strong gags to defend yourself with.\x07Please show me you have good enough gags by delivering to me One Whole Cream Pie.', GREETING: 'Hey there, buddy!', LEAVING: 'Cya, buddy!'}, 4904: {QUEST: 'Now that you have the Whole Cream Pie, I think you\'re ready for a new challenge.\x07Go infultrate and shut down the Sellbot Factory.\x07You will need other toons to accompany you during this task.', GREETING: 'Hey there, buddy!', LEAVING: 'Cya, buddy!', INCOMPLETE_PROGRESS: "Juo can find de squid wherever dere's a fishing pier", COMPLETE: "Wonderful job, buddy!\x07Here is your reward..."}, 4905: {QUEST: "Jes! Dat's it!\x07Now I need a leetle time to polish dees.\x07Why don juo go takeover a one story beelding while I work?", GREETING: 'Hola!', LEAVING: 'Adios!', INCOMPLETE_PROGRESS: 'Jest anodder minute...'}, 4906: {QUEST: 'Bery good!\x07Here are de castanets for Leo._where_'}, 4907: {GREETING: '', QUEST: "Cool, dude!\x07They look awesome!\x07Now I need you to get a copy of the lyrics to 'A Beat Christmas' from Hedy._where_"}, 4908: {QUEST: "Hello there!\x07Hmmm, I don't have a copy of that song handy.\x07If you give me a little while I could transcribe it from memory.\x07Why don't you run along and reclaim a two story building while I write?"}, 4909: {QUEST: "I'm sorry.\x07My memory is getting a little fuzzy.\x07If you go reclaim a three story building I'm sure I'll be done when you get back..."}, 4910: {QUEST: 'All done!\x07Sorry it took so long.\x07Take this back to Leo._where_', GREETING: '', COMPLETE: 'Awesome, dude!\x07My concert is gonna rock!\x07Speaking of rock, you can rock some Cogs with this...'}, 5247: {QUEST: 'This neighborhood is pretty tough...\x07You might want to learn some new tricks.\x07_toNpcName_ taught me everything I know, so maybe he can help you too._where_'}, 5248: {GREETING: 'Ahh, yes.', LEAVING: '', INCOMPLETE_PROGRESS: 'You appear to be struggling with my assignment.', QUEST: 'Ahh, so welcome, new apprentice.\x07I know all there is to know about the pie game.\x07But before we can begin your training, a small demonstration is necessary.\x07You have seen many cogs out there, but you have probably not seen cogs that hide out in facilities only, or haven\'t seen them as often.\x07These cogs are very rare and very strong. They\'re level range is outrageous too, they can go to level 50.\x07Before you start your training, I want you to defeat 5 of each of these, starting with The Big Cheeses.'}, 5249: {GREETING: 'Mmmmm.', QUEST: 'Excellent!\x07Now defeat some Big Wigs.', LEAVING: '', INCOMPLETE_PROGRESS: 'It seems you may not be so clever with the rod and reel.'}, 5250: {GREETING: '', LEAVING: '', QUEST: 'Now for some Robber Barons.\x07If you have strong enough gags, you can easily find them in the Cashbot Coin Mint.', INCOMPLETE_PROGRESS: 'Do the buildings give you trouble?'}, 5258: {GREETING: '', LEAVING: '', QUEST: 'Tell some Mr. Hollywoods to say good-bye to Hollywood.', INCOMPLETE_PROGRESS: 'Do the buildings give you trouble?'}, 5259: {GREETING: '', LEAVING: '', QUEST: 'Finally, I need you to defeat the Cogs in charge of almost all the operations: Search Engines.', INCOMPLETE_PROGRESS: 'Do the buildings give you trouble?'}, 5260: {GREETING: '', LEAVING: '', QUEST: 'Aha! These dice will look great hanging from the rearview mirror of my ox cart!\x07Now, show me that you can tell your enemies from one another.\x07Return when you have restored two of the tallest Sellbot buildings.', INCOMPLETE_PROGRESS: 'Do the buildings give you trouble?'}, 5202: {QUEST: lTheBrrrgh + " has been overrun with some of the toughest Cogs we've seen yet.\x07You will probably want to carry more gags around here.\x07I hear _toNpcName_ may have a large bag you can use to carry more gags._where_"}, 5203: {GREETING: '', QUEST: "What's that? You want a bag?\x07I had one somewhere around here...\x07While I go looking for it, defeat some of the toughest Cogs around here. It'll help attract more customers to this here dinner.", LEAVING: '', INCOMPLETE_PROGRESS: "Still can't find it...", COMPLETE: "Found it!"}, 5210: {QUEST: '_toNpcName_\'s snow globe collection has been stolen by the Cogs._where_'}, 5211: {GREETING: '', QUEST: 'My entire snow globe collection! Ruined!\x08_avName_, you must help me!\x07The Cogs on this street have stolen all 15 of my snow globes.\x07Please go get them back for me!', LEAVING: '', INCOMPLETE_PROGRESS: 'Please find my letter.'}, 5264: {GREETING: '', QUEST: 'Thanks so much!\x07Here is your re-\x07Wait, I forgot, a Cog walked in here and stole my secretly stored snow globe while you were away!\x07This snow globe happens to be my favorite.\x07I think the Cog mentioned something about visiting Walrus Way...', LEAVING: '', INCOMPLETE_PROGRESS: 'Please find my letter.', COMPLETE: 'Now, here\'s your reward...'}, 5265: {GREETING: '', QUEST: 'Thanks so much!\x07Here is your re-\x07Wait, I forgot, a Cog walked in here and stole my secretly stored snow globe while you were away!\x07This snow globe happens to be my favorite.\x07I think the Cog mentioned something about visiting Polar Place...', LEAVING: '', INCOMPLETE_PROGRESS: 'Please find my letter.', COMPLETE: 'Now, here\'s your reward...'}, 5217: {QUEST: 'It sounds like _toNpcName_ could use some help._where_'}, 5218: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: "I'm sure there are more Minglers around somewhere.", QUEST: "Help!!! Help!!! I can't take it anymore!\x07Those Minglers are driving me batty!!!"}, 5219: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: "That can't be all of them. I just saw one!", QUEST: "Oh thanks, but now it's the Corporate Raiders.\x07You have to help help me!"}, 5220: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'No, no, no there was one just here!', QUEST: "I realize now that it's those Loan Sharks!!!\x07I thought you were going to save me!!!"}, 5221: {GREETING: '', LEAVING: '', QUEST: "You know what? Maybe it isn't the Cogs after all.\x07Could you ask Fanny to make me a soothing potion? Maybe that would help...._where_"}, 5222: {LEAVING: '', QUEST: "Oh, that Harry, he sure is a card!\x07I'll whip up something that will fix him right up!\x07Oh, I appear to be out of sardine whiskers...\x07Be a dear and run down to the pond and catch some for me.", INCOMPLETE_PROGRESS: 'Got those whiskers for me yet?'}, 5223: {QUEST: 'Okay. Thanks, hon.\x07Here, now take this to Harry. It should calm him right down.', GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'Please go on and take the potion to Harry.'}, 5224: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'Go defeat those Legal Eagles for me.', QUEST: "Oh thank goodness you're back!\x07Give me the potion, quick!\x07Glug, glug, glug...\x07That tasted awful!\x07You know what though? I feel a lot calmer. Now that I can think clearly, I realize that...\x07It wasn't the Legal Eagles that were driving me crazy after all this time.", COMPLETE: "Oh boy, now I can relax!\x07I'm sure there's something here I can give you. Here you go!"}, 5225: {QUEST: '_toNpcName_ is hosting a skiing party and needs help preparing._where_'}, 5226: {QUEST: 'As you have heard, I am hosting a skiing party for a bunch of guests, but I have three things I need you to help me with.\x07First off, the Ambulance Chasers on this street can be a bit rough.\x07They usually take my guests and break their legs after these events.\x07Seeing this as problematic, please defeat at least 10 of them.', LEAVING: '', INCOMPLETE_PROGRESS: 'Maybe a few more buildings?'}, 5227: {QUEST: "Great job on those Chasers.\x07Next, I need you to get me some of _toNpcName_'s world famous soup, for I have a cold and do not need it spreading._where_"}, 5228: {QUEST: 'Need some soup?\x07Sure thing.\x07Just take down some big, pesky Sellbot Buildings on this street for me while I prepare the soup.', GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'You again? I thought you were going to get my tooth fixed for me.'}, 5229: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: "I'm still working on the tooth. It will be a bit longer.", QUEST: "Great job on those buildings.\x07Deliver this to _toNpcName_, pronto!"}, 5230: {GREETING: '', QUEST: "Thank you so much for the soup.\x07Slurp, Slurp.\x07I'm starting feel better already.\x07For my final request, I need some skates for this event from Kate._where_", LEAVING: '', INCOMPLETE_PROGRESS: 'Did you find that tooth yet?'}, 5231: {QUEST: "You need some skates?\x07First you'll have to do me a favor.\x07The Head Hunters on this street freak me out.\x07Please defeat some of them for me.", GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'I bet Phil would like to see his new tooth.'}, 5232: {QUEST: "A deal's a deal.\x07Run these over to _toNpcName_.", LEAVING: '', GREETING: '', COMPLETE: 'Thanks for all your help.\x07You deserve this reward.'}, 903: {QUEST: 'You may be ready to see _toNpcName_ the Blizzard Wizard for your final test._where_'}, 5234: {GREETING: '', QUEST: "Ahh, welcome back young apprentice.\x07I see you have completed all 15 Track Frames. Congrats!\x07However, you must pass my final test in order to prove yourself ready.\x07Start by shutting down 3 Sellbot Factories.", LEAVING: '', INCOMPLETE_PROGRESS: "I may be old, but I know you haven't finished your quest yet. You can't fool me that easily."}, 5235: {GREETING: '', QUEST: "Welcome back.\x07Great job on shutting down those factories.\x07Next, I want you to take down some Lawbot Field Offices.", LEAVING: '', INCOMPLETE_PROGRESS: "I may be old, but I know you haven't finished your quest yet. You can't fool me that easily."}, 5236: {GREETING: '', QUEST: "Welcome back.\x07Great job on shutting down those factories.\x07Next, I want you to take down some Sellbot Field Offices.", LEAVING: '', INCOMPLETE_PROGRESS: "I may be old, but I know you haven't finished your quest yet. You can't fool me that easily."}, 5237: {QUEST: "Now, I want you to defeat some of the strongest Cogs out there.\x07Afterwards, I will give you my final quest for you.", GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'Too weak for those Cogs?'}, 5238: {GREETING: '', QUEST: 'Okay.\x07As I once said, to truly throw a pie, you must throw not with the hand...\x07...but with the soul.\x07I know not what that means, so I will sit and contemplate while take down some of the strongest Cog Buildings.\x07Return when you have completed your task.', LEAVING: '', COMPLETE: 'Whew! I am tired from all this effort. I must rest now.\x07Here, take your reward and be off.'}, 5243: {QUEST: '_toNpcName_ has a strong fear of the new Marketingbot Cog Buildings, more than any other Toon in Toontown._where_'}, 5244: {GREETING: '', QUEST: "Egad!\x07Marketingbots keep taking over building after building!\x07Please take some down before they decide to take over MY shop!", LEAVING: '', INCOMPLETE_PROGRESS: "Where's that gear you were going to get?", COMPLETE: "Thank you."}, 5251: {QUEST: '_toNpcName_ is preparing a trip around the world, but the Cogs just don\'t want her to go!_where_'}, 5252: {GREETING: '', QUEST: 'Please help me!\x07Every time I prepare for a trip, the Cogs keep stealing all I need to travel.\x07This time, a Marketingbot has taken my Boarding Ticket.\x07That Cog should still be somewhere around this playground...', LEAVING: '', INCOMPLETE_PROGRESS: "Hey man, I can't sing without my microphone."}, 5253: {GREETING: '', QUEST: "Those Marketingbots really have it in for me.\x07A Camera Head came in and took my passport...", LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding my keboard?'}, 5273: {GREETING: '', QUEST: "Those Marketingbots really have it in for me.\x07An Assfucker came in and took my passport...", LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding my keboard?'}, 5274: {GREETING: '', QUEST: "Those Marketingbots really have it in for me.\x07A Viral Marketer came in and took my passport...", LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding my keboard?'}, 5275: {GREETING: '', QUEST: "Those Marketingbots really have it in for me.\x07A Cog Cart came in and took my passport...", LEAVING: '', INCOMPLETE_PROGRESS: 'No luck finding my keboard?'}, 5254: {GREETING: '', QUEST: "Seriously?\x07Now a Mingler took my Suitcase!", LEAVING: '', COMPLETE: "Now I am good to go.\x07Thank you, here is your reward...", INCOMPLETE_PROGRESS: "I can't perform barefoot, can I?"}, 5282: {GREETING: '', QUEST: "Seriously?\x07Now a Corporate Raider took my Suitcase!", LEAVING: '', COMPLETE: "Now I am good to go.\x07Thank you, here is your reward...", INCOMPLETE_PROGRESS: "I can't perform barefoot, can I?"}, 5283: {GREETING: '', QUEST: "Seriously?\x07Now a Loan Shark took my Suitcase!", LEAVING: '', COMPLETE: "Now I am good to go.\x07Thank you, here is your reward...", INCOMPLETE_PROGRESS: "I can't perform barefoot, can I?"}, 5284: {GREETING: '', QUEST: "Seriously?\x07Now a Legal Eagle took my Suitcase!", LEAVING: '', COMPLETE: "Now I am good to go.\x07Thank you, here is your reward...", INCOMPLETE_PROGRESS: "I can't perform barefoot, can I?"}, 5255: {QUEST: '_toNpcName_ hates Lawbots and needs help dealing with them.\x07Toons may not like Cogs, but his foreign policy specifically on Lawbots is too brutal for us to imagine..._where_'}, 5256: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: "A deal's a deal.", QUEST: "Welcome, fellow toon.\x07When Lawbot HQ sends its Cogs, they're not sending their best.\x07Look at them! They storm all around this street and take over so many buildings!\x07I want you to defeat a handful of them on this street."}, 5276: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: "A deal's a deal.", QUEST: "Now, let's take back what belongs to us.\x07Defeat a Lawbot Building on this street.", COMPLETE: "Maybe I should build a wall around Lawbot HQ. That'll keep them from entering our town..."}, 5257: {QUEST: "_toNpcName_'s glasses have been stolen._where_"}, 5277: {GREETING: '', LEAVING: '', QUEST: "A Foreign Marketer has stolen my glasses!\x07Please go get them back for me, or I'll be blind forever!", INCOMPLETE_PROGRESS: "I don't think you're done yet.", COMPLETE: "It's a miracle! I can see!"}, 5301: {QUEST: "_toNpcName_'s glasses have been stolen._where_"}, 5302: {GREETING: '', LEAVING: '', COMPLETE: "Thank goodness, I can see again.", INCOMPLETE_PROGRESS: 'Hi!\x07What are you doing in here again!', QUEST: 'A Loan Shark has stolen my glasses!\x07Please go get them back for me, or I\'ll be blind forever!'}, 5308: {GREETING: '', LEAVING: '', QUEST: 'I hear _toNpcName_ is having some legal troubles.\x07Can you stop by and check it out?_where_'}, 5309: {GREETING: "I'm glad you're here...", LEAVING: '', INCOMPLETE_PROGRESS: 'Please hurry! The street is crawling with them!', QUEST: "The Lawbots have really taken over out there.\x07I'm afraid they are going to take me to court.\x07Do you think you could help get them off of this street?"}, 5310: {GREETING: '', LEAVING: '', INCOMPLETE_PROGRESS: 'I think I hear them coming for me...', QUEST: "Thanks. I feel a little better now.\x07 But there is one more thing...\x07Could you drop by _toNpcName_'s and get me an alibi?_where_"}, 5311: {GREETING: 'WHAAAA!!!!', LEAVING: '', INCOMPLETE_PROGRESS: "I can't help him if you can't find it!", QUEST: "Alibi?! Why that's a great idea!\x07You'd better make it two!\x07I bet a Legal Eagle would have some..."}, 5312: {GREETING: 'Finally!', LEAVING: '', INCOMPLETE_PROGRESS: '', COMPLETE: "Whew! Am I ever relieved to have this.\x07Here's your reward...", QUEST: "Super! You'd better run these back to _toNpcName_!"}, 5313: {QUEST: "Checkpoint!\x07_toNpcName_ wants to test your skills to see if you're eligable to continue your Gag Training._where_"}, 5314: {QUEST: "Now that you are halfway done, you should be able to take down one of the biggest Cog Buildings around the town.\x07If you cannot, don't bother finishing your Gag Training.", LEAVING: '', COMPLETE: "I stand corrected..."}, 6201: {QUEST: 'The citizens of Pajama Place are dealing with a lot of issues.\x07_toNpcName_ needs help taking care of these citizen\'s needs._where_'}, 6202: {QUEST: 'Heya, _avName_! Thanks for stopping by.\x07There are so many citizens on this street who need help, and as a high class member in the Toon Resistance, it is my duty to help these toons with their needs.\x07However, I could use some help with some toons. I\'ve worn myself out from all the other help.\x07First, _toNpcName_\'s boat has been destroyed by the Cogs and he needs some help._where_'}, 6203: {GREETING: '', QUEST: "Yarrr.\x07Those obnoxious Cogs have destoryed me fine, favorite ship's steering wheel.\x07Luckily, I know the best matey in town who can fix this in a jiffy! _toNpcName_!\x07Just deliver this to the laddy and all shall be a bliss._where_", LEAVING: "Avast, matey!"}, #He's suppose to sound like a pirate, "me fine" is not a mistake 6204: {QUEST: "This needs some fixing?\x07Sure, no problem.\x07While I work on this, please defeat some Cogs on this street. There are too many and it freaks me out."}, 6205: {QUEST: "All done!\x07Bring this back to _toNpcName_ on the double!", LEAVING: ''}, 6206: {GREETING: '', QUEST: "Yarrr!\x07Brilliant work, lad!\x07Let _toNpcName_ know that me issue has been taken care of.", LEAVING: 'Avast, matey!'}, #He's suppose to sound like a pirate, "me issue" is not a mistake 6207: {QUEST: "Great job!\x07Next, the higher powered Cogs have been messing with the Optometry stores around town and have been stealing glasses from the doctors running the store.\x07Speaking of which, _toNpcName_ needs his glasses back._where_"}, 6208: {GREETING: '', QUEST: "A Corporate Raider just came in here and took my glasses!\x07Please go get them back for me! I can't see a thing without them!", LEAVING: ''}, 6209: {GREETING: '', QUEST: "Awesome! You got them back!\x07However, you better hurry to _toNpcName_'s shop!\x07He just called in saying that his glasses were stolen._where_", LEAVING: ''}, 6210: {GREETING: '', QUEST: "Thank you so much for coming.\x07A Mingler just broke in and took my glasses.\x07I can't see a thing without them! Please go get them back!", LEAVING: ''}, 6211: {GREETING: '', QUEST: "Great!\x07Let _toNpcName_ know that the Optometries in town are fine now.", LEAVING: ''}, 6212: {QUEST: "OK, I've got one more job for you before I go back to helping the citizens myself.\x07_toNpcName_ is trying to go on a vacation, but the Cogs won't let him leave._where_"}, 6213: {QUEST: "I'm trying to get out of here and take a nice, relaxing vacation.\x07However, a Legal Eagle stole my passport and I can't go anywhere without it.\x07Please go get it back for me.", LEAVING: ''}, 6214: {QUEST: "Thanks, but I can't really go anywhere with all these Cashbots keeping the shopkeepers in their shops.\x07Please take out a handful of them so I can escape without any issues.", LEAVING: ''}, 6215: {QUEST: "Thanks, but I can't really go anywhere with all these strong Cogs keeping the shopkeepers in their shops.\x07Please take out a handful of them so I can escape without any issues.", LEAVING: ''}, 6216: {GREETING: '', QUEST: "Thank you so much!\x07I'll be heading out soon.\x07Let _toNpcName_ know that everything is OK over here.", COMPLETE: "Thank you for all your help around here.\x07That was some BIG help you lent me, so I think you deserve a BIG reward!"}, 6217: {QUEST: "_toNpcName_'s customers haven't been returning their library books._where_"}, 6218: {QUEST: "Thanks for coming.\x07Twenty of the people who check books out at my store have called and said that the Cogs have taken their books.\x07All the toons that called were citizens of Donald's Dreamland, which means the Cogs must be around here too.\x07Please go get the books back.", COMPLETE: "Great job!"}, 6219: {QUEST: "_toNpcName_ can't serve drinks without her bottles!_where_"}, 6220: {GREETING: '', QUEST: ". . . ZZZ . . . (Thanks for coming).\x07. . . ZZZ . . . (The other day, the Cogs had a party here and I poured them drinks, but they just ran off with the bottles).\x07. . . ZZZ . . . (Those were the only bottles I had to serve drinks in! Please get them back.)\x07. . . ZZZ . . . (Those Cogs should be around Donald's Dreamland).", LEAVING: '. . . ZZZ . . .', COMPLETE: '. . . ZZZ . . . (Thank you).\x07. . . ZZZ . . . (Here is your reward).'}, 6221: {QUEST: "_toNpcName_ hates the Cog Buildings around here._where_"}, 6222: {GREETING: '', QUEST: "I see you need Teleportation Access to Donald's Dreamland, but first I need help.\x07Please take down some big buildings in Donald's Dreamland. They cause a lot of tension for us shopkeepers.", COMPLETE: 'Good job.\x07Here is your reward...'}, 7201: {QUEST: '_toNpcName_ is having an issue with his oil supply._where_'}, 7202: {GREETING: '', LEAVING: 'Ehh? You say something, sonny?', QUEST: "You know, young feller, many toons around here need my oil for their high technological device things.\x07I'm old and don't know how that works, but I will supply them young folks with the oil they need.\x07However, the Cashbots keep taking my here oil and storing it in their high tech Coin Mints, or whatever you young folks call it.\x07Shut down 5 Coin Mints, and maybe the other young folks will get the oil they need.", INCOMPLETE_PROGRESS: "Did Hardy have any beds? I was sure he'd have one.", COMPLETE: 'Good job.\x07The Cogs need to learn what a \'Fair Share\' is, and Flippy clearly doesn\'t know how to educate them on that!\x07Here is, whatever you young folks call it... Your reward.'}, 7203: {QUEST: "The Cashbots seem to rather enjoy _toNpcName_'s Donuts, but perhaps a bit too much..._where_"}, 7204: {GREETING: '', QUEST: "Oh, _avName_, you've gotta help me!\x07The Cashbots of the Dollar Mint occassionally have donut parties for the high leveled Cogs and often take my donuts.\x07Now, that doesn't sound problematic, IF THEY WOULD PAY FOR THE DONUTS!\x07Please recover the ten that were just stolen for tonight's donut party!", LEAVING: '', COMPLETE: "Thank you so much!\x07Would you like to buy some donuts? No?\x07Instead, I will reward you with this..."}, 7205: {QUEST: "_toNpcName_ has a tap dancing competition, but she can't perform without the tap dancing shoes that were stolen from her._where_"}, 7206: {QUEST: "Oh this is just great!\x07Tomorrow's the big day of the tap dancing competition, and a Money Bags came and stole my tap dancing shoes!\x07I have a tracking device on those shoes, for reasons like this, and it says that the Money Bag is in the Cashbot Coin Mint.\x07Please go get those shoes back for me!", LEAVING: '', COMPLETE: "Thank you so much."}, 7207: {QUEST: "_toNpcName_ has a story to tell you.\x07However, you must complete the quests he talks about in the story, for the quests in the story are told to come true if they're not done.\x07We would just ask you to tell him to stop, but he reads his stories to guests as they enter before answering any questions.\x07Maybe you can get him to stop?_where_"}, 7208: {GREETING: '', QUEST: "Once upon a time, there was a heroic toon named _avName_.\x07_avName_ was the toon who stopped the great Cashbot takeover.\x07First, _avName_ did this by stopping the 10 most dangerous Money Bags in the Coin Mint.\x07If _avName_ were to fail to defeat these 10 Money Bags, they'd advise the other Money Bags of the Coin Mint to flood out of the mints and storm Toontown.", LEAVING: ''}, 7209: {GREETING: '', QUEST: "After flawlessly defeating those Money Bags, _avName_ knew found out that there were 15 Loan Sharks in the Dollar Mint devising a plan to invade.", LEAVING: ''}, 7210: {GREETING: '', QUEST: "With the defeat of the Loan Sharks, _avName_ was told by one of them \"You'll never stop our top 20 Robber Barons in the Bullion Mint from invading.\"\x07\"Our plans were false just to distract you from going to the Bullion Mint.\"\x07With that, _avName_ ran to the Bullion Mint to fight off those Robber Barons...", LEAVING: '', COMPLETE: "...and everyone lived happily ever after.\x07The End.\x07So, _avName_, what do you need?\x07The Toon Headquarters say my stories come true? No way!\x07I'll try to make my stories less intense. In the meantime, here's a reward for saving our town."}, 7211: {QUEST: "_toNpcName_ just can't get enough sleep._where_"}, 7212: {GREETING: '', QUEST: "_avName_, you've gotta help me!\x07My pillows are all rough and uncomforting.\x07Can you ask _toNpcName_ if I can get some of her pillows?_where_", LEAVING: ''}, 7213: {QUEST: "Need some pillows?\x07I hate to tell you this, but we're fresh out of pillows.\x07The Cashbots took my last shipment of 15 Pillows to the Bullion Mint.\x07I have no idea why they would do such a thing, but please go get them back for me!", LEAVING: ''}, 7214: {GREETING: '', QUEST: "Awesome.\x07Here are some pillows for you.", LEAVING: '', COMPLETE: "Thank you so much!\x07These pillows are awesome.\x07Here is your reward..."}, 7215: {QUEST: "The Marketingbots of Lullaby Lane have been causing trouble to _toNpcName_'s shop._where_"}, 7216: {GREETING: '', QUEST: "It's just awful how those Marketingbots treat me!\x07I just fixed 10 watches for my customers. amd they just came in and stole them all!\x07Please go get them back for me! The customers will be here soon!\x07The Marketingbots couldn't of gone far...", LEAVING: '', COMPLETE: "Thank you so much! Here's a larger bean bag for you."}, 8301: {QUEST: "_toNpcName_ has a bad feeling about the Lawbot Clerk._where_"}, 8302: {QUEST: "Ever since the Lawbot Offices have requested more Cogs, their Clerk has been getting stronger.\x07People don't believe me when I say this, but rumor has it that the Clerk is a Level 16 Cog!\x07Crazy, right!\x07I want you to prove it by defeating a Lawbot Office A.", COMPLETE: "You saw it?\x07Oh my Galoshes!\x07Anyways, here's your reward..."}, 8303: {QUEST: "Living near Lawbot Headquarters can be so brutal, says _toNpcName_._where_"}, 8304: {GREETING: '', QUEST: "Dude.\x07Like, those Lawbots man! They just keep coming in here and, like, totally steal all my records that I listen to!\x07They, like, have a groovy party in the Office B and they totally don't invite me!\x07Can you, like, get all 20 of my records back, dude?", LEAVING: "Like, peace out man.", COMPLETE: "Dude!\x07You are like, totally whicked man!\x07Here's, like, your reward..."}, 8305: {QUEST: "Hmm... There has been a report of a power outage on Walrus Way.\x07Go to _toNpcName_, he manages the power around The Brrrgh._where_"}, 8306: {GREETING: '', QUEST: "Many shops on this street have been experiencing power outages, and it's all because a Spin Doctor came in and took the power generator.\x07He told me that I need to pay my fair share to the Cogs and to give up the generator to give more power to the Lawbot Office C.\x07I don't even know what that's suppose to mean!\x07You should hurry and get that generator back before it's too late!", LEAVING: ''}, 8307: {GREETING: '', QUEST: "Good job getting it back.\x07Now let's just put this into the socket...\x07Huh? That's weird. It's not working!\x07Oh no, it seems we're too late!\x07The Lawbot Building in The Brrrgh have taken all the power!\x07If you can take down 5 Lawbot Buildings, the power should be up and running perfectly again.", LEAVING: '', COMPLETE: "We're up and running!\x07Here's your reward..."}, 8308: {QUEST: "We believe that _toNpcName_ has some intel on Lawbot Offices._where_"}, 8309: {GREETING: '', QUEST: "So I've been researching, and the Lawbot Office D consists of some of the strongest Cogs in Toontown.\x07I want you to defeat 30 of the highest Cogs in there.\x07Then, I will give you a big reward.", LEAVING: '', COMPLETE: "A promise is a promise."}, 8310: {QUEST: "Professor Flake is astonished at the fact that Cogs have started to go higher than level 12!_where_"}, 8311: {GREETING: "", QUEST: "Oh, this is bad...\x07The Cashbot Supervisors can go up to Level 14 and the Lawbot Clerks can go up to Level 16!\x07This is big news to me!\x07I want you to defeat several Level 16 Cogs in the DA Offices, maybe that'll calm me down.", LEAVING: '', COMPLETE: "I wonder what made those Cogs so strong...\x07Here is a reward for you..."}, 9301: {QUEST: "_toNpcName_ is tracking down a new type of Cog._where_"}, 9302: {GREETING: '', QUEST: "Greetings, _avName_.\x07It seems the Bossbots have a new type of Cog called a Version 2.0 Cog.\x07I don't know much about these, but you can find them all over Bossbot Headquarters.\x07Go defeat some in the Front Three and report back what you witness.", LEAVING: '', COMPLETE: "Interesting...\x07The Cogs revive after being defeated?\x07How about that...\x07Here is your reward..."}, 9303: {QUEST: "The Bossbot Golf Courses are pretty brutal.\x07_toNpcName_ wants to see if you are able to handle them._where_"}, 9304: {GREETING: '', QUEST: "In Bossbot Headquarters, there are 3 different Golf Courses.\x07The Front Three, The Middle Six, and The Back Nine.\x07I want you to defeat 3 Front Threes.", LEAVING: '', COMPLETE: "Good job."}, 9305: {QUEST: "_toNpcName_ has intel on the Middle Six._where_"}, 9306: {GREETING: '', QUEST: "The Middle Six has more holes than the Front Three does, which means it also has some Cogs.\x07I want you to defeat 2 Middle Sixes, then report back to me.", LEAVING: '', COMPLETE: "Good job."}, 9307: {QUEST: "_toNpcName_ wants you to infultrate the hardest Cog facility out there._where_"}, 9308: {GREETING: 'Yarr...', QUEST: "Avast, I have once infultrated a Back Nine, but brutally failed.\x07I want ye to infultrate the Back Nine and finish the job for me.\x07A few things that ye must know, a Back Nine takes a lot of time to complete, so ye must plan when to do it for when ye have enough time.\x07Ye also need a mighty crew to complete the task.\x07I wish ye the best of luck!", LEAVING:'', COMPLETE: "Ye did it!"}, 9309: {GREETING: '', QUEST: "_toNpcName_ has leads on the high leveled Cogs in Bossbot Headquarters._where_", LEAVING: ''}, 9310: {GREETING: '', QUEST: "Oh my, this is crazy.\x07The Cogs in Bossbot Headquarters go as high as level 18! That's crazy!\x07I want you to defeat several of these high leveled Cogs.", LEAVING: '', COMPLETE: "I got worried that you were hurt when I sent you off to do that quest.\x07Take this as an apology..."}, 11000: {GREETING: '', LEAVING: '', QUEST: '_toNpcName_ has some dirt on how to teleport to Sellbot Headquarters._where_'}, 11001: {GREETING: '', QUEST: "Welcome, _avName_!\x07As you have heard, I have the scoop on how you can teleport to Sellbot Headquarters.\x07First, I want you to do some vigorous tasks involving taking those Sellbots down.\x07Shut down several Cog Factories.", LEAVING: ''}, 11002: {GREETING: '', QUEST: "Now, take down some Sellbot Field Offices.", LEAVING: ''}, 11003: {GREETING: '', QUEST: "OK, I'll tell you how you can get teleportation access.\x07Rarely, one of the Cogs in Sellbot Headquarters carry around a memo for teleportation access.\x07The reason that nobody has figured it out before is because the memo is in the shape of a Cog Gear.\x07Once you recover it, return it here to me and you will be granted with teleportation access.", LEAVING: '', COMPLETE: 'And now...'}, 12000: {GREETING: '', LEAVING: '', QUEST: "_toNpcName_ has a secret on how you can teleport into Cashbot Headquarters._where_"}, 12001: {GREETING: '', QUEST: "You want teleportation access to Cashbot Headquarters?\x07Sure! I'll let you on a little secret, but you'll have to prove yourself worthy.\x07First, shut down some Coin Mints.", LEAVING: ''}, 12002: {GREETING: '', LEAVING: '', QUEST: "Next, I want you to shut down a few Dollar Mints."}, 12003: {GREETING: '', LEAVING: '', QUEST: "Lastly, shut down a couple of Bullion Mints."}, 12004: {GREETING: '', LEAVING: '', QUEST: "OK, I'll let you in on a little secret.\x07All Cashbots carry money everywhere they go.\x07However, in Cashbot Headquarters, it is rare that a Cashbot will carry around fake money.\x07One of these fake bills is the actual memo to grant you Teleportation Access to Cashbot Headquarters.\x07Go look for it and return it here so I can grant you access with the memo.", COMPLETE: "Using the memo, let me grant you access.\x07...\x07Done!"}, 13000: {GREETING: '', LEAVING: '', QUEST: "_toNpcName_ knows her ways around Lawbot Headquarters and also knows how to get teleportation access to it._where_"}, 13001: {GREETING: '', LEAVING: '', QUEST: "Welcome, _avName_.\x07I am willing to grant you teleportation access, but you must prove yourself worthy.\x07Shut down several Lawbot B-Offices to start with."}, 13002: {GREETING: '', LEAVING: '', QUEST: "Now, take down some Lawbot Field Offices."}, 13003: {GREETING: '', LEAVING: '', QUEST: "Now, I shall let you in on my little secret.\x07All Cogs in Lawbot Headquarters carry around a small gavel with them.\x07Who were to know that some of their gavels are folded up teleporation access memo?\x07Now that you know, go find one and bring it back here so I can grant you teleportation access.", COMPLETE: "Here you go."}, 14000: {GREETING: '', LEAVING: '', QUEST: "_toNpcName_ has a big scoop on how to teleport to Bossbot Headquarters._where_"}, 14001: {GREETING: '', LEAVING: '', QUEST: "Hey there, _avName_.\x07I see you are interested in my little secret to teleporting to Bossbot Headquarters.\x07First, I want you to complete a couple middle sixes to prove that you're worthy."}, 14002: {GREETING: '', LEAVING: '', QUEST: "OK, I'll tell ya.\x07In their pockets, the Bossbots that are members at the Country Club carry a golf ball.\x07Several of the Cogs fold their teleportation access memos into spheres to make them look like golf balls.\x07Bring back a memo so I can grant your access.", COMPLETE: "Wonderful job!"}} ChatGarblerDog = ['woof', 'arf', 'rruff'] ChatGarblerCat = ['meow', 'mew'] ChatGarblerMouse = ['squeak', 'squeaky', 'squeakity'] ChatGarblerHorse = ['neigh', 'brrr'] ChatGarblerRabbit = ['eek', 'eepr', 'eepy', 'eeky'] ChatGarblerDuck = ['quack', 'quackity', 'quacky'] ChatGarblerMonkey = ['ooh', 'ooo', 'ahh'] ChatGarblerBear = ['growl', 'grrr'] ChatGarblerPig = ['oink', 'oik', 'snort'] ChatGarblerDefault = ['blah'] Boardbot = 'Marketingbot' Bossbot = 'Bossbot' Lawbot = 'Lawbot' Cashbot = 'Cashbot' Sellbot = 'Sellbot' BoardbotS = 'a Marketingbot' BossbotS = 'a Bossbot' LawbotS = 'a Lawbot' CashbotS = 'a Cashbot' SellbotS = 'a Sellbot' BoardbotP = 'Marketingbots' BossbotP = 'Bossbots' LawbotP = 'Lawbots' CashbotP = 'Cashbots' SellbotP = 'Sellbots' BoardbotSkelS = 'a Marketingbot Skelecog' BossbotSkelS = 'a Bossbot Skelecog' LawbotSkelS = 'a Lawbot Skelecog' CashbotSkelS = 'a Cashbot Skelecog' SellbotSkelS = 'a Sellbot Skelecog' BoardbotSkelP = 'Bossbot Skelecogs' BossbotSkelP = 'Bossbot Skelecogs' LawbotSkelP = 'Lawbot Skelecogs' CashbotSkelP = 'Cashbot Skelecogs' SellbotSkelP = 'Sellbot Skelecogs' SkeleReviveCogName = 'Version 2.0 %(cog_name)s' SkeleRevivePostFix = ' v2.0' AvatarDetailPanelOK = lOK AvatarDetailPanelCancel = lCancel AvatarDetailPanelClose = lClose AvatarDetailPanelLookup = 'Looking up details for %s.' AvatarDetailPanelFailedLookup = 'Unable to get details for %s.' AvatarDetailPanelPlayer = 'Player: %(player)s\nWorld: %(world)s' AvatarDetailPanelPlayerShort = '%(player)s\nWorld: %(world)s\nLocation: %(location)s' AvatarDetailPanelRealLife = 'Offline' AvatarDetailPanelOnline = 'District: %(district)s\nLocation: %(location)s' AvatarDetailPanelOnlinePlayer = 'District: %(district)s\nLocation: %(location)s\nPlayer: %(player)s' AvatarDetailPanelOffline = 'District: offline\nLocation: offline' import time def getTimeString(timestamp, past = None): if past: seconds = int(time.time()) - int(timestamp) else: seconds = int(timestamp) - int(time.time()) if timestamp == 0: return 'Never' else: if seconds < 60: string = 'Less than a minute' elif seconds < 120: string = '1 minute' elif seconds < 3600: string = '%d minutes' % int(seconds / 60) elif seconds < 7200: string = '1 hour' elif seconds < 86400: string = '%d hours' % int(seconds / 3600) elif seconds < 172800: string = '1 day' elif seconds < 2592000: string = '%d days' % int(seconds / 86400) elif seconds < 5184000: string = '1 month' elif seconds < 31536000: string = '%d months' % int(seconds / 2592000) elif seconds < 63072000: string = '1 year' else: if past: return 'A very long time ago... :-(' return 'a long time' if past: return string + ' ago' return string AvatarShowPlayer = 'Show Player' OfflineLocation = 'Offline' PlayerToonName = 'Toon: %(toonname)s' PlayerShowToon = 'Show Toon' PlayerPanelDetail = 'Player Details' AvatarPanelFriends = 'Friends' AvatarPanelWhisper = 'Whisper' AvatarPanelSecrets = 'True Friends' AvatarPanelGoTo = 'Go To' AvatarPanelPet = 'Show Doodle' AvatarPanelIgnore = 'Ignore' AvatarPanelIgnoreCant = 'Okay' AvatarPanelStopIgnoring = 'Stop Ignoring' AvatarPanelReport = 'Report' AvatarPanelCogLevel = 'Level: %s' AvatarPanelCogDetailClose = lClose AvatarPanelDetail = 'Toon Details' AvatarPanelGroupInvite = 'Invite' AvatarPanelGroupRetract = 'Retract Invitation' AvatarPanelGroupMember = 'Already In Group' AvatarPanelGroupMemberKick = 'Remove' ReportPanelTitle = 'Report A Player' ReportPanelBody = 'This feature will send a complete report to a Moderator. Instead of sending a report, you might choose to do one of the following:\n\n - Teleport to another district\n - Use "Ignore" on the toon\'s panel\n\nDo you really want to report %s to a Moderator?' ReportPanelBodyFriends = 'This feature will send a complete report to a Moderator. Instead of sending a report, you might choose to do one of the following:\n\n - Teleport to another district\n - Break your friendship\n\nDo you really want to report %s to a Moderator?\n\n(This will also break your friendship)' ReportPanelCategoryBody = 'You are about to report %s. A Moderator will be alerted to your complaint and will take appropriate action for anyone breaking our rules. Please choose the reason you are reporting %s:' ReportPanelBodyPlayer = 'This feature is stilling being worked on and will be coming soon. In the meantime you can do the following:\n\n - Go to DXD and break the friendship there.\n - Tell a parent about what happened.' ReportPanelCategoryLanguage = 'Foul Language' ReportPanelCategoryPii = 'Sharing/Requesting Personal Info' ReportPanelCategoryRude = 'Rude or Mean Behavior' ReportPanelCategoryName = 'Bad Name' ReportPanelCategoryHacking = 'Hacking' ReportPanelConfirmations = ('You are about to report that %s has used obscene, bigoted or sexually explicit language.', 'You are about to report that %s is being unsafe by giving out or requesting a phone number, address, last name, email address, password or account name.', 'You are about to report that %s is bullying, harassing, or using extreme behavior to disrupt the game.', "You are about to report that %s has created a name that does not follow the Town Toon Wacky Silly 3 rules.", 'You are about to report that %s has hacked/tampered with the game or used third party software.') ReportPanelWarning = "We take reporting very seriously. Your report will be viewed by a Moderator who will take appropriate action for anyone breaking our rules. If your account is found to have participated in breaking the rules, or if you make false reports or abuse the 'Report a Player' system, a Moderator may take action against your account. Are you absolutely sure you want to report this player?" ReportPanelThanks = 'Thank you! Your report has been sent to a Moderator for review. There is no need to contact us again about the issue. The moderation team will take appropriate action for a player found breaking our rules.' ReportPanelRemovedFriend = 'We have automatically removed %s from your Toon Friends List.' ReportPanelRemovedPlayerFriend = 'We have automatically removed %s as a Player friend so as such you will not see them as your friend in any Town Toon Wacky Silly 3 product.' ReportPanelAlreadyReported = 'You have already reported %s during this session. A Moderator will review your previous report.' IgnorePanelTitle = 'Ignore A Player' IgnorePanelAddIgnore = 'Would you like to ignore %s for the rest of this session?' IgnorePanelIgnore = 'You are now ignoring %s.' IgnorePanelRemoveIgnore = 'Would you like to stop ignoring %s?' IgnorePanelEndIgnore = 'You are no longer ignoring %s.' IgnorePanelAddFriendAvatar = '%s is your friend, you cannot ignore them while you are friends.' IgnorePanelAddFriendPlayer = '%s (%s)is your friend, you cannot ignore them while you are friends.' PetPanelFeed = 'Feed' PetPanelCall = 'Call' PetPanelGoTo = 'Go To' PetPanelOwner = 'Show Owner' PetPanelDetail = 'Pet Details' PetPanelScratch = 'Scratch' PetDetailPanelTitle = 'Trick Training' PetTrickStrings = {0: 'Jump', 1: 'Beg', 2: 'Play dead', 3: 'Rollover', 4: 'Backflip', 5: 'Dance', 6: 'Speak'} PetMoodAdjectives = {'neutral': 'neutral', 'hunger': 'hungry', 'boredom': 'bored', 'excitement': 'excited', 'sadness': 'sad', 'restlessness': 'restless', 'playfulness': 'playful', 'loneliness': 'lonely', 'fatigue': 'tired', 'confusion': 'confused', 'anger': 'angry', 'surprise': 'surprised', 'affection': 'affectionate'} SpokenMoods = {'neutral': 'neutral', 'hunger': ["I'm tired of Jellybeans! How'bout giving me a slice of pie?", "How'bout a Red JellyBean? I'm tired of the Green ones!", "Oh, those Jellybeans were for planting?!! But I'm hungry!"], 'boredom': ["I'm dying of boredom over here!", "You didn't think I understood you, huh?", 'Could we, like, DO something already?'], 'excitement': ["Wow, it's you, it's you, it's you!", 'mmm, Jellybeans, mmm!', 'Does it GET any better than this?', "Happy April Toons' Week!"], 'sadness': ["Don't go, Don't go, Don't go, Don't go, Don't go, Don't go, Don't go, Don't go, Don't go, Don't go, Don't go...", "I'll be good, I promise!", "I don't know WHY I'm sad, I just am!!!"], 'restlessness': ["I'm sooo restless!!!"], 'playfulness': ["Let's play, Let's play, Let's play, Let's play, Let's play, Let's play, Let's play, Let's play, Let's play...", 'Play with me or I dig up some flowers!', 'Lets run around and around and around and around and around and around...'], 'loneliness': ['Where have you been?', 'Wanna cuddle?', 'I want to go with you when you fight Cogs!'], 'fatigue': ['That swim in the pond really tired me out!', 'Being a Doodle is exhausting!', 'I gotta get to Dreamland!'], 'confusion': ['Where am I? Who are you again?', "What's a Toon-up again?", "Whoa, I'm standing between you and the Cogs! Run away!"], 'anger': ['... and you wonder why I never give you a Toon-up?!!!', 'You always leave me behind!', 'You love your gags more than you love me!'], 'surprise': ['Of course Doodles can talk!', 'Toons can talk?!!', 'Whoa, where did you come from?'], 'affection': ["You're the best Toon EVER!!!!!!!!!!", 'Do you even KNOW how great you are?!?', 'I am SO lucky to be with you!!!']} DialogQuestion = '?' FriendsListLabel = 'Friends' TeleportPanelOK = lOK TeleportPanelCancel = lCancel TeleportPanelYes = lYes TeleportPanelNo = lNo TeleportPanelCheckAvailability = 'Trying to go to %s.' TeleportPanelNotAvailable = '%s is busy right now; try again later.' TeleportPanelIgnored = '%s is ignoring you.' TeleportPanelNotOnline = "%s isn't online right now." TeleportPanelWentAway = '%s went away.' TeleportPanelUnknownHood = "You don't know how to get to %s!" TeleportPanelUnavailableHood = '%s is not available right now; try again later.' TeleportPanelDenySelf = "You can't go to yourself!" TeleportPanelOtherShard = "%(avName)s is in district %(shardName)s, and you're in district %(myShardName)s. Do you want to switch to %(shardName)s?" TeleportPanelBusyShard = '%(avName)s is in a full District. Playing in a full District can severely slow down game performance. Are you sure you want to switch districts?' TeleportPanelFullShard = 'That District is bursting with toons! You and your friend should move to a less busy one.' BattleBldgBossTaunt = "I'm the boss." CogdoBattleBldgBossTaunt = "I don't take meetings with Toons." FactoryBossTaunt = "I'm the Factory Foreman." FactoryBossBattleTaunt = 'Let me introduce you to the Factory Foreman.' MintBossTaunt = "I'm the Mint Supervisor." MintBossBattleTaunt = 'You need to talk to the Mint Supervisor.' StageBossTaunt = "I'm the District Attorney." StageBossBattleTaunt = "You need to talk to the District Attorney." CountryClubBossTaunt = "I'm the Club President." CountryClubBossBattleTaunt = 'You need to talk to the Club President.' ForcedLeaveCountryClubAckMsg = 'The Club President was defeated before you could reach him. You did not recover any Stock Options.' ToonHealJokes = [['What goes TICK-TICK-TICK-WOOF?', 'A watchdog! '], ['Why do male deer need braces?', "Because they have 'buck teeth'!"], ['Why is it hard for a ghost to tell a lie?', 'Because you can see right through him.'], ['What did the ballerina do when she hurt her foot?', 'She called the toe truck!'], ['What has one horn and gives milk?', 'A milk truck!'], ["Why don't witches ride their brooms when they're angry?", "They don't want to fly off the handle!"], ['Why did the dolphin cross the ocean?', 'To get to the other tide.'], ['What kind of mistakes do spooks make?', 'Boo boos.'], ['Why did the chicken cross the playground?', 'To get to the other slide!'], ['Where does a peacock go when he loses his tail?', 'A retail store.'], ["Why didn't the skeleton cross the road?", "He didn't have the guts."], ["Why wouldn't they let the butterfly into the dance?", 'Because it was a moth ball.'], ["What's gray and squirts jam at you?", 'A mouse eating a doughnut.'], ['What happened when 500 hares got loose on the main street?', 'The police had to comb the area.'], ["What's the difference between a fish and a piano?", "You can tune a piano, but you can't tuna fish!"], ['What do people do in clock factories?', 'They make faces all day.'], ['What do you call a blind dinosaur?', "An I-don't-think-he-saurus."], ['If you drop a white hat into the Red Sea, what does it become?', 'Wet.'], ['Why was Cinderella thrown off the basketball team?', 'She ran away from the ball.'], ['Why was Cinderella such a bad player?', 'She had a pumpkin for a coach.'], ["What two things can't you have for breakfast?", 'Lunch and dinner.'], ['What do you give an elephant with big feet?', 'Big shoes.'], ['Where do baby ghosts go during the day?', 'Day-scare centers.'], ['What did Snow White say to the photographer?', 'Some day my prints will come.'], ["What's Tarzan's favorite song?", 'Jungle bells.'], ["What's green and loud?", 'A froghorn.'], ["What's worse than raining cats and dogs?", 'Hailing taxis.'], ['When is the vet busiest?', "When it's raining cats and dogs."], ['What do you call a gorilla wearing ear-muffs?', "Anything you want, he can't hear you."], ['Where would you weigh a whale?', 'At a whale-weigh station.'], ['What travels around the world but stays in the corner?', 'A stamp.'], ['What do you give a pig with a sore throat?', 'Oinkment.'], ['What did the hat say to the scarf?', 'You hang around while I go on a head.'], ["What's the best parting gift?", 'A comb.'], ['What kind of cats like to go bowling?', 'Alley cats.'], ["What's wrong if you keep seeing talking animals?", "You're having Disney spells."], ['What did one eye say to the other?', 'Between you and me, something smells.'], ["What's round, white and giggles?", 'A tickled onion.'], ['What do you get when you cross Bambi with a ghost?', 'Bamboo.'], ['Why do golfers take an extra pair of socks?', 'In case they get a hole in one.'], ['What do you call a fly with no wings?', 'A walk.'], ['Who did Frankenstein take to the prom?', 'His ghoul friend.'], ['What lies on its back, one hundred feet in the air?', 'A sleeping centipede.'], ['How do you keep a bull from charging?', 'Take away his credit card.'], ['What do you call a chicken at the North Pole?', 'Lost.'], ['What do you get if you cross a cat with a dog?', 'An animal that chases itself.'], ['What did the digital watch say to the grandfather clock?', 'Look dad, no hands.'], ['Where does Ariel the mermaid go to see movies?', 'The dive-in.'], ['What do you call a mosquito with a tin suit?', 'A bite in shining armor.'], ['What do giraffes have that no other animal has?', 'Baby giraffes.'], ['Why did the man hit the clock?', 'Because the clock struck first.'], ['Why did the apple go out with a fig?', "Because it couldn't find a date."], ['What do you get when you cross a parrot with a monster?', 'A creature that gets a cracker whenever it asks for one.'], ["Why didn't the monster make the football team?", 'Because he threw like a ghoul!'], ['What do you get if you cross a Cocker Spaniel with a Poodle and a rooster?', 'A cockapoodledoo!'], ['What goes dot-dot-dash-dash-squeak?', 'Mouse code.'], ["Why aren't elephants allowed on beaches?", "They can't keep their trunks up."], ['What is at the end of everything?', 'The letter G.'], ['How do trains hear?', 'Through the engineers.'], ['What does the winner of a marathon lose?', 'His breath.'], ['Why did the pelican refuse to pay for his meal?', 'His bill was too big.'], ['What has six eyes but cannot see?', 'Three blind mice.'], ["What works only when it's fired?", 'A rocket.'], ["Why wasn't there any food left after the monster party?", 'Because everyone was a goblin!'], ['What bird can be heard at mealtimes?', 'A swallow.'], ['What goes Oh, Oh, Oh?', 'Santa walking backwards.'], ['What has green hair and runs through the forest?', 'Moldy locks.'], ['Where do ghosts pick up their mail?', 'At the ghost office.'], ['Why do dinosaurs have long necks?', 'Because their feet smell.'], ['What do mermaids have on toast?', 'Mermarlade.'], ['Why do elephants never forget?', 'Because nobody ever tells them anything.'], ["What's in the middle of a jellyfish?", 'A jellybutton.'], ['What do you call a very popular perfume?', 'A best-smeller.'], ["Why can't you play jokes on snakes?", 'Because you can never pull their legs.'], ['Why did the baker stop making donuts?', 'He got sick of the hole business.'], ['Why do mummies make excellent spies?', "They're good at keeping things under wraps."], ['How do you stop an elephant from going through the eye of a needle?', 'Tie a knot in its tail.'], ["What goes 'Ha Ha Ha Thud'?", 'Someone laughing his head off.'], ["My friend thinks he's a rubber band.", 'I told him to snap out of it.'], ["My sister thinks she's a pair of curtains.", 'I told her to pull herself together!'], ['Did you hear about the dentist that married the manicurist?', 'Within a month they were fighting tooth and nail.'], ['Why do hummingbirds hum?', "Because they don't know the words."], ['Why did the baby turkey bolt down his food?', 'Because he was a little gobbler.'], ['Where did the whale go when it was bankrupt?', 'To the loan shark.'], ['How does a sick sheep feel?', 'Baah-aahd.'], ["What's gray, weighs 10 pounds and squeaks?", 'A mouse that needs to go on a diet.'], ['Why did the dog chase his tail?', 'To make ends meet.'], ['Why do elephants wear running shoes?', 'For jogging of course.'], ['Why are elephants big and gray?', "Because if they were small and yellow they'd be canaries."], ['If athletes get tennis elbow what do astronauts get?', 'Missile toe.'], ['Did you hear about the man who hated Santa?', 'He suffered from Claustrophobia.'], ['Why did ' + Donald + ' sprinkle sugar on his pillow?', 'Because he wanted to have sweet dreams.'], ['Why did ' + Goofy + ' take his comb to the dentist?', 'Because it had lost all its teeth.'], ['Why did ' + Goofy + ' wear his shirt in the bath?', 'Because the label said wash and wear.'], ['Why did the dirty chicken cross the road?', 'For some fowl purpose.'], ["Why didn't the skeleton go to the party?", 'He had no body to go with.'], ['Why did the burglar take a shower?', 'To make a clean getaway.'], ['Why does a sheep have a woolly coat?', "Because he'd look silly in a plastic one."], ['Why do potatoes argue all the time?', "They can't see eye to eye."], ['Why did ' + Pluto + ' sleep with a banana peel?', 'So he could slip out of bed in the morning.'], ['Why did the mouse wear brown sneakers?', 'His white ones were in the wash.'], ['Why are false teeth like stars?', 'They come out at night.'], ['Why are Saturday and Sunday so strong?', 'Because the others are weekdays.'], ['Why did the archaeologist go bankrupt?', 'Because his career was in ruins.'], ['What do you get if you cross the Atlantic on the Titanic?', 'Very wet.'], ['What do you get if you cross a chicken with cement?', 'A brick-layer.'], ['What do you get if you cross a dog with a phone?', 'A golden receiver.'], ['What do you get if you cross an elephant with a shark?', 'Swimming trunks with sharp teeth.'], ['What did the tablecloth say to the table?', "Don't move, I've got you covered."], ['Did you hear about the time ' + Goofy + ' ate a candle?', 'He wanted a light snack.'], ['What did the balloon say to the pin?', 'Hi Buster.'], ['What did the big chimney say to the little chimney?', "You're too young to smoke."], ['What did the carpet say to the floor?', 'I got you covered.'], ['What did the necklace say to the hat?', "You go ahead, I'll hang around."], ['What goes zzub-zzub?', 'A bee flying backwards.'], ['How do you communicate with a fish?', 'Drop him a line.'], ["What do you call a dinosaur that's never late?", 'A prontosaurus.'], ['What do you get if you cross a bear and a skunk?', 'Winnie-the-phew.'], ['How do you clean a tuba?', 'With a tuba toothpaste.'], ['What do frogs like to sit on?', 'Toadstools.'], ['Why was the math book unhappy?', 'It had too many problems.'], ['Why was the school clock punished?', 'It tocked too much.'], ["What's a polygon?", 'A dead parrot.'], ['What needs a bath and keeps crossing the street?', 'A dirty double crosser.'], ['What do you get if you cross a camera with a crocodile?', 'A snap shot.'], ['What do you get if you cross an elephant with a canary?', 'A very messy cage.'], ['What do you get if you cross a jeweler with a plumber?', 'A ring around the bathtub.'], ['What do you get if you cross an elephant with a crow?', 'Lots of broken telephone poles.'], ['What do you get if you cross a plum with a tiger?', 'A purple people eater.'], ["What's the best way to save water?", 'Dilute it.'], ["What's a lazy shoe called?", 'A loafer.'], ["What's green, noisy and dangerous?", 'A thundering herd of cucumbers.'], ['What color is a shout?', 'Yellow!'], ['What do you call a sick duck?', 'A mallardy.'], ["What's worse then a giraffe with a sore throat?", "A centipede with athlete's foot."], ['What goes ABC...slurp...DEF...slurp?', 'Someone eating alphabet soup.'], ["What's green and jumps up and down?", 'Lettuce at a dance.'], ["What's a cow after she gives birth?", 'De-calf-inated.'], ['What do you get if you cross a cow and a camel?', 'Lumpy milk shakes.'], ["What's white with black and red spots?", 'A Dalmatian with measles.'], ["What's brown has four legs and a trunk?", 'A mouse coming back from vacation.'], ["What does a skunk do when it's angry?", 'It raises a stink.'], ["What's gray, weighs 200 pounds and says, Here Kitty, kitty?", 'A 200 pound mouse.'], ["What's the best way to catch a squirrel?", 'Climb a tree and act like a nut.'], ["What's the best way to catch a rabbit?", 'Hide in a bush and make a noise like lettuce.'], ['What do you call a spider that just got married?', 'A newly web.'], ['What do you call a duck that robs banks?', 'A safe quacker.'], ["What's furry, meows and chases mice underwater?", 'A catfish.'], ["What's a funny egg called?", 'A practical yolker.'], ["What's green on the outside and yellow inside?", 'A banana disguised as a cucumber.'], ['What did the elephant say to the lemon?', "Let's play squash."], ['What weighs 4 tons, has a trunk and is bright red?', 'An embarrassed elephant.'], ["What's gray, weighs 4 tons, and wears glass slippers?", 'Cinderelephant.'], ["What's an elephant in a fridge called?", 'A very tight squeeze.'], ['What did the elephant say to her naughty child?', 'Tusk! Tusk!'], ['What did the peanut say to the elephant?', "Nothing -- Peanuts can't talk."], ['What do elephants say when they bump into each other?', "Small world, isn't it?"], ['What did the cashier say to the register?', "I'm counting on you."], ['What did the flea say to the other flea?', 'Shall we walk or take the cat?'], ['What did the big hand say to the little hand?', 'Got a minute.'], ['What does the sea say to the sand?', 'Not much. It usually waves.'], ['What did the stocking say to the shoe?', 'See you later, I gotta run.'], ['What did one tonsil say to the other tonsil?', 'It must be spring, here comes a swallow.'], ['What did the soil say to the rain?', 'Stop, or my name is mud.'], ['What did the puddle say to the rain?', 'Drop in sometime.'], ['What did the bee say to the rose?', 'Hi, bud.'], ['What did the appendix say to the kidney?', "The doctor's taking me out tonight."], ['What did the window say to the venetian blinds?', "If it wasn't for you it'd be curtains for me."], ['What did the doctor say to the sick orange?', 'Are you peeling well?'], ['What do you get if you cross a chicken with a banjo?', 'A self-plucking chicken.'], ['What do you get if you cross a hyena with a bouillon cube?', 'An animal that makes a laughing stock of itself.'], ['What do you get if you cross a rabbit with a spider?', 'A hare net.'], ['What do you get if you cross a germ with a comedian?', 'Sick jokes.'], ['What do you get if you cross a hyena with a mynah bird?', 'An animal that laughs at its own jokes.'], ['What do you get if you cross a railway engine with a stick of gum?', 'A chew-chew train.'], ['What would you get if you crossed an elephant with a computer?', 'A big know-it-all.'], ['What would you get if you crossed an elephant with a skunk?', 'A big stinker.'], ['Why did ' + MickeyMouse + ' take a trip to outer space?', 'He wanted to find ' + Pluto + '.']] MovieHealLaughterMisses = ('hmm', 'heh', 'ha', 'harr harr') MovieHealLaughterHits1 = ('Ha Ha Ha', 'Hee Hee', 'Tee Hee', 'Ha Ha') MovieHealLaughterHits2 = ('BWAH HAH HAH!', 'HO HO HO!', 'HA HA HA!') MovieSOSCallHelp = '%s HELP!' MovieSOSWhisperHelp = '%s needs help in battle!' MovieSOSObserverHelp = 'HELP!' MovieNPCSOSGreeting = 'Hi %s! Glad to help!' MovieNPCSOSGoodbye = 'See you later!' MovieNPCSOSToonsHit = 'Toons Always Hit!' MovieNPCSOSCogsMiss = 'Cogs Always Miss!' MovieNPCSOSRestockGags = 'Restocking %s gags!' MovieNPCSOSHeal = 'Heal' MovieNPCSOSTrap = 'Trap' MovieNPCSOSLure = 'Lure' MovieNPCSOSSound = 'Sound' MovieNPCSOSThrow = 'Throw' MovieNPCSOSSquirt = 'Squirt' MovieNPCSOSDrop = 'Drop' MovieNPCSOSZap = 'Push' MovieNPCSOSAll = 'All' MoviePetSOSTrickFail = 'Sigh' MoviePetSOSTrickSucceedBoy = 'Good boy!' MoviePetSOSTrickSucceedGirl = 'Good girl!' MovieSuitCancelled = 'CANCELLED\nCANCELLED\nCANCELLED' RewardPanelToonTasks = 'ToonTasks' RewardPanelItems = 'Items Recovered' RewardPanelMissedItems = 'Items Not Recovered' RewardPanelQuestLabel = 'Quest %s' RewardPanelCongratsStrings = ['Yeah!', 'Congratulations!', 'Wow!', 'Cool!', 'Awesome!', 'Toon-tastic!'] RewardPanelNewGag = 'New %(gagName)s gag for %(avName)s!' RewardPanelUberGag = '%(avName)s earned the %(gagName)s gag with %(exp)s experience points!' RewardPanelEndTrack = 'Yay! %(avName)s has reached the end of the %(gagName)s Gag Track!' RewardPanelMeritsMaxed = 'Maxed' RewardPanelMeritBarLabels = ['Stock Options', 'Jury Notices', 'Cogbucks', 'Merits'] RewardPanelMeritAlert = 'Ready for promotion!' RewardPanelCogPart = 'You gained a Cog disguise part!' RewardPanelPromotion = 'Ready for promotion in %s track!' RewardPanelSkip = 'Skip' CheesyEffectDescriptions = [('Normal Toon', 'you will be normal'), ('Big head', 'you will have a big head'), ('Small head', 'you will have a small head'), ('Big legs', 'you will have big legs'), ('Small legs', 'you will have small legs'), ('Big toon', 'you will be a little bigger'), ('Small toon', 'you will be a little smaller'), ('Flat portrait', 'you will be two-dimensional'), ('Flat profile', 'you will be two-dimensional'), ('Transparent', 'you will be transparent'), ('No color', 'you will be colorless'), ('Invisible toon', 'you will be invisible')] CheesyEffectIndefinite = 'Until you choose another effect, %(effectName)s%(whileIn)s.' CheesyEffectMinutes = 'For the next %(time)s minutes, %(effectName)s%(whileIn)s.' CheesyEffectHours = 'For the next %(time)s hours, %(effectName)s%(whileIn)s.' CheesyEffectDays = 'For the next %(time)s days, %(effectName)s%(whileIn)s.' CheesyEffectWhileYouAreIn = ' while you are in %s' CheesyEffectExceptIn = ', except in %s' SuitFlunky = 'Flunky' SuitPencilPusher = 'Pencil Pusher' SuitYesman = 'Yesman' SuitMicromanager = 'Micro\x03manager' SuitDownsizer = 'Downsizer' SuitHeadHunter = 'Head Hunter' SuitCorporateRaider = 'Corporate Raider' SuitTheBigCheese = 'The Big Cheese' SuitColdCaller = 'Cold Caller' SuitTelemarketer = 'Tele\x03marketer' SuitNameDropper = 'Name Dropper' SuitGladHander = 'Glad Hander' SuitMoverShaker = 'Mover & Shaker' SuitTwoFace = 'Two-Face' SuitTheMingler = 'The Mingler' SuitMrHollywood = 'Mr. Hollywood' SuitShortChange = 'Short Change' SuitPennyPincher = 'Penny Pincher' SuitTightwad = 'Tightwad' SuitBeanCounter = 'Bean Counter' SuitNumberCruncher = 'Number Cruncher' SuitMoneyBags = 'Money Bags' SuitLoanShark = 'Loan Shark' SuitRobberBaron = 'Robber Baron' SuitConArtist = 'Penis Muncher' SuitConnoisseur = 'Door to Door Salesman' SuitSwindler = 'Camera Head' SuitMiddleman = 'Assfucker' SuitToxicManager = 'Viral Marketer' SuitMagnate = 'Cog Cart' SuitBigFish = 'Foreign Marketer' SuitHeadHoncho = 'Search Engine' SuitBottomFeeder = 'Bottom Feeder' SuitBloodsucker = 'Blood\x03sucker' SuitDoubleTalker = 'Double Talker' SuitAmbulanceChaser = 'Ambulance Chaser' SuitBackStabber = 'Back Stabber' SuitSpinDoctor = 'Spin Doctor' SuitLegalEagle = 'Legal Eagle' SuitBigWig = 'Big Wig' SuitFlunkyS = 'a Flunky' SuitPencilPusherS = 'a Pencil Pusher' SuitYesmanS = 'a Yesman' SuitMicromanagerS = 'a Micromanager' SuitDownsizerS = 'a Downsizer' SuitHeadHunterS = 'a Head Hunter' SuitCorporateRaiderS = 'a Corporate Raider' SuitTheBigCheeseS = 'a Big Cheese' SuitColdCallerS = 'a Cold Caller' SuitTelemarketerS = 'a Telemarketer' SuitNameDropperS = 'a Name Dropper' SuitGladHanderS = 'a Glad Hander' SuitMoverShakerS = 'a Mover & Shaker' SuitTwoFaceS = 'a Two-Face' SuitTheMinglerS = 'a Mingler' SuitMrHollywoodS = 'a Mr. Hollywood' SuitShortChangeS = 'a Short Change' SuitPennyPincherS = 'a Penny Pincher' SuitTightwadS = 'a Tightwad' SuitBeanCounterS = 'a Bean Counter' SuitNumberCruncherS = 'a Number Cruncher' SuitMoneyBagsS = 'a Money Bags' SuitLoanSharkS = 'a Loan Shark' SuitRobberBaronS = 'a Robber Baron' SuitConArtistS = 'a Penis Muncher' SuitConnoisseurS = 'a Door to Door Salesman' SuitSwindlerS = 'a Camera Head' SuitMiddlemanS = 'an Assfucker' SuitToxicManagerS = 'a Viral Marketer' SuitMagnateS = 'a Cog Cart' SuitBigFishS = 'a Foreign Marketer' SuitHeadHonchoS = 'a Search Engine' SuitBottomFeederS = 'a Bottom Feeder' SuitBloodsuckerS = 'a Bloodsucker' SuitDoubleTalkerS = 'a Double Talker' SuitAmbulanceChaserS = 'an Ambulance Chaser' SuitBackStabberS = 'a Back Stabber' SuitSpinDoctorS = 'a Spin Doctor' SuitLegalEagleS = 'a Legal Eagle' SuitBigWigS = 'a Big Wig' SuitFlunkyP = 'Flunkies' SuitPencilPusherP = 'Pencil Pushers' SuitYesmanP = 'Yesmen' SuitMicromanagerP = 'Micromanagers' SuitDownsizerP = 'Downsizers' SuitHeadHunterP = 'Head Hunters' SuitCorporateRaiderP = 'Corporate Raiders' SuitTheBigCheeseP = 'Big Cheeses' SuitColdCallerP = 'Cold Callers' SuitTelemarketerP = 'Telemarketers' SuitNameDropperP = 'Name Droppers' SuitGladHanderP = 'Glad Handers' SuitMoverShakerP = 'Movers & Shakers' SuitTwoFaceP = 'Two-Faces' SuitTheMinglerP = 'Minglers' SuitMrHollywoodP = 'Mr. Hollywoods' SuitShortChangeP = 'Short Changes' SuitPennyPincherP = 'Penny Pinchers' SuitTightwadP = 'Tightwads' SuitBeanCounterP = 'Bean Counters' SuitNumberCruncherP = 'Number Crunchers' SuitMoneyBagsP = 'Money Bags' SuitLoanSharkP = 'Loan Sharks' SuitRobberBaronP = 'Robber Barons' SuitConArtistP = 'Penis Munchers' SuitConnoisseurP = 'Door to Door Salesmen' SuitSwindlerP = 'Camera Heads' SuitMiddlemanP = 'Assfuckers' SuitToxicManagerP = 'Viral Marketers' SuitMagnateP = 'Cog Carts' SuitBigFishP = 'Foreign Marketers' SuitHeadHonchoP = 'Search Engines' SuitBottomFeederP = 'Bottom Feeders' SuitBloodsuckerP = 'Bloodsuckers' SuitDoubleTalkerP = 'Double Talkers' SuitAmbulanceChaserP = 'Ambulance Chasers' SuitBackStabberP = 'Back Stabbers' SuitSpinDoctorP = 'Spin Doctors' SuitLegalEagleP = 'Legal Eagles' SuitBigWigP = 'Big Wigs' SuitFaceoffDefaultTaunts = ['Boo!'] SuitAttackDefaultTaunts = ['Take that!', 'Take a memo on this!'] SuitAttackNames = {'Audit': 'Audit!', 'Bite': 'Bite!', 'BounceCheck': 'Bounce Check!', 'BrainStorm': 'Brain Storm!', 'BuzzWord': 'Buzz Word!', 'Calculate': 'Calculate!', 'Canned': 'Canned!', 'Chomp': 'Chomp!', 'CigarSmoke': 'Cigar Smoke!', 'ClipOnTie': 'Clip On Tie!', 'Crunch': 'Crunch!', 'Demotion': 'Demotion!', 'Downsize': 'Downsize!', 'DoubleTalk': 'Double Talk!', 'EvictionNotice': 'Eviction Notice!', 'EvilEye': 'Evil Eye!', 'Filibuster': 'Filibuster!', 'FillWithLead': 'Fill With Lead!', 'FiveOClockShadow': "Five O'Clock Shadow!", 'FingerWag': 'Finger Wag!', 'Fired': 'Fired!', 'FloodTheMarket': 'Flood The Market!', 'FountainPen': 'Fountain Pen!', 'FreezeAssets': 'Freeze Assets!', 'Gavel': 'Gavel!', 'GlowerPower': 'Glower Power!', 'GuiltTrip': 'Guilt Trip!', 'HalfWindsor': 'Half Windsor!', 'HangUp': 'Hang Up!', 'HeadShrink': 'Head Shrink!', 'HotAir': 'Hot Air!', 'Jargon': 'Jargon!', 'Legalese': 'Legalese!', 'Liquidate': 'Liquidate!', 'MarketCrash': 'Market Crash!', 'MumboJumbo': 'Mumbo Jumbo!', 'ParadigmShift': 'Paradigm Shift!', 'PeckingOrder': 'Pecking Order!', 'PickPocket': 'Pick Pocket!', 'PinkSlip': 'Pink Slip!', 'PlayHardball': 'Play Hardball!', 'PoundKey': 'Pound Key!', 'PowerTie': 'Power Tie!', 'PowerTrip': 'Power Trip!', 'Quake': 'Quake!', 'RazzleDazzle': 'Razzle Dazzle!', 'RedTape': 'Red Tape!', 'ReOrg': 'Re-Org!', 'RestrainingOrder': 'Restraining Order!', 'Rolodex': 'Rolodex!', 'RubberStamp': 'Rubber Stamp!', 'RubOut': 'Rub Out!', 'Sacked': 'Sacked!', 'SandTrap': 'Sand Trap!', 'Schmooze': 'Schmooze!', 'Shake': 'Shake!', 'Shred': 'Shred!', 'SongAndDance': 'Song And Dance!', 'Spin': 'Spin!', 'Synergy': 'Synergy!', 'Tabulate': 'Tabulate!', 'TeeOff': 'Tee Off!', 'ThrowBook': 'Throw Book!', 'Tremor': 'Tremor!', 'Watercooler': 'Watercooler!', 'Withdrawal': 'Withdrawal!', 'WriteOff': 'Write Off!', 'Overdraft': 'Overdraft!'} SuitAttackTaunts = {'Audit': ["I believe your books don't balance.", "Looks like you're in the red.", 'Let me help you with your books.', 'Your debit column is much too high.', "Let's check your assets.", 'This will put you in debt.', "Let's take a close look at what you owe.", 'This should drain your account.', 'Time for you to account for your expenses.', "I've found an error in your books."], 'Bite': ['Would you like a bite?', 'Try a bite of this!', "You're biting off more than you can chew.", 'My bite is bigger than my bark.', 'Bite down on this!', 'Watch out, I may bite.', "I don't just bite when I'm cornered.", "I'm just gonna grab a quick bite.", "I haven't had a bite all day.", 'I just want a bite. Is that too much to ask?'], 'BounceCheck': ["Ah, too bad, you're funless.", 'You have a payment due.', 'I believe this check is yours.', 'You owed me for this.', "I'm collecting on this debt.", "This check isn't going to be tender.", "You're going to be charged for this.", 'Check this out.', 'This is going to cost you.', "I'd like to cash this in.", "I'm just going to kick this back to you.", 'This is one sour note.', "I'm deducting a service charge."], 'BrainStorm': ['I forecast rain.', 'Hope you packed your umbrella.', 'I want to enlighten you.', 'How about a few rain DROPS?', 'Not so sunny now, are you Toon?', 'Ready for a down pour?', "I'm going to take you by storm.", 'I call this a lightning attack.', 'I love to be a wet blanket.'], 'BuzzWord': ['Pardon me if I drone on.', 'Have you heard the latest?', 'Can you catch on to this?', 'See if you can hum this Toon.', 'Let me put in a good word for you.', 'I\'ll "B" perfectly clear.', 'You should "B" more careful.', 'See if you can dodge this swarm.', "Careful, you're about to get stung.", 'Looks like you have a bad case of hives.'], 'Calculate': ['These numbers do add up!', 'Did you count on this?', "Add it up, you're going down.", 'Let me help you add this up.', 'Did you register all your expenses?', "According to my calculations, you won't be around much longer.", "Here's the grand total.", 'Wow, your bill is adding up.', 'Try fiddling with these numbers!', Cogs + ': 1 Toons: 0'], 'Canned': ['Do you like it out of the can?', '"Can" you handle this?', "This one's fresh out of the can!", 'Ever been attacked by canned goods before?', "I'd like to donate this canned good to you!", 'Get ready to "Kick the can"!', 'You think you "can", you think you "can".', "I'll throw you in the can!", "I'm making me a can o' toon-a!", "You don't taste so good out of the can."], 'Chomp': ['Take a look at these chompers!', 'Chomp, chomp, chomp!', "Here's something to chomp on.", 'Looking for something to chomp on?', "Why don't you chomp on this?", "I'm going to have you for dinner.", 'I love to feed on Toons!'], 'CigarSmoke': ['Gentlemen.', "It's a good day for me to have a smoke.", 'Take a breath of this.', "It's tradition you know.", 'Another day, another dollar spent.', 'I always have the occasional cigar.', "I'll quit tomorrow, I swear.", "You can't even escape my secondhand smoke.", 'These fumes are toxic.', 'I need a good smoke.', 'Smoking is a dirty habit.'], 'ClipOnTie': ['Better dress for our meeting.', "You can't go OUT without your tie.", 'The best dressed ' + Cogs + ' wear them.', 'Try this on for size.', 'You should dress for success.', 'No tie, no service.', 'Do you need help putting this on?', 'Nothing says powerful like a good tie.', "Let's see if this fits.", 'This is going to choke you up.', "You'll want to dress up before you go OUT.", "I think I'll tie you up."], 'Crunch': ["Looks like you're in a crunch.", "It's crunch time!", "I'll give you something to crunch on!", 'Crunch on this!', 'I pack quite a crunch.', 'Which do you prefer, smooth or crunchy?', "I hope you're ready for crunch time.", "It sounds like you're getting crunched!", "I'll crunch you like a can."], 'Demotion': ["You're moving down the corporate ladder.", "I'm sending you back to the Mail Room.", 'Time to turn in your nameplate.', "You're going down, clown.", "Looks like you're stuck.", "You're going nowhere fast.", "You're in a dead end position.", "You won't be moving anytime soon.", "You're not going anywhere.", 'This will go on your permanent record.'], 'Downsize': ['Come on down!', 'Do you know how to get down?', "Let's get down to business.", "What's wrong? You look down.", 'Going down?', "What's goin' down? You!", 'Why pick on people my own size?', "Why don't I size you up, or should I say, down?", 'Would you like a smaller size for just a quarter more?', 'Try this on for size!', 'You can get this in a smaller size.', 'This attack is one size fits all!'], 'EvictionNotice': ["It's moving time.", 'Pack your bags, Toon.', 'Time to make some new living arrangements.', 'Consider yourself served.', "You're behind on your lease.", 'This will be extremely unsettling.', "You're about to be uprooted.", "I'm going to send you packing.", "You're out of place.", 'Prepare to be relocated.', "You're in a hostel position."], 'EvilEye': ["I'm giving you the evil eye.", 'Could you eye-ball this for me?', "Wait. I've got something in my eye.", "I've got my eye on you!", 'Could you keep an eye on this for me?', "I've got a real eye for evil.", "I'll poke you in the eye!", '"Eye" am as evil as they come!', "I'll put you in the eye of the storm!", "I'm rolling my eye at you."], 'Filibuster': ["Shall I fill 'er up?", 'This is going to take awhile.', 'I could do this all day.', "I don't even need to take a breath.", 'I keep going and going and going.', 'I never get tired of this one.', 'I can talk a blue streak.', 'Mind if I bend your ear?', "I think I'll shoot the breeze.", 'I can always get a word in edgewise.'], 'FingerWag': ['I have told you a thousand times.', 'Now see here Toon.', "Don't make me laugh.", "Don't make me come over there.", "I'm tired of repeating myself.", "I believe we've been over this.", 'You have no respect for us ' + Cogs + '.', "I think it's time you pay attention.", 'Blah, Blah, Blah, Blah, Blah.', "Don't make me stop this meeting.", 'Am I going to have to separate you?', "We've been through this before."], 'Fired': ['I hope you brought some marshmallows.', "It's going to get rather warm around here.", 'This should take the chill out of the air.', "I hope you're cold blooded.", 'Hot, hot and hotter.', 'You better stop, drop, and roll!', "You're outta here.", 'How does "well-done" sound?', 'Can you say ouch?', 'Hope you wore sunscreen.', 'Do you feel a little toasty?', "You're going down in flames.", "You'll go out in a blaze.", "You're a flash in the pan.", 'I think I have a bit of a flare about me.', "I just sparkle, don't I?", 'Oh look, a crispy critter.', "You shouldn't run around half baked."], 'FountainPen': ['This is going to leave a stain.', "Let's ink this deal.", 'Be prepared for some permanent damage.', "You're going to need a good dry cleaner.", 'You should change.', 'This fountain pen has such a nice font.', "Here, I'll use my pen.", 'Can you read my writing?', 'I call this the plume of doom.', "There's a blot on your performance.", "Don't you hate when this happens?"], 'FreezeAssets': ['Your assets are mine.', 'Do you feel a draft?', "Hope you don't have plans.", 'This should keep you on ice.', "There's a chill in the air.", 'Winter is coming early this year.', 'Are you feeling a little blue?', 'Let me crystallize my plan.', "You're going to take this hard.", 'This should cause freezer burn.', 'I hope you like cold cuts.', "I'm very cold blooded."], 'GlowerPower': ['You looking at me?', "I'm told I have very piercing eyes.", 'I like to stay on the cutting edge.', "Jeepers, Creepers, don't you love my peepers?", "Here's looking at you kid.", "How's this for expressive eyes?", 'My eyes are my strongest feature.', 'The eyes have it.', 'Peeka-boo, I see you.', 'Look into my eyes...', 'Shall we take a peek at your future?'], 'GuiltTrip': ["I'll lay a real guilt trip on you!", 'Feeling guilty?', "It's all your fault!", 'I always blame everything on you.', 'Wallow in your own guilt!', 'Did you have a nice trip?', "You had better say you're sorry.", "I wouldn't forgive you in a million years!", 'See you next fall.', 'Call me when you get back from your trip.', 'When do you get back from your trip?'], 'HalfWindsor': ["This is the fanciest tie you'll ever see!", 'Try not to get too winded.', "This isn't even half the trouble you're in.", "You're lucky I don't have a whole windsor.", "You can't afford this tie.", "I bet you've never even SEEN a half windsor!", 'This tie is out of your league.', "I shouldn't even waste this tie on you.", "You're not even worth half of this tie!"], 'HangUp': ["You've been disconnected.", 'Good bye!', "It's time I end our connection.", "...and don't call back!", 'Click!', 'This conversation is over.', "I'm severing this link.", 'I think you have a few hang ups.', "It appears you've got a weak link.", 'Your time is up.', 'I hope you receive this loud and clear.', 'You got the wrong number.'], 'HeadShrink': ["Looks like you're seeing a shrink.", 'Honey, I shrunk the toon.', "Hope this doesn't shrink your pride.", 'Do you shrink in the wash?', 'I shrink therefore I am.', "It's nothing to lose your head over.", 'Are you going out of your head?', 'Heads up! Or should I say, down.', 'Objects may be larger than they appear.', 'Good Toons come in small packages.'], 'HotAir': ["We're having a heated discussion.", "You're experiencing a heat wave.", "I've reached my boiling point.", 'This should cause some wind burn.', 'I hate to grill you, but...', "Always remember, where there's smoke, there's fire.", "You're looking a little burned out.", 'Another meeting up in smoke.', "Guess it's time to add fuel to the fire.", 'Let me kindle a working relationship.', 'I have some glowing remarks for you.', 'Air Raid!!!'], 'Jargon': ['What nonsense.', 'See if you can make sense of this.', 'I hope you get this loud and clear.', "Looks like I'm going to have to raise my voice.", 'I insist on having my say.', "I'm very outspoken.", 'I must pontificate on this subject.', 'See, words can hurt you.', 'Did you catch my meaning?', 'Words, words, words, words, words.'], 'Legalese': ['You must cease and desist.', 'You will be defeated, legally speaking.', 'Are you aware of the legal ramifications?', "You aren't above the law!", 'There should be a law against you.', "There's no ex post facto with me!", "The opinions expressed in this attack are not those of Town Toon Wacky Silly 3.", 'We cannot be held responsible for damages suffered in this attack.', 'Your results for this attack may vary.', 'This attack is void where prohibited.', "You don't fit into my legal system!", "You can't handle the legal matters."], 'Liquidate': ['I like to keep things fluid.', 'Are you having some cash flow problems?', "I'll have to purge your assets.", 'Time for you to go with the flow.', "Remember it's slippery when wet.", 'Your numbers are running.', 'You seem to be slipping.', "It's all crashing down on you.", "I think you're diluted.", "You're all washed up."], 'MarketCrash': ["I'm going to crash your party.", "You won't survive the crash.", "I'm more than the market can bear.", "I've got a real crash course for you!", "Now I'll come crashing down.", "I'm a real bull in the market.", 'Looks like the market is going down.', 'You had better get out quick!', 'Sell! Sell! Sell!', 'Shall I lead the recession?', "Everybody's getting out, shouldn't you?"], 'MumboJumbo': ['Let me make this perfectly clear.', "It's as simple as this.", "This is how we're going to do this.", 'Let me supersize this for you.', 'You might call this technobabble.', 'Here are my five-dollar words.', 'Boy, this is a mouth full.', 'Some call me bombastic.', 'Let me just interject this.', 'I believe these are the right words.'], 'ParadigmShift': ["Watch out! I'm rather shifty.", 'Prepare to have your paradigm shifted!', "Isn't this an interesting paradigm.", "You'll get shifted out of place.", "I guess it's your shift now.", 'Your shift is up!', "You've never shifted this much in your life.", "I'm giving you the bad shift!", 'Look into my shifty eyes!'], 'PeckingOrder': ["This one's for the birds.", 'Get ready for a bird bath.', "Looks like you're going to hit a birdie.", 'Some think this attack is fowl.', "You're on the bottom of the pecking order.", 'A bird in my hand is worth ten on your head!', 'Your order is up; the pecking order!', "Why don't I peck on someone my own size? Nah.", 'Birds of a feather strike together.'], 'PickPocket': ['Let me check your valuables.', "Hey, what's that over there?", 'Like taking candy from a baby.', 'What a steal.', "I'll hold this for you.", 'Watch my hands at all times.', 'The hand is quicker than the eye.', "There's nothing up my sleeve.", 'The management is not responsible for lost items.', "Finder's keepers.", "You'll never see it coming.", 'One for me, none for you.', "Don't mind if I do.", "You won't be needing this..."], 'PinkSlip': ['Try not to slip up.', "Are you frightened? You've turned pink!", 'This one will surely slip you up.', 'Oops, I guess you slipped there, huh?', "Watch yourself, wouldn't want to slip!", "This one's slippery when wet.", "I'll just slip this one in.", "Don't mind if you slip by, do you?", "Pink isn't really your color.", "Here's your pink slip, you're outta here!"], 'PlayHardball': ['So you wanna play hardball?', "You don't wanna play hardball with me.", 'Batter up!', 'Hey batter, batter!', "And here's the pitch...", "You're going to need a relief pitcher.", "I'm going to knock you out of the park.", "Once you get hit, you'll run home.", 'This is your final inning!', "You can't play with me!", "I'll strike you out.", "I'm throwing you a real curve ball!"], 'PoundKey': ['Time to return some calls.', "I'd like to make a collect call.", "Ring-a-ling - it's for you!", "I've been wanting to drop a pound or two.", 'I have a lot of clout.', 'This may cause a slight pounding sensation.', "I'll just punch in this number.", 'Let me call up a little surprise.', "I'll ring you up.", "O.K. Toon, it's the pound for you."], 'PowerTie': ["I'll call later, you looked tied up.", 'Are you ready to tie die?', "Ladies and gentlemen, it's a tie!", 'You had better learn how to tie.', "I'll have you tongue-tied!", "This is the worst tie you'll ever get!", 'Can you feel the power?', 'My powers are far too great for you!', "I've got the power!", "By the powers vested in me, I'll tie you up."], 'PowerTrip': ["Pack your bags, we're taking a little trip.", 'Did you have a nice trip?', "Nice trip, I guess I'll see you next fall.", 'How was your trip?', 'Sorry to trip you up there!', 'You look a little tripped up.', "Now you see who's in power!", 'I am much more powerful than you.', "Who's got the power now?", "You can't fight the power.", 'Power corrupts, especially in my hands!'], 'Quake': ["Let's quake, rattle, and roll.", "I've got a whole lot of quakin' goin' on!", "I see you quakin' in your shoes.", "Here it comes, it's the big one!", "This one's off the Richter scale.", 'Now the earth will quake!', "Hey, what's shakin'? You!", 'Ever been in an earthquake?', "You're on shaky ground now!"], 'RazzleDazzle': ['Read my lips.', 'How about these choppers?', "Aren't I charming?", "I'm going to wow you.", 'My dentist does excellent work.', "Blinding aren't they?", "Hard to believe these aren't real.", "Shocking, aren't they?", "I'm going to cap this off.", 'I floss after every meal.', 'Say Cheese!'], 'RedTape': ['This should wrap things up.', "I'm going to tie you up for awhile.", "You're on a roll.", 'See if you can cut through this.', 'This will get sticky.', "Hope you're claustrophobic.", "I'll make sure you stick around.", 'Let me keep you busy.', 'Just try to unravel this.', 'I want this meeting to stick with you.'], 'ReOrg': ["You don't like the way I reorganized things!", 'Perhaps a little reorganization is in order.', "You're not that bad, you just need to be reorganized.", 'Do you like my organizational skills.', "I just thought I'd give things a new look.", 'You need to get organized!', "You're looking a little disorganized.", 'Hold on while I reorganize your thoughts.', "I'll just wait for you to get a little organized.", "You don't mind if I just reorganize a bit?"], 'RestrainingOrder': ['You should show a little restraint.', "I'm slapping you with a restraining order!", "You can't come within five feet of me.", 'Perhaps you better keep your distance.', 'You should be restrained.', Cogs + '! Restrain that Toon!', 'Try and restrain yourself.', "I hope I'm being too much of a restraint on you.", 'See if you can lift these restraints!', "I'm ordering you to restrain!", "Why don't we start with basic restraining?"], 'Rolodex': ["Your card's in here somewhere.", "Here's the number for a pest exterminator.", 'I want to give you my card.', "I've got your number right here.", "I've got you covered from a-z.", "You'll flip over this.", 'Take this for a spin.', 'Watch out for paper cuts.', "I'll let my fingers do the knocking.", 'Is this how I can contact you?', 'I want to make sure we stay in touch.'], 'RubberStamp': ['I always make a good impression.', "It's important to apply firm and even pressure.", 'A perfect imprint every time.', 'I want to stamp you out.', 'You must be RETURNED TO SENDER.', "You've been CANCELLED.", 'You have a PRIORITY delivery.', "I'll make sure you RECEIVED my message.", "You're not going anywhere - you have POSTAGE DUE.", "I'll need a response ASAP."], 'RubOut': ['And now for my disappearing act.', "I sense I've lost you somewhere.", 'I decided to leave you out.', 'I always rub out all obstacles.', "I'll just erase this error.", 'I can make any nuisance disappear.', 'I like things neat and tidy.', 'Please try and stay animated.', "Now I see you... now I don't.", 'This will cause some fading.', "I'm going to eliminate the problem.", 'Let me take care of your problem areas.'], 'Sacked': ["Looks like you're getting sacked.", "This one's in the bag.", "You've been bagged.", 'Paper or plastic?', 'My enemies shall be sacked!', 'I hold the Toontown record in sacks per game.', "You're no longer wanted around here.", "Your time is up around here, you're being sacked!", 'Let me bag that for you.', 'No defense can match my sack attack!'], 'Schmooze': ["You'll never see this coming.", 'This will look good on you.', "You've earned this.", "I don't mean to gush.", 'Flattery will get me everywhere.', "I'm going to pile it on now.", 'Time to lay it on thick.', "I'm going to get on your good side.", 'That deserves a good slap on the back.', "I'm going to ring your praises.", 'I hate to knock you off your pedestal, but...'], 'Shake': ["You're right on the epicenter.", "You're standing on a fault line.", "It's going to be a bumpy ride.", 'I think of this as a natural disaster.', "It's a disaster of seismic proportions.", "This one's off the Richter scale.", 'Time to duck and cover.', 'You seem disturbed.', 'Ready for a jolt?', "I'll have you shaken, not stirred.", 'This will shake you up.', 'I suggest a good escape plan.'], 'Shred': ['I need to get rid of some hazardous waste.', "I'm increasing my throughput.", "I think I'll dispose of you right now.", 'This will get rid of the evidence.', "There's no way to prove it now.", 'See if you can put this back together.', 'This should cut you down to size.', "I'm going to rip that idea to shreds.", "We don't want this to fall into the wrong hands.", 'Easy come, easy go.', "Isn't this your last shred of hope?"], 'SongAndDance': ['Whoa whoa whoa...', 'This maybe cringe-worthy ...', "Try not to cringe.", "Think of this as a dance to the death.", "It's like dreaming with your feet.", 'Never miss a chance to dance!', 'When you feel sad, dance!', 'I never dance to forget.'], 'Spin': ['What do you say we go for a little spin?', 'Do you use the spin cycle?', "This'll really make your head spin!", "Here's my spin on things.", "I'll take you for a spin.", 'How do you like to "spin" your time?', "Watch it. Wouldn't want to spin out of control!", "Oh what a spin you're in!", 'My attacks will make your head spin!'], 'Synergy': ["I'm taking this to committee.", "Your project's been cancelled.", "Your budget's been cut.", "We're restructuring your division.", 'I put it to a vote, and you lose.', 'I just received the final approval.', 'A good team can get rid of any problem.', "I'll get back to you on this.", "Let's get right to business.", 'Consider this a Synergy crisis.'], 'Tabulate': ["This doesn't add up.", 'By my count, you lose.', "You're racking up quite a tab.", "I'll have you totaled in a moment.", 'Are you ready for these numbers?', 'Your bill is now due and payable.', 'Time for the reckoning.', 'I like to put things in order.', 'And the tally is...', 'These numbers should prove to be quite powerful.'], 'TeeOff': ["You're not up to par.", 'Fore!', "I'm getting teed off.", "Caddie, I'll need my driver!", 'Just try and avoid this hazard.', 'Swing!', 'This is a sure hole in one.', "You're in my fairway.", 'Notice my grip.', 'Watch the birdie!', 'Keep your eye on the ball!', 'Mind if I play through?'], 'ThrowBook': ['My book from Law School should help.', 'You better have a good lawyer.', "I'll have to take legal action.", 'Legal Eagle will be pleased to see this.', 'Objection!', 'Under article 14 subsection C...', 'I see you have broken the law!', "It seems you don't understand the authority of law.", "I'll see you in court, Toon."], 'Tremor': ['Did you feel that?', 'Not afraid of a little tremor are you?', 'A tremor is only the beginning.', 'You look jittery.', "I'll shake things up a bit!", 'Are you ready to rumble?', "What's wrong? You look shaken.", 'Tremor with fear!', 'Why are you tremoring with fear?'], 'Watercooler': ['This ought to cool you off.', "Isn't this refreshing?", 'I deliver.', 'Straight from the tap - into your lap.', "What's the matter, it's just spring water.", "Don't worry, it's purified.", 'Ah, another satisfied customer.', "It's time for your daily delivery.", "Hope your colors don't run.", 'Care for a drink?', 'It all comes out in the wash.', "The drink's on you."], 'Withdrawal': ["I believe you're overdrawn.", 'I hope your balance is high enough for this.', 'Take that, with interest.', 'Your balance is dropping.', "You're going to need to make a deposit soon.", "You've suffered an economic collapse.", "I think you're in a slump.", 'Your finances have taken a decline.', 'I foresee a definite downturn.', "It's a reversal of fortune."], 'WriteOff': ['Let me increase your losses.', "Let's make the best of a bad deal.", 'Time to balance the books.', "This won't look good on your books.", "I'm looking for some dividends.", 'You must account for your losses.', 'You can forget about a bonus.', "I'll shuffle your accounts around.", "You're about to suffer some losses.", 'This is going to hurt your bottom line.'], 'Overdraft': ["It looks like you've been spending too many beans.", "I'm going to have to cut you off.", "You need to stop spending so many beans, toon.", "You toons and your bean spending.", "Looks like I'm gonna have to take that out of your bank.", "Your bean bank won't be so full after this."]} BuildingWaitingForVictors = ('Waiting for other players...',) ElevatorHopOff = 'Hop off' ElevatorStayOff = "If you hop off, you'll need to wait\nfor the elevator to leave or empty." ElevatorLeaderOff = 'Only your leader can decide when to hop off.' ElevatorHoppedOff = 'You need to wait for the next elevator.' ElevatorMinLaff = 'You need %s laff points to ride this elevator.' ElevatorHopOK = 'Okay' ElevatorGroupMember = 'Only your group leader can\n decide when to board.' KartMinLaff = 'You need %s laff points to ride this kart' CogsIncExt = ', Inc.' CogsIncModifier = '%s' + CogsIncExt CogsInc = Cogs.upper() + CogsIncExt CogdominiumsExt = ' Field Office' Cogdominiums = Cog.upper() + CogdominiumsExt DoorKnockKnock = 'Knock, knock.' DoorWhosThere = "Who's there?" DoorWhoAppendix = ' who?' DoorNametag = 'Door' FADoorCodes_UNLOCKED = None FADoorCodes_TALK_TO_TOM = 'You need gags! Go talk to Tutorial Tom!' FADoorCodes_DEFEAT_FLUNKY_HQ = 'Come back here when you have defeated the Flunky!' FADoorCodes_TALK_TO_HQ = 'Go get your reward from HQ Harry!' FADoorCodes_WRONG_DOOR_HQ = 'Wrong door! Take the other door to the playground!' FADoorCodes_GO_TO_PLAYGROUND = 'Wrong way! You need to go to the playground!' FADoorCodes_DEFEAT_FLUNKY_TOM = 'Walk up to the Flunky to battle him!' FADoorCodes_TALK_TO_HQ_TOM = 'Go get your reward from Toon Headquarters!' FADoorCodes_SUIT_APPROACHING = None FADoorCodes_BUILDING_TAKEOVER = "Watch out! There's a Cog in there!" FADoorCodes_SB_DISGUISE_INCOMPLETE = "You'll get caught going in there as a Toon! You need to complete your Sellbot Disguise first!\n\nBuild your Sellbot Disguise out of parts from the Factory." FADoorCodes_CB_DISGUISE_INCOMPLETE = "You'll get caught going in there as a Toon! You need to complete your Cashbot Disguise first!\n\nBuild your Cashbot Disguise out of parts from the Mint." FADoorCodes_LB_DISGUISE_INCOMPLETE = "You'll get caught going in there as a Toon! You need to complete your Lawbot Disguise first!\n\nBuild your Lawbot Disguise out of parts from the DA Office." FADoorCodes_BB_DISGUISE_INCOMPLETE = "You'll get caught going in there as a Toon! You need to complete your Bossbot Disguise first!\n\nBuild your Bossbot Disguise out of parts from the Country Club." KnockKnockDoorNames = { 44: DoorNametag, 2: 'Furr Elise', 1: 'Overwhelming October', 3: 'Slate', 4: 'Fanshy', 5: 'Smirky Bumberpop', 6: 'Little Flappy Bananaberry', 7: 'Quackity', 49: 'P Cuddles', 60: 'lilreenie', 10: 'parker643', 11: 'Midnite Purr', 63: 'Chipythepig', 62: 'Amanda', 16: 'Tyrynn', 18: 'mrpiggywinkles', 66: 'Error', 21: 'Quackity', 65: 'Azure Swallowtail', 24: 'krae2121', 26: 'GeeMayn', 25: 'FancyJackL', 67: 'Kewldude', 61: 'Macca', 29: 'PicklesJesse2'} KnockKnockContestJokes = { 2100: {44: ['Wally', "Wally's not looking, hit him with a pie!"], 2: ['Mirror', 'Mirror who?'], 1: ['Act', 'No, we\'re starting from act one.'], 3: ['Insane', 'I don\'t know, but you\'re the one talking to a door.'], 4: ['Candy', 'Candy have some Jellybeans?'], 5: ['Santa', 'I santa you the key, now let me out!'], 6: ['Sensor', 'Sensor not doing anything, mind opening the door?'], 7: ['Donald', 'Donald your tasks yet?'], 49: ['Eureka', 'Eureka something weird!'], 60: ['Anomaly', 'Anomaly don\'t say this, but have you seen my spaceship?'], 10: ['Toboggan', 'I hate toboggan with you, but will you open this door?'], 11: ['Goshi', 'Goshi wonder if I won an alpha key.'], 63: ['Shelly', 'Shelly compare thee to a summer\'s day?'], 62: ['Were', 'No, Werewolf! Owoooooo!'], 16: ['Stan', 'Stan back, or I\'ll throw this pie!'], 18: ['Snow', 'Snow way I\'m telling you!'], 66: ['Big Cheese', 'Big Cheese pizza delivery here, open up!'], 21: ['Telemarketer', 'Telemarketer I\'m not buying his offer.'], 65: ['June', 'Juneau how to get out of this fountain?'], 24: ['Mickey', 'Mickey is stuck! Help'], 26: ['Guess', 'Does he have a mustache?'], 25: ['Usain', 'Usain you forgot me?'], 67: ['Wayt', 'Wayt, you forgot my name?'], 61: ['Fuchsia', 'Fuchsia stop talking to doors and go finish that ToonTask!'], 29: ['Vincent', 'Vincent, where did my Van Gogh?']}, 2200: {28: ['Biscuit', 'Biscuit out of here the Cogs are coming!'], 41: ['Dewey', 'Dewey want to go defeat some more Cogs?'], 40: ['Minnie', "Minnie people have asked that, and it's driving me crazy!"], 27: ['Disguise', 'Disguise where the Cogs fly!']}, 2300: ['Justin', 'Justin other couple of Cog parts and off we go!'], 3300: {10: ['Aladdin', 'Aladdin HQ wants a word with you.'], 6: ['Weirdo', 'Weirdo all these Cogs come from?'], 30: ['Bacon', 'Bacon a cake to throw at the Cogs.'], 28: ['Isaiah', 'Isaiah we go ride the trolley.'], 12: ['Juliet', "Juliet me in that Cog building with you and I'll give you a Toon-Up."]}} KnockKnockJokes = [['Who', "Bad echo in here, isn't there?"], ['Dozen', 'Dozen anybody want to let me in?'], ['Freddie', 'Freddie or not, here I come.'], ['Dishes', 'Dishes your friend, let me in.'], ['Wooden shoe', 'Wooden shoe like to know.'], ['Betty', "Betty doesn't know who I am."], ['Kent', 'Kent you tell?'], ['Noah', "Noah don't know who either."], ["I don't know", 'Neither do I, I keep telling you that.'], ['Howard', 'Howard I know?'], ['Emma', 'Emma so glad you asked me that.'], ['Auto', "Auto know, but I've forgotten."], ['Jess', 'Jess me and my shadow.'], ['One', 'One-der why you keep asking that?'], ['Alma', 'Alma not going to tell you!'], ['Zoom', 'Zoom do you expect?'], ['Amy', "Amy fraid I've forgotten."], ['Arfur', 'Arfur got.'], ['Ewan', 'No, just me'], ['Cozy', "Cozy who's knocking will you?"], ['Sam', 'Sam person who knocked on the door last time.'], ['Fozzie', 'Fozzie hundredth time, my name is ' + Flippy + '.'], ['Deduct', Donald + ' Deduct.'], ['Max', 'Max no difference, just open the door.'], ['N.E.', 'N.E. body you like, let me in.'], ['Amos', 'Amos-quito bit me.'], ['Alma', "Alma candy's gone."], ['Bruce', "I Bruce very easily, don't hit me."], ['Colleen', "Colleen up your room, it's filthy."], ['Elsie', 'Elsie you later.'], ['Hugh', 'Hugh is going to let me in?'], ['Hugo', "Hugo first - I'm scared."], ['Ida', 'Ida know. Sorry!'], ['Isabel', 'Isabel on a bike really necessary?'], ['Joan', "Joan call us, we'll call you."], ['Kay', 'Kay, L, M, N, O, P.'], ['Justin', 'Justin time for dinner.'], ['Liza', 'Liza wrong to tell.'], ['Luke', 'Luke and see who it is.'], ['Mandy', "Mandy the lifeboats, we're sinking."], ['Max', 'Max no difference - just open the door!'], ['Nettie', 'Nettie as a fruitcake.'], ['Olivia', 'Olivia me alone!'], ['Oscar', 'Oscar stupid question, you get a stupid answer.'], ['Patsy', 'Patsy dog on the head, he likes it.'], ['Paul', "Paul hard, the door's stuck again."], ['Thea', 'Thea later, alligator.'], ['Tyrone', "Tyrone shoelaces, you're old enough."], ['Stella', 'Stella no answer at the door.'], ['Uriah', 'Keep Uriah on the ball.'], ['Dwayne', "Dwayne the bathtub. I'm drowning."], ['Dismay', "Dismay be a joke, but it didn't make me laugh."], ['Ocelot', "Ocelot of questions, don't you?"], ['Thermos', 'Thermos be a better knock knock joke than this.'], ['Sultan', 'Sultan Pepper.'], ['Vaughan', 'Vaughan day my prince will come.'], ['Donald', 'Donald come baby, cradle and all.'], ['Lettuce', "Lettuce in, won't you?"], ['Ivor', 'Ivor sore hand from knocking on your door!'], ['Isabel', 'Isabel broken, because I had to knock.'], ['Heywood, Hugh, Harry', 'Heywood Hugh Harry up and open this door.'], ['Juan', "Juan of this days you'll find out."], ['Earl', 'Earl be glad to tell you if you open this door.'], ['Abbot', 'Abbot time you opened this door!'], ['Ferdie', 'Ferdie last time, open the door!'], ['Don', 'Don mess around, just open the door.'], ['Sis', 'Sis any way to treat a friend?'], ['Isadore', 'Isadore open or locked?'], ['Harry', 'Harry up and let me in!'], ['Theodore', "Theodore wasn't open so I knocked-knocked."], ['Ken', 'Ken I come in?'], ['Boo', "There's no need to cry about it."], ['You', 'You who! Is there anybody there?'], ['Ice cream', "Ice cream if you don't let me in."], ['Sarah', "Sarah 'nother way into this building?"], ['Mikey', 'Mikey dropped down the drain.'], ['Doris', 'Doris jammed again.'], ['Yelp', 'Yelp me, the door is stuck.'], ['Scold', 'Scold outside.'], ['Diana', 'Diana third, can I have a drink please?'], ['Doris', 'Doris slammed on my finger, open it quick!'], ['Lettuce', 'Lettuce tell you some knock knock jokes.'], ['Izzy', 'Izzy come, izzy go.'], ['Omar', 'Omar goodness gracious - wrong door!'], ['Says', "Says me, that's who!"], ['Duck', "Just duck, they're throwing things at us."], ['Tank', "You're welcome."], ['Eyes', 'Eyes got loads more knock knock jokes for you.'], ['Pizza', 'Pizza cake would be great right now.'], ['Closure', 'Closure mouth when you eat.'], ['Harriet', "Harriet all my lunch, I'm starving."], ['Wooden', 'Wooden you like to know?'], ['Punch', 'Not me, please.'], ['Gorilla', 'Gorilla me a hamburger.'], ['Jupiter', "Jupiter hurry, or you'll miss the trolley."], ['Bertha', 'Happy Bertha to you!'], ['Cows', 'Cows go "moo" not "who."'], ['Tuna fish', "You can tune a piano, but you can't tuna fish."], ['Consumption', 'Consumption be done about all these knock knock jokes?'], ['Banana', 'Banana spilt so ice creamed.'], ['X', 'X-tremely pleased to meet you.'], ['Haydn', 'Haydn seek is fun to play.'], ['Rhoda', 'Rhoda boat as fast as you can.'], ['Quacker', "Quacker 'nother bad joke and I'm off!"], ['Nana', 'Nana your business.'], ['Ether', 'Ether bunny.'], ['Little old lady', "My, you're good at yodelling!"], ['Beets', 'Beets me, I forgot the joke.'], ['Hal', 'Halloo to you too!'], ['Sarah', 'Sarah doctor in the house?'], ['Aileen', 'Aileen Dover and fell down.'], ['Atomic', 'Atomic ache'], ['Agatha', 'Agatha headache. Got an aspirin?'], ['Stan', "Stan back, I'm going to sneeze."], ['Hatch', 'Bless you.'], ['Ida', "It's not Ida who, it's Idaho."], ['Zippy', 'Mrs. Zippy.'], ['Yukon', 'Yukon go away and come back another time.']] SharedChatterGreetings = ['Hi, %!', 'Yoo-hoo %, nice to see you.', "I'm glad you're here today!", 'Well, hello there, %.'] SharedChatterComments = ["That's a great name, %.", 'I like your name.', 'Watch out for the ' + Cogs + '.', 'Looks like the trolley is coming!', 'I need to play a trolley game to get some pies!', 'Sometimes I play trolley games just to eat the fruit pie!', 'Whew, I just stopped a bunch of ' + Cogs + '. I need a rest!', 'Yikes, some of those ' + Cogs + ' are big guys!', "You look like you're having fun.", "Oh boy, I'm having a good day.", "I like what you're wearing.", "I think I'll go fishing this afternoon.", 'Have fun in my neighborhood.', 'I hope you are enjoying your stay in Toontown!', "I heard it's snowing at the Brrrgh.", 'Have you ridden the trolley today?', 'I like to meet new people.', 'Wow, there are lots of ' + Cogs + ' in the Brrrgh.', 'I love to play tag. Do you?', 'Trolley games are fun to play.', 'I like to make people laugh.', "It's fun helping my friends.", "A-hem, are you lost? Don't forget your map is in your shticker Book.", 'Try not to get tied up in the ' + Cogs + "' Red Tape.", 'I hear ' + Daisy + ' has planted some new flowers in her garden.', 'If you press the Page Up key, you can look up!', 'If you help take over Cog buildings, you can earn a bronze star!', 'If you press the Tab key, you can see different views of your surroundings!', 'If you press the Ctrl key, you can jump!'] SharedChatterGoodbyes = ['I have to go now, bye!', "I think I'll go play a trolley game.", "Well, so long. I'll be seeing you, %!", "I'd better hurry and get to work stopping those " + Cogs + '.', "It's time for me to get going.", 'Sorry, but I have to go.', 'Good-bye.', 'See you later, %!', "I think I'm going to go practice tossing cupcakes.", "I'm going to join a group and stop some " + Cogs + '.', 'It was nice to see you today, %.', "I have a lot to do today. I'd better get busy."] MickeyChatter = (['Welcome to ' + lToontownCentral + '.', 'Hi, my name is ' + Mickey + ". What's yours?"], ['Hey, have you seen ' + Donald + '?', "I'm going to go watch the fog roll in at " + lDonaldsDock + '.', 'If you see my pal ' + Goofy + ', say hi to him for me.', 'I hear ' + Daisy + ' has planted some new flowers in her garden.'], ["I'm going to MelodyLand to see " + Minnie + '!', "Gosh, I'm late for my date with " + Minnie + '!', "Looks like it's time for " + Pluto + "'s dinner.", "I think I'll go swimming at " + lDonaldsDock + '.', "It's time for a nap. I'm going to Dreamland."]) WinterMickeyCChatter = (["Hi, I'm Merry Mickey!", 'Welcome to Tinseltown... I mean, Toontown!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %'], ['Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'Golly, these halls sure are decked!', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'Just look at those tree lights! What a sight!', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'Not a creature is stirring, except this mouse!', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'I love this time of year!', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', "I'm feeling jolly, how about you?", 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'Know any good carols?', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', 'Oh boy! I love Winter Holiday!', 'Sing your seasonal cheer at Joy Buzzers to the World and Joy is sure to return the favor!', "I think I'll trade my gloves for mittens!"], ['Have a happy Winter Holiday!', 'Warm wishes to you!', 'Shucks, sorry you have to go. So long!', "I'm going caroling with Minnie!"]) ValentinesMickeyChatter = (["Hi, I'm Mickey!", 'Welcome to ValenToontown Central!', "Happy ValenToon's Day!", "Happy ValenToon's Day, %"], ['Love is in the air! And butterflies!', 'Those hearts are good for Laff boosts!', 'I hope Minnie likes what I got her!', "The Cattlelog has lots of ValenToon's Day gifts!", "Throw a ValenToon's Day party!", 'Show the Cogs you love them with a pie in the face!', "I'm taking Minnie out to the Kooky Cafe!", 'Will Minnie want chocolates or flowers?'], ['I loved having you visit!', "Tell Minnie I'll pick her up soon!"]) WinterMickeyDChatter = (["Hi, I'm Merry Mickey!", 'Welcome to Tinseltown... I mean, Toontown!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %'], ['Golly, these halls sure are decked!', 'Just look at those tree lights! What a sight!', 'Not a creature is stirring, except this mouse!', 'I love this time of year!', "I'm feeling jolly, how about you?", 'Know any good carols?', 'Oh boy! I love Winter Holiday!', "I think I'll trade my gloves for mittens!"], ['Have a happy Winter Holiday!', 'Warm wishes to you!', 'Shucks, sorry you have to go. So long!', "I'm going caroling with Minnie!"]) VampireMickeyChatter = (['Welcome to ' + lToontownCentral + '.', 'Hi, my name is ' + Mickey + ". What's yours?", 'Happy Halloween!', 'Happy Halloween, %!', 'Welcome to Tombtown... I mean Toontown!'], ['If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', "It's fun to dress up for Halloween!", 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', 'Do you like my costume?', 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', '%, watch out for Bloodsucker Cogs!', 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', "Aren't the Halloween decorations great?", 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', 'Beware of black cats!', 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', 'Did you see the Toon with the pumpkin head?', 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', 'Boo! Did I scare you?', 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', "Don't forget to brush your fangs!", 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', "I'm a vampire, but not a Bloodsucker!", 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', "I hope you're enjoying our Halloween fun!", 'If you think playing tricks is All Fun and Games, go see Lazy Hal for a treat!', 'Vampires are really popular this year!'], ["I'm going to check out the cool Halloween decorations.", "I'm going to MelodyLand to surprise " + Minnie + '!', "I'm going to sneak up on another Toon! Shhh!", "I'm going trick-or-treating!", 'Shhh, sneak with me.']) FieldOfficeMickeyChatter = ['Have you heard about the new Mover & Shaker Field Offices?'] MinnieChatter = (['Welcome to Melodyland.', 'Hi, my name is ' + Minnie + ". What's yours?"], ['The hills are alive with the sound of music!', 'You have a cool outfit, %.', 'Hey, have you seen ' + Mickey + '?', 'If you see my friend ' + Goofy + ', say hi to him for me.', 'Wow, there are lots of ' + Cogs + ' near ' + Donald + "'s Dreamland.", "I heard it's foggy at the " + lDonaldsDock + '.', 'Be sure and try the maze in ' + lDaisyGardens + '.', "I think I'll go catch some tunes.", 'Hey %, look at that over there.', 'I love the sound of music.', "I bet you didn't know Melodyland is also called TuneTown! Hee Hee!", 'I love to play the Matching Game. Do you?', 'I like to make people giggle.', 'Boy, trotting around in heels all day is hard on your feet!', 'Nice shirt, %.', 'Is that a jellybean on the ground?'], ["Gosh, I'm late for my date with %s!" % Mickey, "Looks like it's time for %s's dinner." % Pluto, "It's time for a nap. I'm going to Dreamland."]) WinterMinnieCChatter = (["Hi, I'm Merry Minnie!", 'Welcome to the land of carols!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ["You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", 'Belt out a tune, Toon!', "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", 'Show us how to croon, Toon!', "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", 'Can you carry a melody here in Melodyland?', "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", 'Those lamps look warm in their scarves!', "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", "The sing's the thing!", "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", "I'll always like you, for better or verse!", "You'll get more than a Shave and a Haircut For a Song if you carol to Barbara Seville!", 'Everything looks better with a wreath!'], ['Have a fun Winter Holiday!', 'Happy Trails!', 'Mickey is taking me caroling!']) WinterMinnieDChatter = (["Hi, I'm Merry Minnie!", 'Welcome to the land of carols!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['Belt out a tune, Toon!', 'Show us how to croon, Toon!', 'Can you carry a melody here in Melodyland?', 'Those lamps look warm in their scarves!', "The sing's the thing!", "You can't go wrong with a song!", "I'll always like you, for better or verse!", 'Everything looks better with a wreath!'], ['Have a fun Winter Holiday!', 'Happy Trails!', 'Mickey is taking me caroling!']) ValentinesMinnieChatter = (["Hello, I'm Minnie!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %"], ['I hope Mickey got me chocolates or flowers!', 'Those hearts are good for Laff boosts!', 'I want to go to a ValenToon Party!', 'I hope Mickey takes me to the Kooky Cafe!', 'Mickey is such a good ValenToon!', 'What did you get your ValenToon?', "Mickey has never missed a ValenToon's Day!"], ['It was sweet having you visit!']) WitchMinnieChatter = (['Welcome to Magicland... I mean Melodyland!', "Hi, my name is Magic Minnie! What's yours?", "Hello, I think you're enchanting!", 'Happy Halloween!', 'Happy Halloween, %!'], ['I hear Tabitha has treats for Really Kool Katz who can play tricks!', "It's a magical day, don't you think?", 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Now where did I put my spell book', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Abra-Cadabra!', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Toontown looks positively spooky today!', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Are you seeing stars too?', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Purple is really my color!', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'I hope your Halloween is bewitching!', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'Beware of musical spiders!', 'I hear Tabitha has treats for Really Kool Katz who can play tricks!', 'I hope you are enjoying our Halloween fun!'], ["I'm going to disappear now!", 'Time for me to vanish!', 'Mickey is taking me Trick-or-Treating!']) FieldOfficeMinnieChatter = ['Everyone is talking about the new Mover & Shaker Field Offices!'] DaisyChatter = (['Welcome to my garden!', "Hello, I'm " + Daisy + ". What's your name?", "It's so nice to see you %!"], ['My prize winning flower is at the center of the garden maze.', 'I just love strolling through the maze.', "I haven't seen " + Goofy + ' all day.', 'I wonder where ' + Goofy + ' is.', 'Have you seen ' + Donald + "? I can't find him anywhere.", 'If you see my friend ' + Minnie + ', please say "Hello" to her for me.', 'The better gardening tools you have the better plants you can grow.', 'There are far too many ' + Cogs + ' near ' + lDonaldsDock + '.', 'Watering your garden every day keeps your plants happy.', 'To grow a Pink Daisy plant a yellow and red jellybean together.', 'Yellow daisies are easy to grow, just plant a yellow jellybean.', 'If you see sand under a plant it needs water or it will wilt!'], ["I'm going to Melody Land to see %s!" % Minnie, "I'm late for my picnic with %s!" % Donald, "I think I'll go swimming at " + lDonaldsDock + '.', "Oh, I'm a little sleepy. I think I'll go to Dreamland."]) ValentinesDaisyChatter = (["Hi, I'm Daisy!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %"], ["I hope Donald doesn't get me another Amore Eel!", 'Donald is taking me out to the Deep-see Diner!', 'I certainly have enough roses!', 'Those hearts are good for Laff boosts!', "I'd love to go to a ValenToon's Day party!", 'This is the garden where love grows!', "Donald better not sleep through ValenToon's Day again!", 'Maybe Donald and I can double-date with Mickey and Minnie!'], ["Tell Donald I'll be waiting for him!", "Have a nice ValenToon's Day!"]) WinterDaisyCChatter = (['Welcome to the only garden that grows in the winter!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'My garden needs more mistletoe!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'I need to plant holly for next year!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', "I'm going to ask Goofy to build me a gingerbread house!", 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'Those lights on the lamps are lovely!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'That is some jolly holly!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'My snowman keeps melting!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'That duck is decked out!', 'Shoshanna at Pine Needle Crafts is a real sap for songs, so why not craft her a carol?', 'I grew all these lights myself!'], ['Have a jolly Winter Holiday!', 'Happy planting!', 'Tell Donald to stop by with presents!', 'Donald is taking me caroling!']) WinterDaisyDChatter = (['Welcome to the only garden that grows in the winter!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['My garden needs more mistletoe!', 'I need to plant holly for next year!', "I'm going to ask Goofy to build me a gingerbread house!", 'Those lights on the lamps are lovely!', 'That is some jolly holly!', 'My snowman keeps melting!', 'That duck is decked out!', 'I grew all these lights myself!'], ['Have a jolly Winter Holiday!', 'Happy planting!', 'Tell Donald to stop by with presents!', 'Donald is taking me caroling!']) HalloweenDaisyChatter = (['Welcome to Daisy Ghosts... I mean Gardens!', 'Happy Halloween!', 'Happy Halloween, %!'], ['Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'Wanna dance?', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', "I'm a duck with a poodle skirt!", 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'The pirate tree needs water.', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'Trick-or-Tree!', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'Do you notice anything strange about the trees?', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'I should grow some pumpkins!', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'WHO notices something different about the lamps?', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'Halloween really grows on me!', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'Twig-or-Treat!', 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', "Owl bet you didn't notice the spooky lamps!", 'Visit my friend Leif Pyle if you have a trick and Rake Inn the treats!', 'I hope you are enjoying our Halloween fun!'], ['Donald is taking me Trick-or-Treating!', "I'm going to check out the fun Halloween decorations."]) FieldOfficeDaisyChatter = ['Those Mover & Shaker Field Offices are popping up like weeds!'] ChipChatter = (['Welcome to %s!' % lOutdoorZone, "Hello, I'm " + Chip + ". What's your name?", "No, I'm " + Chip + '.', "It's so nice to see you %!", 'We are Chip and Dale!'], ['I like golf.', 'We have the best acorns in Toontown.', 'The golf holes with volcanoes are the most challenging for me.'], ["We're going to the " + lTheBrrrgh + ' and play with %s.' % Pluto, "We'll visit %s and fix him." % Donald, "I think I'll go swimming at " + lDonaldsDock + '.', "Oh, I'm a little sleepy. I think I'll go to Dreamland."]) ValentinesChipChatter = (["I'm Chip!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %!"], ["What did you get me for ValenToon's Day, Dale?", 'Those hearts are good for Laff boosts!', 'Will you be my ValenToon, Dale?', "What did you get the Cogs for ValenToon's Day?", "I love ValenToon's Day!"], ['Come back any time!']) WinterChipChatter = (['Happy Winter Holiday!', 'Dressed as chipmunks!', 'Happy Winter Holiday, %!'], ['Happy Winter Holiday, Dale!', 'All this water could freeze any minute!', 'We should switch the golf balls with snowballs!', 'If only chipmunks knew how to sing!', 'Did you remember to store nuts for the winter?', 'Did you get the Cogs a present?'], ['Go nuts this Winter Holiday!', 'Have a joyful winter Holiday!']) HalloweenChipChatter = (['Play some MiniGhoul... I mean Golf!', 'Happy Halloween!', 'Happy Halloween, %!'], ["We're nuts about Halloween!", "You're under arrest", "You can't outrun the long arm of the law", "I'm a Bobby!", 'I hope you are enjoying our Halloween fun!', 'Play golf and get a Howl-In-One.', 'Candy corns are sweeter than acorns.', 'I hope you are enjoying our Halloween fun!'], ['%, watch out for Bloodsucker Cogs!']) DaleChatter = (["It's so nice to see you %!", "Hello, I'm " + Dale + ". What's your name?", "Hi I'm " + Chip + '.', 'Welcome to %s!' % lOutdoorZone, 'We are Chip and Dale!'], ['I like picnics.', 'Acorns are tasty, try some.', 'Those windmills can be hard too.'], ['Hihihi ' + Pluto + ' is fun to play with.', "Yeah, let's fix %s." % Donald, 'A swim sounds refreshing.', "I'm getting tired and could use a nap."]) ValentinesDaleChatter = (["I'm Dale!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %!"], ['Same thing as last year. Nothing!', 'I miss the nuts!', 'Will you be my ValenToon, Chip?', 'A pie in the face', "Yeah, it's all right."], ['Come back any time!']) WinterDaleChatter = (['Merry chipmunks!', "Hi, we're two merry elves!", 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['Happy Winter Holiday, Chip!', 'Better not be on the geyser when it happens!', 'And the golf clubs with icicles!', 'Whoever heard of singing chipmunks?', 'I told YOU to do that!', 'Yes, a cream pie!'], ['And bring some back for us!', 'Have a joyful Winter Holiday!']) HalloweenDaleChatter = (['Happy Halloween, %!', 'Play some MiniGhoul... I mean Golf!', 'Happy Halloween!'], ["We're nuts about Halloween!", 'Great, I could use a rest!', 'But your arms are short!', 'I thought you were a Chip!', 'Play golf and get a Howl-In-One', 'Candy corns are sweeter than acorns.', 'I hope you are enjoying our Halloween fun!'], ['%, watch out for Bloodsucker Cogs!']) GoofyChatter = (['Welcome to ' + lDaisyGardens + '.', 'Hi, my name is ' + Goofy + ". What's yours?", "Gawrsh, it's nice to see you %!"], ['Boy it sure is easy to get lost in the garden maze!', 'Be sure and try the maze here.', "I haven't seen " + Daisy + ' all day.', 'I wonder where ' + Daisy + ' is.', 'Hey, have you seen ' + Donald + '?', 'If you see my friend ' + Mickey + ', say hi to him for me.', "D'oh! I forgot to fix " + Mickey + "'s breakfast!", 'Gawrsh there sure are a lot of ' + Cogs + ' near ' + lDonaldsDock + '.', 'It looks like ' + Daisy + ' has planted some new flowers in her garden.', 'At the Brrrgh branch of my Gag Shop, Hypno-Goggles are on sale for only 1 jellybean!', "Goofy's Gag Shops offer the best jokes, tricks, and funnybone-ticklers in all of Toontown!", "At Goofy's Gag Shops, every pie in the face is guaranteed to make a laugh or you get your Jellybeans back!"], ["I'm going to Melody Land to see %s!" % Mickey, "Gosh, I'm late for my game with %s!" % Donald, "I think I'll go swimming at " + lDonaldsDock + '.', "It's time for a nap. I'm going to Dreamland."]) WinterGoofyChatter = (["I'm Goofy about the holidays!", 'Welcome to Snowball Speedway!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['Who needs reindeer when you have a fast kart?', 'Gawrsh! Is it Winter Holiday already?', 'I need my earmuffs!', "I haven't done any shopping yet!", "Don't drive your kart on ice!", 'Seems like it was Winter Holiday only a year ago!', 'Treat your kart to a present and spruce it up!', 'These karts are better than any old sleigh!'], ['Have a cheery Winter Holiday!', 'Drive safe, now!', 'Watch out for flying reindeer!']) ValentinesGoofyChatter = (["I'm Goofy about ValenToon's Day!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %!"], ["Gawrsh! Is it ValenToon's Day already?", 'I LOVE kart racing!', 'Be sweet to each other out there!', 'Show your sweetie a new kart!', 'Toons love their karts!', 'Make some new friends on the track!'], ['Drive safe, now!', 'Show some love out there!']) GoofySpeedwayChatter = (['Welcome to ' + lGoofySpeedway + '.', 'Hi, my name is ' + Goofy + ". What's yours?", "Gawrsh, it's nice to see you %!"], ['Boy, I saw a terrific race earlier.', 'Watch out for banana peels on the race track!', 'Have you upgraded your kart lately?', 'We just got in some new rims at the kart shop.', 'Hey, have you seen ' + Donald + '?', 'If you see my friend ' + Mickey + ', say hi to him for me.', "D'oh! I forgot to fix " + Mickey + "'s breakfast!", 'Gawrsh there sure are a lot of ' + Cogs + ' near ' + lDonaldsDock + '.', 'At the Brrrgh branch of my Gag Shop, Hypno-Goggles are on sale for only 1 jellybean!', "Goofy's Gag Shops offer the best jokes, tricks, and funnybone-ticklers in all of Toontown!", "At Goofy's Gag Shops, every pie in the face is guaranteed to make a laugh or you get your Jellybeans back!"], ["I'm going to Melody Land to see %s!" % Mickey, "Gosh, I'm late for my game with %s!" % Donald, "I think I'll go swimming at " + lDonaldsDock + '.', "It's time for a nap. I'm going to Dreamland."]) SuperGoofyChatter = (['Welcome to my Super Speedway!', "Hi, I'm Super Goof! What's your name?", 'Happy Halloween!', 'Happy Halloween, %!'], ['I am feeling kind of batty today!', 'Anybody see my cape around? Oh, there it is!', "Gawrsh! I don't know my own strength!", 'Did somebody call for a superhero?', "Beware Cogs, I'll save Halloween!", "There's nothing scarier than me in a kart!", "I bet you don't know who I am with this mask on!", "It's fun to dress up for Halloween!", 'I hope you are enjoying our Halloween fun!'], ['Gotta fly!', 'Hi-Ho and away I go!', "Should I fly or drive to Donald's Dock?", 'Gawrsh, have a Happy Halloween!']) DonaldChatter = (['Welcome to Dreamland.', "Hi, my name is %s. What's yours?" % Donald], ['Sometimes this place gives me the creeps.', 'Be sure and try the maze in ' + lDaisyGardens + '.', "Oh boy, I'm having a good day.", 'Hey, have you seen ' + Mickey + '?', 'If you see my buddy ' + Goofy + ', say hi to him for me.', "I think I'll go fishing this afternoon.", 'Wow, there are lots of ' + Cogs + ' at ' + lDonaldsDock + '.', "Hey, didn't I take you on a boat ride at " + lDonaldsDock + '?', "I haven't seen " + Daisy + ' all day.', 'I hear ' + Daisy + ' has planted some new flowers in her garden.', 'Quack.'], ["I'm going to Melody Land to see %s!" % Minnie, "Gosh, I'm late for my date with %s!" % Daisy, "I think I'll go swimming at my dock.", "I think I'll take my boat for a spin at my dock."]) WinterDreamlandCChatter = (["Hi, I'm Dozing Donald!", 'Welcome to Holiday Dreamland!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', 'I wish I was nestled all snug in my bed!', 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', "I'm dreaming of a white Toontown!", 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', 'I meant to leave out milk and cookies!', 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', 'When I wake up, I better see lots of presents!', 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', "I hope I don't sleep through the holidays!", 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', "I love a long winter's nap!", 'Willow says that learning a little Sleep Voice Training is a real present, sing her a tune and find out why!', 'The trees on the streets are covered in night lights!'], ['To all, a good night!', 'Sweet dreams!', 'When I wake up I am going caroling!']) WinterDreamlandDChatter = (["Hi, I'm Dozing Donald!", 'Welcome to Holiday Dreamland!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['I wish I was nestled all snug in my bed!', "I'm dreaming of a white Toontown!", 'I meant to leave out milk and cookies!', 'When I wake up, I better see lots of presents!', "I hope I don't sleep through the holidays!", "I love a long winter's nap!", 'The trees on the streets are covered in night lights!'], ['To all, a good night!', 'Sweet dreams!', 'When I wake up I am going caroling!']) HalloweenDreamlandChatter = (['Happy Halloween!', 'Happy Halloween, %!', "Hi, I'm FrankenDonald!"], ['If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', 'Am I awake or dreaming?', 'If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', "I'm so scared, I can't fall asleep!", 'If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', 'So this is what Dreamland looks like!', 'If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', "Boy, I'm sleepy!", 'If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', "I hope I don't sleep through Halloween this year!", 'If you can play a trick on my friend Max, then you can Relax To The Max with a treat!', 'I hope you are enjoying our Halloween fun!'], ['Sleep with the lights on tonight!', 'When I wake up, I am going Trick-or-Treating!']) ValentinesDreamlandChatter = (["Hello, I'm (yawn) Donald!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %!"], ["I hope I don't sleep through ValenToon's Day!", "I'm dreaming of Daisy!", "I had a nightmare that I missed ValenToon's Day!", 'Those hearts are good for Laff boosts!', "Throw a ValenToon's Day party!", 'Show the Cogs you love them with a pie in the face!', "I couldn't dream of a nicer holiday than ValenToon's Day!", 'I love sleeping!'], ['Nite-nite!', "Wake me when it's ValenToon's Day!"]) FieldOfficeDreamlandChatter = ['I dreamed about something called a Field Office...'] HalloweenDonaldChatter = (['Welcome to my Halloween harbor!', 'Come aboard, if you have treats!', 'Happy Halloween!', 'Happy Halloween, %!'], ['If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', "I'm dressed as a sailor!", 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', 'Pumpkins make great lanterns!', 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', "I've never seen palm trees with hairy legs before!", 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', "Maybe I'll be a pirate next Halloween!", 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', 'I think the best treats are starfish!', 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', "I'll take you Trick-or-Treating around the harbor!", 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', 'I hope those spiders stay in the trees!', 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', 'What do you call a ghost in the water? A BOO-y!', 'If playing tricks is making you feel Rudderly Ridiculous, then go see Rudy for a treat!', 'I hope you are enjoying our Halloween fun!'], ['Set sail for scares!', 'Happy haunting!', "I'm going to check out the spooky Halloween decorations."]) ValentinesDonaldChatter = (["Ahoy, I'm Donald!", "Happy ValenToon's Day!", "Happy ValenToon's Day, %!"], ["Was I supposed to take Daisy somewhere for ValenToon's Day?", "Just once more around the dock, then I'll get Daisy something.", "What would Daisy like for ValenToon's Day?", 'Those hearts in the water are good for Laff boosts!', "Throw a ValenToon's Day party!", 'Show the Cogs you love them with a pie in the face!', "I'll have to catch an Amore Eel for Daisy!"], ['Aloha!', 'Give the Cogs my best!']) WinterDonaldCChatter = (["Welcome to Donald's Boat and Sleigh Dock!", 'All aboard for the Winter Holiday cruise!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'How do you like my duck-orations?', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'What is snow doing on the lamp posts?', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'This water better not ice over!', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'How did they get the lights up in those trees?', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'This boat is better than a sleigh! or is it?', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', "I don't need reindeer to pull this boat!", 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', "I'm glad I'm not a turkey this time of year!", 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', 'My present to you? Free boat rides!', 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!', "I hope I don't get a lump of coal again!", 'I hear that Dante has Gifts With A Porpoise, share a song and he may have a gift for you too!'], ['All ashore for holiday fun!', 'Remember to tip your boat driver on the way out!', 'Enjoy your holiday!']) WinterDonaldDChatter = (["Welcome to Donald's Boat and Sleigh Dock!", 'All aboard for the Winter Holiday cruise!', 'Happy Winter Holiday!', 'Happy Winter Holiday, %!'], ['How do you like my duck-orations?', 'What is snow doing on the lamp posts?', 'This water better not ice over!', 'How did they get the lights up in those trees?', 'This boat is better than a sleigh! or is it?', "I don't need reindeer to pull this boat!", "I'm glad I'm not a turkey this time of year!", 'My present to you? Free boat rides!', "I hope I don't get a lump of coal again!"], ['All ashore for holiday fun!', 'Remember to tip your boat driver on the way out!', 'Enjoy your holiday!']) WesternPlutoChatter = (["Boo! Don't be scared, it's just me ... Pluto!", 'Happy Halloween, pardner!', 'Happy Halloween, %!'], ["Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", 'I do tricks for treats!', "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", "Mickey's taking me Trick-or-Treating later!", "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", 'It feels more like Winter Holiday than Halloween!', "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", "Bark! That's 'Trick-or-Treat' in dog!", "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", 'I hope you are enjoying our Halloween fun!', "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", 'I like to chase Black Cat Toons!', "Frosty Fred has treats for tricks, they make him feel like there's Snowplace Like Home!", "There's a snake in my boot!"], ["I'm going to go dig up a treat!", "I'm going to see if Mickey has some treats!", "I'm going to scare Donald!"]) WinterPlutoCChatter = (["Hi, I'm Pluto!", "Welcome to the Brrgh, where it's winter all year!", 'Happy Winter Holiday!', 'Happy Winter Holiday, %'], ["Eddie could use a good tune, because Snowman's Land is a lonely place for a Yeti!", 'I chewed on an icicle and got frost-bite!', "Eddie could use a good tune, because Snowman's Land is a lonely place for a Yeti!", 'This is like living in a snow globe!', "Eddie could use a good tune, because Snowman's Land is a lonely place for a Yeti!", 'I wish I was beside a warm fire!', "Eddie could use a good tune, because Snowman's Land is a lonely place for a Yeti!", 'Arf! Arf! I need a scarf!', "Eddie could use a good tune, because Snowman's Land is a lonely place for a Yeti!", "At least my nose isn't red and glowing!"], ['Have a fun Winter Holiday!', 'Come back any time you want snow!', 'Mickey is taking me caroling!']) WinterPlutoDChatter = (["Hi, I'm Pluto!", "Welcome to the Brrgh, where it's winter all year!", 'Happy Winter Holiday!', 'Happy Winter Holiday, %'], ['I chewed on an icicle and got frost-bite!', 'This is like living in a snow globe!', 'I wish I was beside a warm fire!', 'Arf! Arf! I need a scarf!', "At least my nose isn't red and glowing!"], ['Have a fun Winter Holiday!', 'Come back any time you want snow!', 'Mickey is taking me caroling!']) AFMickeyChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Welcome to the Gardens! I'm " + Daisy + '!', "I'm " + Daisy + ', and I love to garden!', "April Toons' Week is the silliest week of the year!", "What, you've never seen a duck with mouse ears?", "Hi, I'm " + Daisy + '! Quack!', "It's tough quacking like a duck!", "I'm not feeling like myself today!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ["Have a wacky April Toons' Week!", 'Tell Mickey I said hi!']) AFMinnieChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ['Welcome to ' + lTheBrrrgh + "! I'm " + Pluto + '!', "Hi, I'm " + Pluto + "! What's your name?", "What, you've never seen a dog with mouse ears?", "I'm not feeling like myself today!", "Does anyone have a doggie biscuit? I'm hungry!", 'Bark! My name is ' + Pluto + '!', "Isn't this silly?", "Don't make me chase you around!", "April Toons' Week is the silliest week of the year!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ["Have a wacky April Toons' Week!", 'I have to go chase cars now! Bye!']) AFDaisyChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ['Welcome to ' + lToontownCentral + "! I'm " + Mickey + ' Mouse!', "Hi, I'm " + Mickey + '! The happiest mouse in Toontown!', 'If you see ' + Daisy + ', tell her ' + Mickey + ' said hi!', "What, you've never seen a mouse with feathers?", "Isn't this silly?", "I'm not feeling like myself today!", "April Toons' Week is the silliest week of the year!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ['Bye! Tell them ' + Mickey + ' sent you!', 'If you go to ' + lDaisyGardens + ', say hi to her for me!']) AFGoofySpeedwayChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Welcome to Dreamland! I'm " + Donald + '!', "Hello, I'm " + Donald + '! Is it nap time yet?', 'A duck needs his beauty rest, you know!', "What, you've never seen a duck with dog ears?", 'Gawrsh! I mean -- Quack!', 'This would make a great race track ... um, I mean place to nap!', "I'm not feeling like myself today!", "April Toons' Week is the silliest week of the year!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ['If you see ' + Goofy + ', tell him ' + Donald + ' says hi!', 'Bye, and good night!']) AFDonaldChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Welcome to the Speedway! I'm " + Goofy + '!', "I'm " + Goofy + ", and I'm dreaming I'm " + Donald + '!', "I've heard of sleep walking, but sleep kart driving?", 'Gawrsh! It sure is silly being ' + Goofy + '!', 'How can I watch the races with my eyes closed?', 'I better grab a nap before my next race!', "April Toons' Week is the silliest week of the year!", "I'm not feeling like myself today!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ["Have a wacky April Toons' Week!", 'I need to work on my karts! Bye!']) AFDonaldDockChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Everybody gets April Toons' Week off but me!", "I'm the only one who has to work this week!", 'I only get time off when I sleep!', 'All my friends are pretending to be somebody else!', 'Round and round in this boat, all day long!', 'I heard Daisy is pretending to be Mickey!', "The silliest week of the year, and I'm missing it!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ["Have a wacky April Toons' Week!", 'Play a joke on the Cogs for me!']) AFPlutoChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Welcome to Melodyland! I'm " + Minnie + '!', 'Hi, my name is ' + Minnie + ' Mouse!', "I'm as happy as a mouse can be!", "What, you've never seen a mouse with dog ears?", 'I love when ' + Mickey + ' and I go for walks!', 'What, you never heard a mouse talk before?', "April Toons' Week is the silliest week of the year!", 'Have you heard your Doodle talk yet?', 'Gravity has taken a holiday at the Estates!'], ["Have a wacky April Toons' Week!", 'If you see ' + Pluto + ', tell him ' + Minnie + ' says hi!']) AFChipChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Hi, I'm " + Dale + '!', 'How are you today, ' + Chip + '?', 'I always thought you were ' + Dale + ', ' + Chip + '.', "You're sure you're " + Chip + ' and not ' + Dale + ', ' + Chip + '?', "April Toons' Week is the silliest week of the year!"], ['Bye from ' + Chip + ' and ' + Dale + '!']) AFDaleChatter = (["Happy April Toons' Week!", "Happy April Toons' Week, %!"], ["Hi, I'm " + Chip + '!', 'Very well ' + Dale + ', thanks!', "Nope, I'm " + Chip + ', ' + Dale + '.', 'Yes, ' + Dale + ", I'm " + Chip + ', not ' + Dale + '.', 'It sure is, ' + Chip + '! I mean, ' + Dale + '.'], ['Or ' + Dale + ' and ' + Chip + '!']) CLGoofySpeedwayChatter = (['Welcome to ' + lGoofySpeedway + '.', 'Hi, my name is ' + Goofy + ". What's yours?", "Gawrsh, it's nice to see you %!", "Hi there! Pardon my dusty clothes I've been busy fixin' that broken Leaderboard."], ['We better get this Leaderboard working soon, Grand Prix Weekend is coming up!', "Does anybody want to buy a slightly used kart? It's only been through the Leaderboard once!", 'Grand Prix Weekend is coming, better get to practicing.', 'Grand Prix Weekend will be here on Friday, May 22 through Monday, May 25!', "I'm gonna need a ladder to get that kart down.", 'That Toon really wanted to get on the Leaderboard!', 'Boy, I saw a terrific race earlier.', 'Watch out for banana peels on the race track!', 'Have you upgraded your kart lately?', 'We just got in some new rims at the kart shop.', 'Hey, have you seen ' + Donald + '?', 'If you see my friend ' + Mickey + ', say hi to him for me.', "D'oh! I forgot to fix " + Mickey + "'s breakfast!", 'Gawrsh there sure are a lot of ' + Cogs + ' near ' + lDonaldsDock + '.', 'At the Brrrgh branch of my Gag Shop, Hypno-Goggles are on sale for only 1 jellybean!', "Goofy's Gag Shops offer the best jokes, tricks, and funnybone-ticklers in all of Toontown!", "At Goofy's Gag Shops, every pie in the face is guaranteed to make a laugh or you get your Jellybeans back!"], ['I better go get my kart a new paint job for the upcoming Grand Prix Weekend.', "Gosh, I better get workin' on this broken Leaderboard!", "Hope I'll see y'all on Grand Prix Weekend! Goodbye!", "It's time for a nap. I'm going to Dreamland to dream about winnin' the Grand Prix."]) GPGoofySpeedwayChatter = (['Welcome to ' + lGoofySpeedway + '.', 'Welcome to Grand Prix Weekend!', 'Hi, my name is ' + Goofy + ". What's yours?", "Gawrsh, it's nice to see you %!"], ['Are you excited about the Grand Prix Weekend?', 'Grand Prix Weekend really drives up those scores!', 'Get more tickets by racing practice laps.', "Gawrsh, you're a fast racer!", 'Boy, I saw a terrific race earlier.', 'Watch out for banana peels on the race track!', 'Have you upgraded your kart lately?', 'We just got in some new rims at the kart shop.', 'Hey, have you seen ' + Donald + '? He said he was gonna come watch the Grand Prix!', 'If you see my friend ' + Mickey + ", tell him he's missing some great racing!", "D'oh! I forgot to fix " + Mickey + "'s breakfast!", 'Gawrsh there sure are a lot of ' + Cogs + ' near ' + lDonaldsDock + '.', 'At the Brrrgh branch of my Gag Shop, Hypno-Goggles are on sale for only 1 jellybean!', "Goofy's Gag Shops offer the best jokes, tricks, and funnybone-ticklers in all of Toontown!", "At Goofy's Gag Shops, every pie in the face is guaranteed to make a laugh or you get your Jellybeans back!"], ['Good luck in the Grand Prix!', "I'm going to catch the next race in the Grand Prix!", 'Gawrsh I think the next race is about to start!', 'Gosh, I better go check on the new Leaderboard and make sure it is working right!']) SillyPhase1Chatter = ["If you haven't seen the Silly Meter, head to Toon Hall!", 'Toontown is getting sillier by the day!', "Cause silly surges in battle to boost Toontown's silly levels!", 'Objects on the street are starting to animate!', 'I saw a fire hydrant on Silly Street move!'] SillyPhase2Chatter = ['Silly levels are still rising!', 'The Silly Meter has climbed higher and gotten crazier!', 'Someone saw a trash can moving on Maple Street!', 'A lot of hydrants on Silly Street have come alive!', 'A mailbox on Lighthouse Lane has gone nuts!', 'Go see the Silly Meter in Toon Hall!', 'Keep causing those silly surges!'] SillyPhase3Chatter = ['The Cogs hate how silly Toontown is becoming!', 'Keep a sharp eye out for Cog Invasions!', 'Cog Invasions have caused the silly levels to drop!', 'The Silly Meter went down after the Cog Invasions!', 'Every street of Toontown has animated objects now!', 'Toontown is sillier than ever!'] SillyPhase4Chatter = ['Fire hydrants make your Squirt Gags squirtier!', 'Mail Boxes give your Throw Gags a special delivery!', 'Those crazy Trash Cans can help boost your Toon-up!', 'Objects on the street can help you in battle!', "I just know we'll get the Silly Meter back up soon!", 'Enjoy the sillier Toontown!'] for chatter in [MickeyChatter, DonaldChatter, MinnieChatter, GoofyChatter]: chatter[0].extend(SharedChatterGreetings) chatter[1].extend(SharedChatterComments) chatter[2].extend(SharedChatterGoodbyes) BoringTopic = 'Boring' EmceeDialoguePhase1Topic = 'EmceeDialoguePhase1' EmceeDialoguePhase2Topic = 'EmceeDialoguePhase2' EmceeDialoguePhase3Topic = 'EmceeDialoguePhase3' EmceeDialoguePhase3_5Topic = 'EmceeDialoguePhase3.5' EmceeDialoguePhase4Topic = 'EmceeDialoguePhase4' EmceeDialoguePhase5Topic = 'EmceeDialoguePhase5' EmceeDialoguePhase6Topic = 'EmceeDialoguePhase6' AprilToonsPhasePreTopTopic = 'AprilToonsPhasePreTopTopic' AprilToonsPhaseTopTopic = 'AprilToonsPhaseTopTopic' AprilToonsExtPhaseTopTopic = 'AprilToonsExtPhaseTopTopic' AprilToonsPhasePostTopTopic = 'AprilToonsPhasePostTopTopic' toontownDialogues = {BoringTopic: {(1, 2018): ['Hello Albert', 'It looks like the sillyness levels are rising', 'Yes and dont forget April Toons!'], (2, 2019): ['Hello Newton', 'Yes I wonder how much the parties are contributing to all this'], (3, 2020): ['Why hello there Albert and Newton', 'Halloween was pretty silly too!']}, AprilToonsPhasePreTopTopic: {(1, 2020): ['Gadzooks! The Silly Meter has come back to life!', "It's rising every day, and will reach the top soon!", 'When it does, something silly is sure to happen!', 'So get ready to get ridiculous!']}, AprilToonsPhaseTopTopic: {(1, 2020): ['The Silly Meter has hit the top!', 'Doodles are talking, Estates are bouncy!', "There's only one thing to say\xe2\x80\xa6", 'HAPPY APRIL TOONS!']}, AprilToonsExtPhaseTopTopic: {(1, 2020): ['The Silly Meter has hit the top!', 'Doodles are talking, Estates are bouncy!']}, AprilToonsPhasePostTopTopic: {(1, 2020): ['April Toons is over!', "It's time for us to return to our lab.", 'But when things get REALLY crazy again\xe2\x80\xa6', 'The Silly Meter will return!']}, EmceeDialoguePhase1Topic: {(1, 2020): ['Fellow Toons, this is the Silly Meter!', "It is tracking Toontown's rising silly levels...", 'Which are causing objects on the street to animate!', 'And YOU can help push these levels higher!', 'Battle Cogs to cause Silly Surges...', 'Make Toontown sillier than ever...', "And let's watch the world come alive!", "Now I'll repeat what I said, but only once more."]}, EmceeDialoguePhase2Topic: {(1, 2020): ['Good Gag work, Toons!', "You're keeping those silly levels rising...", 'And Toontown is getting sillier every day!', 'Fire hydrants, trash cans, and mailboxes are springing to life...', 'Making the world more animated than ever!', "You know the Cogs aren't happy about this...", 'But Toons sure are!']}, EmceeDialoguePhase3Topic: {(1, 2020): ['Gadzooks! The Silly Meter is even crazier than expected!', 'Your Silly Surges are working wonders...', 'And Toontown is getting more animated every day!', 'Keep up the good Gag work...', 'And lets see how silly we can make Toontown!', "You know the Cogs aren't happy about what's going on...", 'But Toons sure are!']}, EmceeDialoguePhase3_5Topic: {(1, 2020): ['YOU DID IT TOONS!', 'You brought the streets of Toontown to life!', 'You deserve a reward!', 'Enter the code SILLYMETER in your Shticker Book...', '...to get a Silly Meter T-Shirt!']}, EmceeDialoguePhase4Topic: {(1, 2020): ['Attention all Toons!', 'The sudden Cog invasions have been an unhappy event.', 'As a result, silly levels have rapidly fallen...', 'And no new objects are coming to life.', 'But those that have are very thankful...', "So perhaps they'll find a way to show their appreciation!", 'Stay Tooned!']}, EmceeDialoguePhase5Topic: {(1, 2020): ['Attention all Toons!', 'The Cog invasions have been an unhappy event.', 'As a result, silly levels have rapidly fallen...', 'And no new objects are coming to life.', 'But those that have are very thankful...', 'And are showing their appreciation by helping in battle!', 'We may hold off the Cogs yet, so keep up the fight!']}, EmceeDialoguePhase6Topic: {(1, 2020): ['Congratulations Toons!', 'You all succesfully held off the Cog Invasions...', 'With a little help from our newly animated friends...', 'And brought Toontown back to its usual silly self!', 'We hope to get the Silly Meter rising again soon...', 'So in the meantime, keep up the Cog fight...', 'And enjoy the silliest place ever, Toontown!']}} FriendsListPanelNewFriend = 'New Friend' FriendsListPanelSecrets = 'True Friend' FriendsListPanelOnlineFriends = 'ONLINE TOON\nFRIENDS' FriendsListPanelAllFriends = 'ALL TOON\nFRIENDS' FriendsListPanelIgnoredFriends = 'IGNORED\nTOONS' FriendsListPanelPets = 'NEARBY\nPETS' FriendsListPanelPlayers = 'ALL PLAYER\nFRIENDS' FriendsListPanelOnlinePlayers = 'ONLINE PLAYER\nFRIENDS' FriendInviterClickToon = 'Click on the toon you would like to make friends with.\n\n(You have %s friends)' FriendInviterToon = 'Toon' FriendInviterThatToon = 'That toon' FriendInviterPlayer = 'Player' FriendInviterThatPlayer = 'That player' FriendInviterBegin = 'What type of friend would you like to make?' FriendInviterToonFriendInfo = 'A friend only in Toontown' FriendInviterPlayerFriendInfo = 'A friend across the Town Toon Wacky Silly 3 network' FriendInviterToonTooMany = 'You have too many toon friends to add another one now. You will have to remove some toon friends if you want to make friends with %s. You could also try making player friends them.' FriendInviterPlayerTooMany = 'You have too many player friends to add another one now. You will have to remove some player friends if you want to make friends with %s. You could also try making toon friends with them.' FriendInviterToonAlready = '%s is already your toon friend.' FriendInviterPlayerAlready = '%s is already your player friend.' FriendInviterStopBeingToonFriends = 'Stop being toon friends' FriendInviterStopBeingPlayerFriends = 'Stop being player friends' FriendInviterEndFriendshipToon = 'Are you sure you want to stop being toon friends with %s?' FriendInviterEndFriendshipPlayer = 'Are you sure you want to stop being player friends with %s?' FriendInviterRemainToon = '\n(You will still be toon friends with %s)' FriendInviterRemainPlayer = '\n(You will still be player friends with %s)' DownloadForceAcknowledgeVerbList = ['painted', 'unpacked', 'unfolded', 'drawn', 'inflated', 'built'] DownloadForceAcknowledgeMsg = 'Sorry, the %(phase)s area is still being %(verb)s, and will be ready for you in a minute.' TeaserTop = '' TeaserBottom = '' TeaserDefault = ',\nyou need to become a Member.\n\nJoin us!' TeaserOtherHoods = 'For unlimited adventures in all 6 neighborhoods' TeaserTypeAName = 'Type in your favorite name for your Toon!' TeaserSixToons = 'To play more than one Toon' TeaserClothing = 'To buy items from the Cattlelog \nto customize your toon' TeaserCogHQ = 'To access awesome Cog HQs' TeaserSecretChat = 'To use the True Friends Chat feature' TeaserSpecies = 'To pick this type of Toon' TeaserFishing = 'To fish in all 6 neighborhoods' TeaserGolf = 'To play Toon MiniGolf' TeaserParties = 'To plan a party' TeaserSubscribe = 'Subscribe' TeaserContinue = 'Return To Game' TeaserEmotions = 'To make your Toon more expressive' TeaserKarting = 'To access unlimited Kart Racing' TeaserKartingAccessories = 'To customize your Kart' TeaserGardening = 'To continue gardening at your Toon Estate' TeaserHaveFun = 'Have more fun!' TeaserJoinUs = 'Join us!' TeaserPlantGags = 'To plant these gags' TeaserPickGags = 'To pick these gags' TeaserRestockGags = 'To restock these gags' TeaserGetGags = 'To get these gags' TeaserUseGags = 'To use these gags' TeaserMinigames = TeaserOtherHoods TeaserQuests = TeaserOtherHoods TeaserOtherGags = TeaserOtherHoods TeaserTricks = TeaserOtherHoods LauncherPhaseNames = {0: 'Initialization', 1: 'Panda', 2: 'Engine', 3: 'Make-A-Toon', 3.5: 'Toontorial', 4: 'Playground', 5: 'Streets', 5.5: 'Estates', 6: 'Neighborhoods I', 7: Cog + ' Buildings', 8: 'Neighborhoods II', 9: Sellbot + ' HQ', 10: Cashbot + ' HQ', 11: Lawbot + ' HQ', 12: Bossbot + ' HQ', 13: 'Parties'} LauncherProgress = '%(name)s (%(current)s of %(total)s)' LauncherStartingMessage = "Starting Town Toon Wacky Silly 3... " LauncherDownloadFile = 'Downloading update for ' + LauncherProgress + '...' LauncherDownloadFileBytes = 'Downloading update for ' + LauncherProgress + ': %(bytes)s' LauncherDownloadFilePercent = 'Downloading update for ' + LauncherProgress + ': %(percent)s%%' LauncherDecompressingFile = 'Decompressing update for ' + LauncherProgress + '...' LauncherDecompressingPercent = 'Decompressing update for ' + LauncherProgress + ': %(percent)s%%' LauncherExtractingFile = 'Extracting update for ' + LauncherProgress + '...' LauncherExtractingPercent = 'Extracting update for ' + LauncherProgress + ': %(percent)s%%' LauncherPatchingFile = 'Applying update for ' + LauncherProgress + '...' LauncherPatchingPercent = 'Applying update for ' + LauncherProgress + ': %(percent)s%%' LauncherConnectProxyAttempt = 'Connecting to Town Toon Wacky Silly 3: %s (proxy: %s) attempt: %s' LauncherConnectAttempt = 'Connecting to Town Toon Wacky Silly 3: %s attempt %s' LauncherDownloadServerFileList = 'Updating Town Toon Wacky Silly 3...' LauncherCreatingDownloadDb = 'Updating Town Toon Wacky Silly 3...' LauncherDownloadClientFileList = 'Updating Town Toon Wacky Silly 3...' LauncherFinishedDownloadDb = 'Updating Town Toon Wacky Silly 3... ' LauncherStartingGame = 'Starting Town Toon Wacky Silly 3...' LauncherRecoverFiles = 'Updating Town Toon Wacky Silly 3. Recovering files...' LauncherCheckUpdates = 'Checking for updates for ' + LauncherProgress LauncherVerifyPhase = 'Updating Town Toon Wacky Silly 3...' LoadingDownloadWatcherUpdate = 'Loading %s' AvatarChoiceMakeAToon = 'Make A\nToon' AvatarChoicePlayThisToon = 'Play\nThis Toon' AvatarChoiceSubscribersOnly = 'Subscribe' AvatarChoiceDelete = 'Delete' AvatarChoiceDeleteConfirm = 'This will delete %s forever.' AvatarChoiceNameRejected = 'Name\nRejected' AvatarChoiceNameApproved = 'Name\nApproved!' AvatarChoiceNameReview = 'Under\nReview' AvatarChoiceNameYourToon = 'Name\nYour Toon!' AvatarChoiceDeletePasswordText = 'Careful! This will delete %s forever. To delete this Toon, enter your password.' AvatarChoiceDeleteConfirmText = 'Careful! This will delete %(name)s forever. If you are sure you want to do this, type "%(confirm)s" and click OK.' AvatarChoiceDeleteConfirmUserTypes = 'delete' AvatarChoiceDeletePasswordTitle = 'Delete Toon?' AvatarChoicePassword = 'Password' AvatarChoiceDeletePasswordOK = lOK AvatarChoiceDeletePasswordCancel = lCancel AvatarChoiceDeleteWrongPassword = 'That password does not seem to match. To delete this Toon, enter your password.' AvatarChoiceDeleteWrongConfirm = 'You didn\'t type the right thing. To delete %(name)s, type "%(confirm)s" and click OK. Do not type the quotation marks. Click Cancel if you have changed your mind.' AvatarChooserPickAToon = 'Pick A Toon To Play' AvatarChooserQuit = lQuit DateOfBirthEntryMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] DateOfBirthEntryDefaultLabel = 'Date of Birth' PhotoPageTitle = 'Snapshots' PhotoPageNoName = 'Unnamed' PhotoPageUnknownName = 'Unknown' PhotoPageAddName = 'Add Caption' PhotoPageAddNamePanel = 'Add a Caption to this Snapshot:' PhotoPageDelete = 'Are you sure you want to delete' PhotoPageConfirm = 'Yep!' PhotoPageCancel = lCancel PhotoPageClose = lClose PhotoPageDirectory = 'Open Folder' PhotoPageTutorial = 'You haven\'t taken any snapshots yet! Press TAB to change your camera angle, and press F9 to take a snapshot.\n\n Once you\'ve made a snapshot, come here to manage and name them.' AchievePageTitle = 'Achievements\n(Coming Soon)' BuildingPageTitle = 'Buildings\n(Coming Soon)' InventoryPageTitle = 'Gags' InventoryPageDeleteTitle = 'DELETE GAGS' InventoryPageTrackFull = 'You have all the gags in the %s track.' InventoryPagePluralPoints = 'You will get a new\n%(trackName)s gag when you\nget %(numPoints)s more %(trackName)s points.' InventoryPageSinglePoint = 'You will get a new\n%(trackName)s gag when you\nget %(numPoints)s more %(trackName)s point.' InventoryPageNoAccess = 'You do not have access to the %s track yet.' NPCFriendPageTitle = 'SOS Toons' NPCFriendPageDelete = 'Delete' NPCFriendPageDeleteConfirmation = 'Are you sure you want to delete this SOS card?' PartyDateFormat = '%(mm)s %(dd)d, %(yyyy).4d' PartyTimeFormat = '%d:%.2d %s' PartyTimeFormatMeridiemAM = 'am' PartyTimeFormatMeridiemPM = 'pm' PartyCanStart = "It's Party Time, click Start Party in your Shticker Book Hosting page!" PartyHasStartedAcceptedInvite = '%s party has started! Click the host then "Go To Party" in the Shticker Book Invites page.' PartyHasStartedNotAcceptedInvite = '%s party has started! You can still go to it by teleporting to the host.' EventsPageName = 'Events' EventsPageCalendarTabName = 'Calendar' EventsPageCalendarTabParty = 'Party' EventsPageToontownTimeIs = 'TOONTOWN TIME IS' EventsPageConfirmCancel = 'If you cancel, you will get a %d%% refund. Are you sure you want to cancel your party?' EventsPageCancelPartyResultOk = 'Your party was cancelled and you got %d Jellybeans back!' EventsPageCancelPartyResultError = 'Sorry, your party was not cancelled.' EventsPageCancelPartyAlreadyRefunded = 'Your party was never started. Check your mailbox for your refund!' EventsPageTooLateToStart = 'Sorry, it is too late to start your party. You can cancel it and plan another one.' EventsPagePublicPrivateChange = "Changing your party's privacy setting..." EventsPagePublicPrivateNoGo = "Sorry, you can't change your party's privacy setting right now." EventsPagePublicPrivateAlreadyStarted = "Sorry, your party has already started, so you can't change your party's privacy setting." EventsPageHostTabName = 'Hosting' EventsPageHostTabTitle = 'My Next Party' EventsPageHostTabTitleNoParties = 'No Parties' EventsPageHostTabDateTimeLabel = 'You are having a party on %s at %s Toontown Time.' EventsPageHostingTabNoParty = 'Go to a playground\nParty Gate to plan\nyour own party!' EventsPageHostTabPublicPrivateLabel = 'This party is:' EventsPageHostTabToggleToPrivate = 'Private' EventsPageHostTabToggleToPublic = 'Public' EventsPageHostingTabGuestListTitle = 'Guests' EventsPageHostingTabActivityListTitle = 'Activities' EventsPageHostingTabDecorationsListTitle = 'Decorations' EventsPageHostingTabPartiesListTitle = 'Hosts' EventsPageHostTabCancelButton = 'Cancel Party' EventsPageGoButton = 'Start\nParty!' EventsPageGoBackButton = 'Party\nNow!' EventsPageInviteGoButton = 'Go to\nParty!' EventsPageUnknownToon = 'Unknown Toon' EventsPageInvitedTabName = 'Invitations' EventsPageInvitedTabTitle = 'Party Invitations' EventsPageInvitedTabInvitationListTitle = 'Invitations' EventsPageInvitedTabActivityListTitle = 'Activities' EventsPageInvitedTabTime = '%s %s Toontown Time' EventsPageNewsTabName = 'News' EventsPageNewsTabTitle = 'News' EventsPageNewsDownloading = 'Retrieving News...' EventsPageNewsUnavailable = 'Chip and Dale played with the printing press. News not available.' EventsPageNewsPaperTitle = 'TOONTOWN TIMES' EventsPageNewsLeftSubtitle = 'Still only 1 jellybean' EventsPageNewsRightSubtitle = 'Established toon-thousand nine' NewsPageName = 'News' NewsPageImportError = 'Whoops! There is an issue loading the "Toon News ... for the Amused!" Please check back later.' NewsPageDownloadingNewsSubstr = 'Stay Tooned, while we bring you the latest issue of the \n"Toon News ... for the Amused!"' NewsPageDownloadingNews0 = NewsPageDownloadingNewsSubstr + ' %s%% Complete.' NewsPageDownloadingNews1 = NewsPageDownloadingNewsSubstr + ' %s%% Complete..' NewsPageDownloadingNews2 = NewsPageDownloadingNewsSubstr + ' %s%% Complete...' NewsPageErrorDownloadingFile = 'Whoops! Page %s is missing from "Toon News ... for the Amused!" Please check back later.' NewsPageErrorDownloadingFileCanStillRead = 'Whoops! Page %s \nis missing from the "Toon News ... for the Amused!" \nTurn the page to continue, while we work to get this page back.' NewsPageNoIssues = 'Whoops! The "Toon News ... for the Amused!" has gone missing! \nStay Tooned ... while we work to bring the news back!' IssueFrameThisWeek = 'this week' IssueFrameLastWeek = 'last week' IssueFrameWeeksAgo = '%d weeks ago' SelectedInvitationInformation = '%s is having a party on %s at %s Toontown Time.' PartyPlannerNextButton = 'Continue' PartyPlannerPreviousButton = 'Back' PartyPlannerWelcomeTitle = 'Toontown Party Planner' PartyPlannerInstructions = 'Hosting your own party is a lot of fun!\nStart planning with the arrows at the bottom!' PartyPlannerDateTitle = 'Pick A Day For Your Party' PartyPlannerTimeTitle = 'Pick A Time For Your Party' PartyPlannerGuestTitle = 'Choose Your Guests' PartyPlannerEditorTitle = 'Design Your Party\nPlace Activities and Decorations' PartyPlannerConfirmTitle = 'Choose Invitations To Send' PartyPlannerConfirmTitleNoFriends = 'Double Check Your Party' PartyPlannerTimeToontown = 'Toontown' PartyPlannerTimeTime = 'Time' PartyPlannerTimeRecap = 'Party Date and Time' PartyPlannerPartyNow = 'As Soon As Possible' PartyPlannerTimeToontownTime = 'Toontown Time:' PartyPlannerTimeLocalTime = 'Party Local Time : ' PartyPlannerPublicPrivateLabel = 'This party will be:' PartyPlannerPublicDescription = 'Any Toon\ncan come!' PartyPlannerPrivateDescription = 'Only\nInvited Toons\ncan come!' PartyPlannerPublic = 'Public' PartyPlannerPrivate = 'Private' PartyPlannerCheckAll = 'Check\nAll' PartyPlannerUncheckAll = 'Uncheck\nAll' PartyPlannerDateText = 'Date' PartyPlannerTimeText = 'Time' PartyPlannerTTTimeText = 'Toontown Time' PartyPlannerEditorInstructionsIdle = 'Click on the Party Activity or Decoration you would like to purchase.' PartyPlannerEditorInstructionsClickedElementActivity = 'Click Buy or Drag the Activity Icon onto the Party Grounds Map' PartyPlannerEditorInstructionsClickedElementDecoration = 'Click Buy or Drag the Decoration onto the Party Grounds Map' PartyPlannerEditorInstructionsDraggingActivity = 'Drag the Activity onto the Party Grounds Map.' PartyPlannerEditorInstructionsDraggingDecoration = 'Drag the Activity onto the Party Grounds Map.' PartyPlannerEditorInstructionsPartyGrounds = 'Click and Drag items to move them around the Party Grounds Map' PartyPlannerEditorInstructionsTrash = 'Drag an Activity or Decoration here to remove it.' PartyPlannerEditorInstructionsNoRoom = 'There is no room to place that activity.' PartyPlannerEditorInstructionsRemoved = '%(removed)s removed since %(added)s was added.' PartyPlannerBeans = 'beans' PartyPlannerTotalCost = 'Total Cost:\n%d beans' PartyPlannerSoldOut = 'SOLD OUT' PartyPlannerBuy = 'BUY' PartyPlannerPaidOnly = 'MEMBERS ONLY' PartyPlannerPartyGrounds = 'PARTY GROUNDS MAP' PartyPlannerOkWithGroundsLayout = 'Are you done moving your Party Activities and Decorations around the Party Grounds Map?' PartyPlannerChooseFutureTime = 'Please choose a time in the future.' PartyPlannerInviteButton = 'Send Invites' PartyPlannerInviteButtonNoFriends = 'Plan Party' PartyPlannerBirthdayTheme = 'Birthday' PartyPlannerGenericMaleTheme = 'Star' PartyPlannerGenericFemaleTheme = 'Flower' PartyPlannerRacingTheme = 'Racing' PartyPlannerValentoonsTheme = 'ValenToons' PartyPlannerVictoryPartyTheme = 'Victory' PartyPlannerWinterPartyTheme = 'Winter' PartyPlannerGuestName = 'Guest Name' PartyPlannerClosePlanner = 'Close Planner' PartyPlannerConfirmationAllOkTitle = 'Congratulations!' PartyPlannerConfirmationAllOkText = 'Your party has been created and your invitations sent out.\nThanks!' PartyPlannerConfirmationAllOkTextNoFriends = 'Your party has been created!\nThanks!' PartyPlannerConfirmationErrorTitle = 'Oops.' PartyPlannerConfirmationValidationErrorText = 'Sorry, there seems to be a problem\nwith that party.\nPlease go back and try again.' PartyPlannerConfirmationDatabaseErrorText = "Sorry, I couldn't record all your information.\nPlease try again later.\nDon't worry, no beans were lost." PartyPlannerConfirmationTooManyText = 'Sorry, you are already hosting a party.\nIf you want to plan another party, please\ncancel your current party.' PartyPlannerInvitationThemeWhatSentence = 'You are invited to my %s party! %s!' PartyPlannerInvitationThemeWhatSentenceNoFriends = 'I am hosting a %s party! %s!' PartyPlannerInvitationThemeWhatActivitiesBeginning = 'It will have ' PartyPlannerInvitationWhoseSentence = '%s Party' PartyPlannerInvitationTheme = 'Theme' PartyPlannerInvitationWhenSentence = 'It will be on %s,\nat %s Toontown Time.\nHope you can make it!' PartyPlannerInvitationWhenSentenceNoFriends = 'It will be on %s,\nat %s Toontown Time.\nToontastic!' PartyPlannerComingSoon = 'Coming Soon' PartyPlannerCantBuy = "Can't Buy" PartyPlannerGenericName = 'Party Planner' PartyJukeboxOccupied = 'Someone else is using the jukebox. Try again later.' PartyJukeboxNowPlaying = 'The song you chose is now playing on the jukebox!' MusicEncntrGeneralBg = 'Encounter With Cogs' MusicTcSzActivity = 'Toontorial Medley' MusicTcSz = 'Strolling Along' MusicCreateAToon = 'The New Toon in Town' MusicTtTheme = 'The Toontown Theme' MusicMinigameRace = 'Slow and Steady' MusicMgPairing = 'Remember Me?' MusicTcNbrhood = 'Toontown Central' MusicMgDiving = 'Treasure Lullaby' MusicMgCannonGame = 'Fire the Cannons!' MusicMgTwodgame = 'Running Toon' MusicMgCogthief = 'Catch That Cog!' MusicMgTravel = 'Traveling Music' MusicMgTugOWar = 'Tug-of-War' MusicMgVine = 'The Jungle Swing' MusicMgIcegame = 'Slippery Situation' MusicMgToontag = 'Minigame Medley' MusicMMatchBg2 = 'Jazzy Minnie' MusicMgTarget = "Soarin' Over Toontown" MusicFfSafezone = 'The Funny Farm' MusicDdSz = 'Waddling Way' MusicMmNbrhood = "Minnie's Melodyland" MusicGzPlaygolf = "Let's Play Golf!" MusicGsSz = 'Goofy Speedway' MusicOzSz = "Chip n' Dale's Acres" MusicGsRaceCc = 'Downtown Driving' MusicGsRaceSs = 'Ready, Set, Go!' MusicGsRaceRr = 'Route 66' MusicGzSz = 'The Putt-Putt Polka' MusicMmSz = 'Dancing in the Streets' MusicMmSzActivity = 'Here Comes Treble' MusicDdNbrhood = "Donald's Dock" MusicGsKartshop = 'Mr. Goofywrench' MusicDdSzActivity = 'Sea Shanty' MusicEncntrGeneralBgIndoor = 'Building Excitement' MusicTtElevator = 'Going Up?' MusicEncntrToonWinningIndoor = 'Toons Unite!' MusicEncntrGeneralSuitWinningIndoor = 'Cog-tastrophe!' MusicTbNbrhood = 'The Brrrgh' MusicDlNbrhood = "Donald's Dreamland" MusicDlSzActivity = 'Counting Sheep' MusicDgSz = 'Waltz of the Flowers' MusicDlSz = 'Sleepwalking' MusicTbSzActivity = 'Snow Problem' MusicTbSz = 'Shiver and Shimmy' MusicDgNbrhood = "Daisy's Garden" MusicEncntrHallOfFame = 'The Hall of Fame' MusicEncntrSuitHqNbrhood = 'Dollars and Cents' MusicChqFactBg = 'Cog Factory' MusicCoghqFinale = 'Triumph of the Toons' MusicEncntrToonWinning = 'Cashing In!' MusicEncntrSuitWinning = 'Selling You Short' MusicEncntrHeadSuitTheme = 'The Big Boss' MusicLbJurybg = 'Court is in Session' MusicLbCourtyard = 'Balancing Act' MusicBossbotCeoV2 = 'Search Engine' MusicBossbotFactoryV1 = 'Cog Waltz' MusicBossbotCeoV1 = 'Bossing You Around' MusicPartyOriginalTheme = 'Party Time' MusicPartyPolkaDance = 'Party Polka' MusicPartySwingDance = 'Party Swing' MusicPartyWaltzDance = 'Party Waltz' MusicPartyGenericThemeJazzy = 'Party Jazz' MusicPartyGenericTheme = 'Party Jingle' JukeboxAddSong = 'Add\nSong' JukeboxReplaceSong = 'Replace\nSong' JukeboxQueueLabel = 'Playing Next:' JukeboxSongsLabel = 'Pick a Song:' JukeboxClose = 'Done' JukeboxCurrentlyPlaying = 'Currently Playing' JukeboxCurrentlyPlayingNothing = 'Jukebox is paused.' JukeboxCurrentSongNothing = 'Add a song to the playlist!' PartyOverWarningNoName = 'The party has ended! Thanks for coming!' PartyOverWarningWithName = '%s party has ended! Thanks for coming!' PartyCountdownClockText = 'Time\n\nLeft' PartyTitleText = '%s Party' PartyActivityConjunction = ', and' PartyActivityNameDict = {0: {'generic': 'Jukebox', 'invite': 'a Jukebox', 'editor': 'Jukebox', 'description': 'Listen to music with your own jukebox!'}, 1: {'generic': 'Party Cannons', 'invite': 'Party Cannons', 'editor': 'Cannons', 'description': 'Fire yourself out of the cannons and into fun!'}, 2: {'generic': 'Trampoline', 'invite': 'Trampoline', 'editor': 'Trampoline', 'description': 'Collect Jellybeans and bounce the highest!'}, 3: {'generic': 'Party Catch', 'invite': 'Party Catch', 'editor': 'Party Catch', 'description': 'Catch fruit to win beans! Dodge those anvils!'}, 4: {'generic': 'Dance Floor\n10 moves', 'invite': 'a 10 move Dance Floor', 'editor': 'Dance Floor - 10', 'description': 'Show off all 10 of your moves, toon style!'}, 5: {'generic': 'Party Tug-of-War', 'invite': 'Party Tug-of-War', 'editor': 'Tug-of-War', 'description': 'Up to 4 on 4 toon tugging craziness!'}, 6: {'generic': 'Party Fireworks', 'invite': 'Party Fireworks', 'editor': 'Fireworks', 'description': 'Launch your very own fireworks show!'}, 7: {'generic': 'Party Clock', 'invite': 'a Party Clock', 'editor': 'Party Clock', 'description': 'Counts down the time left in your party.'}, 8: {'generic': 'Deluxe Jukebox', 'invite': 'a deluxe jukebox', 'editor': 'Deluxe Jukebox', 'description': 'Your own deluxe jukebox with double the tunes!'}, 9: {'generic': 'Dance Floor\n20 moves', 'invite': 'a 20 move Dance Floor', 'editor': 'Dance Floor - 20', 'description': 'Show off all 20 of your moves, toon style!'}, 10: {'generic': 'Cog-O-War', 'invite': 'Cog-O-War', 'editor': 'Cog-O-War', 'description': 'The team vs. team game of Cog splatting!'}, 11: {'generic': 'Cog Trampoline', 'invite': 'Cog Trampoline', 'editor': 'Cog Trampoline', 'description': "Jump on a Cog's face!"}, 12: {'generic': 'Present Catch', 'invite': 'Present Catch', 'editor': 'Present Catch', 'description': 'Catch presents to win beans! Dodge those anvils!'}, 13: {'generic': 'Holiday Trampoline', 'invite': 'Holiday Trampoline', 'editor': 'Holiday Trampoline', 'description': 'Jump if you love Winter Holidays!'}, 14: {'generic': 'Holiday Cog-O-War', 'invite': 'Holiday Cog-O-War', 'editor': 'Holiday Cog-O-War', 'description': 'The team vs. team game of Cog splattering!'}, 15: {'generic': 'Dance Floor\n10 moves', 'invite': 'a 10 move ValenToons Dance Floor', 'editor': 'Dance Floor - 10', 'description': 'Get your ValenToon Groove On!'}, 16: {'generic': 'Dance Floor\n20 moves', 'invite': 'a 20 move ValenToons Dance Floor', 'editor': 'Dance Floor - 20', 'description': 'Get your ValenToon Groove On!'}, 17: {'generic': 'Jukebox\n20 songs', 'invite': 'a 20 song Valentoons Jukebox', 'editor': 'Jukebox - 20', 'description': 'Nothing sets the mood like music!'}, 18: {'generic': 'Jukebox\n40 songs', 'invite': 'a 40 song Valentoons jukebox', 'editor': 'Jukebox - 40', 'description': 'Nothing sets the mood like music!'}, 19: {'generic': 'Trampoline', 'invite': 'ValenToons Trampoline', 'editor': 'Trampoline', 'description': "Jump to your heart's content!"}} PartyDecorationNameDict = {0: {'editor': 'Balloon Anvil', 'description': 'Try to keep the fun from floating away!'}, 1: {'editor': 'Party Stage', 'description': 'Balloons, stars, what else could you want?'}, 2: {'editor': 'Party Bow', 'description': 'Wrap up the fun!'}, 3: {'editor': 'Cake', 'description': 'Delicious.'}, 4: {'editor': 'Party Castle', 'description': "A Toon's home is his castle."}, 5: {'editor': 'Gift Pile', 'description': 'Gifts for every Toon!'}, 6: {'editor': 'Streamer Horn', 'description': 'This horn is a hoot! Streamers!'}, 7: {'editor': 'Party Gate', 'description': 'Multi-colored and crazy!'}, 8: {'editor': 'Noise Makers', 'description': 'Tweeeeet!'}, 9: {'editor': 'Pinwheel', 'description': 'Colorful twirling for everyone!'}, 10: {'editor': 'Gag Globe', 'description': 'Gag and star globe designed by Olivea'}, 11: {'editor': 'Bean Banner', 'description': 'A Jellybean banner designed by Cassidy'}, 12: {'editor': 'Gag Cake', 'description': 'A Topsy Turvy gag cake designed by Felicia'}, 13: {'editor': "Cupid's Heart", 'description': 'Ready...Aim...\nValenToons!'}, 14: {'editor': 'Candy Hearts\n Banner', 'description': "Who doesn't love candy hearts?"}, 15: {'editor': 'Flying Heart', 'description': 'This heart is getting carried away!'}, 16: {'editor': 'Victory Bandstand', 'description': 'All our new friends are ready to dance!'}, 17: {'editor': 'Victory Banner', 'description': 'Not just a normal banner!'}, 18: {'editor': 'Confetti Cannons', 'description': 'BOOM! Confetti! Fun!'}, 19: {'editor': 'Cog & Doodle', 'description': "Ouch! That's gotta hurt."}, 20: {'editor': 'Cog Flappy Man', 'description': 'A Cog full of hot air, what a shock!'}, 21: {'editor': 'Cog Ice Cream', 'description': 'A Cog looking his best.'}, 22: {'editor': 'CogCicle', 'description': 'A Cog looking his holiday best.'}, 23: {'editor': 'Holiday Bandstand', 'description': 'Everyone loves a Holiday Party!'}, 24: {'editor': 'Chilly Cog', 'description': "Ouch! That's gotta hurt."}, 25: {'editor': 'Snowman', 'description': "So cool, he's hot!"}, 26: {'editor': 'SnowDoodle', 'description': 'His only trick is being cold!'}, 27: {'editor': 'ValenToons Anvil', 'description': "We've got your heart on a string!"}} ActivityLabel = 'Cost - Activity Name' PartyDoYouWantToPlan = 'Would you like to plan a new party right now?' PartyPlannerOnYourWay = 'Have fun planning your party!' PartyPlannerMaybeNextTime = 'Maybe next time. Have a good day!' PartyPlannerHostingTooMany = 'You can only host one party at a time, sorry.' PartyPlannerOnlyPaid = 'Only paid toons can host a party, sorry.' PartyPlannerNpcComingSoon = 'Parties are coming soon! Try again later.' PartyPlannerNpcMinCost = 'It costs a minimum of %d Jellybeans to plan a party.' PartyHatPublicPartyChoose = 'Do you want to go to the 1st available public party?' PartyGateTitle = 'Public Parties' PartyGateGoToParty = 'Go to\nParty!' PartyGatePartiesListTitle = 'Hosts' PartyGatesPartiesListToons = 'Toons' PartyGatesPartiesListActivities = 'Activities' PartyGatesPartiesListMinLeft = 'Minutes Left' PartyGateLeftSign = 'Come On In!' PartyGateRightSign = 'Public Parties Here!' PartyGatePartyUnavailable = 'Sorry. That party is no longer available.' PartyGatePartyFull = 'Sorry. That party is full.' PartyGateInstructions = 'Click on a host, then click on "Go to Party"' PartyActivityWaitingForOtherPlayers = 'Waiting for other players to join the party game...' PartyActivityPleaseWait = 'Please wait...' DefaultPartyActivityTitle = 'Party Game Title' DefaultPartyActivityInstructions = 'PartyGame Instructions' PartyOnlyHostLeverPull = 'Only the host can start this activity. Sorry.' PartyActivityDefaultJoinDeny = 'You cannot join this activity right now. Sorry.' PartyActivityDefaultExitDeny = 'You cannot leave this activity right now. Sorry.' PartyJellybeanRewardOK = 'OK' PartyCatchActivityTitle = 'Party Catch Activity' PartyCatchActivityInstructions = "Catch as many pieces of fruit as you can. Try not to 'catch' any %(badThing)s!" PartyCatchActivityFinishPerfect = 'PERFECT GAME!' PartyCatchActivityFinish = 'Good Game!' PartyCatchActivityExit = 'EXIT' PartyCatchActivityApples = 'apples' PartyCatchActivityOranges = 'oranges' PartyCatchActivityPears = 'pears' PartyCatchActivityCoconuts = 'coconuts' PartyCatchActivityWatermelons = 'watermelons' PartyCatchActivityPineapples = 'pineapples' PartyCatchActivityAnvils = 'anvils' PartyCatchStarted = 'The game has started. Go play it.' PartyCatchCannotStart = 'The game could not start right now.' PartyCatchRewardMessage = 'Pieces of fruit caught: %s\n\nJellybeans earned: %d' WinterPartyCatchActivityInstructions = "Catch as many presents as you can. Try not to 'catch' any %(badThing)s!" WinterPartyCatchRewardMessage = 'Presents caught: %s\n\nJellybeans earned: %s' PartyDanceActivityTitle = 'Party Dance Floor' PartyDanceActivityInstructions = 'Combine 3 or more ARROW KEY patterns to do dance moves! There are 10 dance moves available. Can you find them all?' PartyDanceActivity20Title = 'Party Dance Floor' PartyDanceActivity20Instructions = 'Combine 3 or more ARROW KEY patterns to do dance moves! There are 20 dance moves available. Can you find them all?' DanceAnimRight = 'Right' DanceAnimReelNeutral = 'The Fishertoon' DanceAnimConked = 'The Headbob' DanceAnimHappyDance = 'The Happy Dance' DanceAnimConfused = 'Very Dizzy' DanceAnimWalk = 'Walking on the Moon' DanceAnimJump = 'The Jump!' DanceAnimFirehose = 'The Firetoon' DanceAnimShrug = 'Who Knows?' DanceAnimSlipForward = 'The Fall' DanceAnimSadWalk = 'Tired' DanceAnimWave = 'Hello Goodbye' DanceAnimStruggle = 'The Shuffle Hop' DanceAnimRunningJump = 'The Running Toon' DanceAnimSlipBackward = 'The Backfall' DanceAnimDown = 'Down' DanceAnimUp = 'Up' DanceAnimGoodPutt = 'The Putt' DanceAnimVictory = 'The Victory Dance' DanceAnimPush = 'The Mimetoon' DanceAnimAngry = "Rock n' Roll" DanceAnimLeft = 'Left' PartyCannonActivityTitle = 'Party Cannons' PartyCannonActivityInstructions = 'Hit the clouds to change their color and bounce in the air! While IN THE AIR, you can USE THE ARROW KEYS to GLIDE.' PartyCannonResults = 'You collected %d jelly beans!\n\nNumber of Clouds Hit: %d' FireworksActivityInstructions = 'Look up using the "Page Up" key to see better.' FireworksActivityBeginning = 'Party fireworks are about to start! Enjoy the show!' FireworksActivityEnding = 'Hope you enjoyed the show!' PartyFireworksAlreadyActive = 'The fireworks show has already started.' PartyFireworksAlreadyDone = 'The fireworks show is over.' PartyTrampolineJellyBeanTitle = 'Jelly Beans Trampoline' PartyTrampolineTricksTitle = 'Tricks Trampoline' PartyTrampolineActivityInstructions = 'Use the Control key to jump.\n\nJump when your Toon is at its lowest point on the trampoline to jump higher.' PartyTrampolineActivityOccupied = 'Trampoline in use.' PartyTrampolineQuitEarlyButton = 'Hop Off' PartyTrampolineBeanResults = 'You collected %d jelly beans.' PartyTrampolineBonusBeanResults = 'You collected %d jelly beans, plus %d more for getting the Big Bean. ' PartyTrampolineTopHeightResults = 'Your top height was %d ft.' PartyTrampolineTimesUp = "Time's Up" PartyTrampolineReady = 'Ready...' PartyTrampolineGo = 'Go!' PartyTrampolineBestHeight = 'Best Height So Far:\n%s\n%d ft' PartyTrampolineNoHeightYet = 'How high\ncan you jump?' PartyTrampolineGetHeight = '%d ft' PartyTeamActivityForMorePlural = 's' PartyTeamActivityForMore = 'Waiting for %d player%s\non each side...' PartyTeamActivityForMoreWithBalance = 'Waiting for %d more player%s...' PartyTeamActivityWaitingForOtherPlayers = 'Waiting for other players...' PartyTeamActivityWaitingToStart = 'Starting in...' PartyTeamActivityExitButton = 'Hop Off' PartyTeamActivitySwitchTeamsButton = 'Switch\nTeams' PartyTeamActivityWins = '%s team wins!' PartyTeamActivityLocalAvatarTeamWins = 'Your team won!' PartyTeamActivityGameTie = "It's a tie!" PartyTeamActivityJoinDenied = "Sorry, you can't join %s at this time." PartyTeamActivityExitDenied = 'Sorry, you are unable to leave %s at this time.' PartyTeamActivitySwitchDenied = "Sorry, you cant's switch teams at this time." PartyTeamActivityTeamFull = 'Sorry, that team is already full!' PartyTeamActivityRewardMessage = 'You got %d Jellybeans. Good job!' PartyCogTeams = ('Blue', 'Orange') PartyCogRewardMessage = 'Your Score: %d\n' PartyCogRewardBonus = '\nYou got %d additional jellybean%s because your team won!' PartyCogJellybeanPlural = 's' PartyCogSignNote = 'HI-SCORE\n%s\n%d' PartyCogTitle = 'Cog-O-War' PartyCogInstructions = 'Throw pies at cogs to push them away from your team. ' + "When time's up, the team with most cogs on the other side wins!" + '\n\nThrow with the CONTROL KEY. Move with the ARROW KEYS.' PartyCogDistance = '%d ft' PartyCogTimeUp = "Time's up!" PartyCogGuiScoreLabel = 'SCORE' PartyCogGuiPowerLabel = 'POWER' PartyCogGuiSpamWarning = 'Hold CONTROL for more power!' PartyCogBalanceBar = 'BALANCE' PartyTugOfWarReady = 'Ready...' PartyTugOfWarGo = 'GO!' PartyTugOfWarGameEnd = 'Good game!' PartyTugOfWarTitle = 'Party Tug-of-War' CalendarShowAll = 'Show All' CalendarShowOnlyHolidays = 'Show Only Holidays' CalendarShowOnlyParties = 'Show Only Parties' CalendarEndsAt = 'Ends at ' CalendarStartedOn = 'Started on ' CalendarEndDash = 'End-' CalendarEndOf = 'End of ' CalendarPartyGetReady = 'Get ready!' CalendarPartyGo = 'Go party!' CalendarPartyFinished = "It's over..." CalendarPartyCancelled = 'Cancelled.' CalendarPartyNeverStarted = 'Never Started.' NPCFriendPanelRemaining = '%d Remaining' MapPageTitle = 'Map' MapPageBackToPlayground = 'Back to Playground' MapPageBackToCogHQ = 'Back to Cog HQ' MapPageGoHome = 'Go Home' MapPageYouAreHere = 'You are in: %s\n%s' MapPageYouAreAtHome = 'You are at\nyour estate' MapPageYouAreAtSomeonesHome = 'You are at %s estate' MapPageGoTo = 'Go To\n%s' OptionsPageTitle = 'Options' OptionsPageSpecial = 'Special' OptionsTabTitle = 'Options\n& Codes' OptionsPagePurchase = 'Subscribe' OptionsPageLogout = 'Logout' OptionsPageExitToontown = 'Exit Toontown' OptionsPageMusic = 'Music:' OptionsPageSFX = 'Sound Effects:' OptionsPageToonChatSoundsOnLabel = 'Type Chat Sounds are on.' OptionsPageToonChatSoundsOffLabel = 'Type Chat Sounds are off.' OptionsPageFriendsEnabledLabel = 'Accepting new friend requests.' OptionsPageFriendsDisabledLabel = 'Not accepting friend requests.' OptionsPageWhisperEnabledLabel = 'Allowing whispers from anyone.' OptionsPageWhisperDisabledLabel = 'Allowing whispers from friends only.' OptionsPageSpeedChatStyleLabel = 'SpeedChat Color' OptionsPageDisplayWindowed = 'windowed' OptionsPageDisplayEmbedded = 'In the browser' OptionsPageSelect = 'Select' OptionsPageToggleOn = 'Turn On' OptionsPageToggleOff = 'Turn Off' OptionsPageChange = 'Change' OptionsPageDisplaySettings = 'Display: %(screensize)s, %(api)s' OptionsPageDisplaySettingsNoApi = 'Display: %(screensize)s' OptionsPageExitConfirm = 'Exit Toontown?' DisplaySettingsTitle = 'Display Settings' DisplaySettingsIntro = 'The following settings are used to configure the way Toontown is displayed on your computer. It is usually unnecessary to adjust these unless you are experiencing a problem.' DisplaySettingsIntroSimple = 'You may adjust the screen resolution to a higher value to improve the clarity of text and graphics in Toontown, but depending on your graphics card, some higher values may make the game run less smoothly or may not work at all.' DisplaySettingsApi = 'Graphics API:' DisplaySettingsResolution = 'Resolution:' DisplaySettingsWindowed = 'In a window' DisplaySettingsFullscreen = 'Full screen' DisplaySettingsEmbedded = 'In the browser' DisplaySettingsApply = 'Apply' DisplaySettingsCancel = lCancel DisplaySettingsApplyWarning = 'When you press OK, the display settings will change. If the new configuration does not display properly on your computer, the display will automatically return to its original configuration after %s seconds.' DisplaySettingsAccept = 'Press OK to keep the new settings, or Cancel to revert. If you do not press anything, the settings will automatically revert back in %s seconds.' DisplaySettingsRevertUser = 'Your previous display settings have been restored.' DisplaySettingsRevertFailed = 'The selected display settings do not work on your computer. Your previous display settings have been restored.' OptionsPageCodesTab = 'Enter Code' CdrPageTitle = 'Enter a Code' CdrInstructions = 'Enter your code to receive a special item in your mailbox.' CdrResultSuccess = 'Congratulations! Check your mailbox to claim your item!' CdrResultInvalidCode = "You've entered an invalid code. Please check the code and try again." CdrResultExpiredCode = "We're sorry. This code has expired." CdrResultUnknownError = "We're sorry. This code cannot be applied to your Toon." CdrResultMailboxFull = 'Your mailbox is full. Please remove an item, then enter your code again.' CdrResultAlreadyInMailbox = "You've already received this item. Check your mailbox to confirm." CdrResultAlreadyInQueue = 'Your item is on its way. Check your mailbox in a few minutes to receive it.' CdrResultAlreadyInCloset = "You've already received this item. Check your closet to confirm." CdrResultAlreadyBeingWorn = "You've already received this item, and you are wearing it!" CdrResultAlreadyReceived = "You've already received this item." CdrResultTooManyFails = "We're sorry. You've tried to enter an incorrect code too many times. Please try again after some time." CdrResultServiceUnavailable = "We're sorry. This feature is temporarily unavailable. Please try again during your next login." CdrResultIneligible = "We're sorry, but you aren't eligible for this item!" TrackPageTitle = 'Gag Track Training' TrackPageShortTitle = 'Gag Training' TrackPageSubtitle = 'Complete ToonTasks to learn how to use new gags!' TrackPageTraining = 'You are training to use %s gags.\nWhen you complete all 16 tasks you\nwill be able to use %s gags in battle.' TrackPageClear = 'You are not training any Gag Tracks now.' TrackPageFilmTitle = '%s\nTraining\nFilm' TrackPageDone = 'FIN' QuestPageToonTasks = 'ToonTasks' QuestPageChoose = 'Choose' QuestPageLocked = 'Locked' QuestPageDestination = '%s\n%s\n%s' QuestPageNameAndDestination = '%s\n%s\n%s\n%s' QuestPosterHQOfficer = lHQOfficerM QuestPosterHQBuildingName = lToonHQ QuestPosterHQStreetName = 'Any Street' QuestPosterHQLocationName = 'Any Neighborhood' QuestPosterTailor = 'Tailor' QuestPosterTailorBuildingName = 'Clothing Store' QuestPosterTailorStreetName = 'Any Playground' QuestPosterTailorLocationName = 'Any Neighborhood' QuestPosterPlayground = 'In the playground' QuestPosterAtHome = 'At your home' QuestPosterInHome = 'In your home' QuestPosterOnPhone = 'On your phone' QuestPosterEstate = 'At your estate' QuestPosterAnywhere = 'Anywhere' QuestPosterAuxTo = 'to:' QuestPosterAuxFrom = 'from:' QuestPosterAuxFor = 'for:' QuestPosterAuxOr = 'or:' QuestPosterAuxReturnTo = 'Return to:' QuestPosterLocationIn = ' in ' QuestPosterLocationOn = ' in ' QuestPosterFun = 'Just for fun!' QuestPosterFishing = 'GO FISHING' QuestPosterComplete = 'COMPLETE' QuestPosterConfirmDelete = 'Are you sure you want to delete this ToonTask?' QuestPosterDeleteBtn = 'Delete' QuestPosterDialogYes = 'Delete' QuestPosterDialogNo = 'Cancel' ShardPageTitle = 'Districts' ShardPageHelpIntro = 'Each District is a copy of the Toontown world.' ShardPageHelpWhere = ' You are currently in the "%s" District.' ShardPageHelpWelcomeValley = ' You are currently in the "Welcome Valley" District, within "%s".' ShardPageHelpMove = ' To move to a new District, click on its name.' ShardPagePopulationTotal = 'Total Toontown Population:\n%d' ShardPageScrollTitle = 'Name Population' ShardPageLow = 'Quiet' ShardPageMed = 'Ideal' ShardPageHigh = 'Full' ShardPageChoiceReject = 'Sorry, that district is full. Please try another one.' SuitPageTitle = 'Cog Gallery' SuitPageMystery = DialogQuestion + DialogQuestion + DialogQuestion SuitPageQuota = '%s of %s' SuitPageCogRadar = '%s present' SuitPageBuildingRadarS = '%s building' SuitPageBuildingRadarP = '%s buildings' DisguisePageTitle = Cog + ' Disguise' DisguisePageMeritAlert = 'Ready for\npromotion!' DisguisePageCogLevel = 'Level %s' DisguisePageMeritFull = 'Full' FishPageTitle = 'Fishing' FishPageTitleTank = 'Fish Bucket' FishPageTitleCollection = 'Fish Album' FishPageTitleTrophy = 'Fishing Trophies' FishPageWeightStr = 'Weight: ' FishPageWeightLargeS = '%d lb. ' FishPageWeightLargeP = '%d lbs. ' FishPageWeightSmallS = '%d oz.' FishPageWeightSmallP = '%d oz.' FishPageWeightConversion = 16 FishPageValueS = 'Value: %d jellybean' FishPageValueP = 'Value: %d Jellybeans' FishPageCollectedTotal = 'Fish Species Collected: %d of %d' FishPageRodInfo = '%s Rod\n%d - %d Pounds' FishPageTankTab = 'Bucket' FishPageCollectionTab = 'Album' FishPageTrophyTab = 'Trophies' FishPickerTotalValue = 'Bucket: %s / %s\nValue: %d Jellybeans' UnknownFish = '???' FishingRod = '%s Rod' FishingRodNameDict = {0: 'Twig', 1: 'Bamboo', 2: 'Hardwood', 3: 'Steel', 4: 'Gold'} FishTrophyNameDict = {0: 'Guppy', 1: 'Minnow', 2: 'Fish', 3: 'Flying Fish', 4: 'Shark', 5: 'Swordfish', 6: 'Killer Whale'} GardenPageTitle = 'Gardening' GardenPageTitleBasket = 'Flower Basket' GardenPageTitleCollection = 'Flower Album' GardenPageTitleTrophy = 'Gardening Trophies' GardenPageTitleSpecials = 'Gardening Specials' GardenPageBasketTab = 'Basket' GardenPageCollectionTab = 'Album' GardenPageTrophyTab = 'Trophies' GardenPageSpecialsTab = 'Specials' GardenPageCollectedTotal = 'Flower Varieties Collected: %d of %d' GardenPageValueS = 'Value: %d jellybean' GardenPageValueP = 'Value: %d Jellybeans' FlowerPickerTotalValue = 'Basket: %s / %s\nValue: %d Jellybeans' GardenPageShovelInfo = '%s Shovel: %d / %d\n' GardenPageWateringCanInfo = '%s Watering Can: %d / %d' FlowerPageWeightConversion = 1 FlowerPageWeightLargeP = 'Large P' FlowerPageWeightLargeS = 'LargeS ' FlowerPageWeightSmallP = 'SmallP ' FlowerPageWeightSmallS = 'SmallS ' FlowerPageWeightStr = 'Weight: %s' KartPageTitle = 'Karts' KartPageTitleCustomize = 'Kart Customizer' KartPageTitleRecords = 'Personal Best Records' KartPageTitleTrophy = 'Racing Trophies' KartPageCustomizeTab = 'Customize' KartPageRecordsTab = 'Records' KartPageTrophyTab = 'Trophy' KartPageTrophyDetail = 'Trophy %s : %s' KartPageTickets = 'Tickets : ' KartPageConfirmDelete = 'Delete Accessory?' KartShtikerDelete = 'Delete' KartShtikerSelect = 'Select a Category' KartShtikerNoAccessories = 'No Accessories Owned' KartShtikerBodyColors = 'Kart Colors' KartShtikerAccColors = 'Accessory Colors' KartShtikerEngineBlocks = 'Hood Accessories' KartShtikerSpoilers = 'Trunk Accessories' KartShtikerFrontWheelWells = 'Front Wheel Accessories' KartShtikerBackWheelWells = 'Back Wheel Accessories' KartShtikerRims = 'Rim Accessories' KartShtikerDecals = 'Decal Accessories' KartShtikerBodyColor = 'Kart Color' KartShtikerAccColor = 'Accessory Color' KartShtikerEngineBlock = 'Hood' KartShtikerSpoiler = 'Trunk' KartShtikerFrontWheelWell = 'Front Wheel' KartShtikerBackWheelWell = 'Back Wheel' KartShtikerRim = 'Rim' KartShtikerDecal = 'Decal' KartShtikerDefault = 'Default %s' KartShtikerNo = 'No %s Accessory' QuestChoiceGuiCancel = lCancel TrackChoiceGuiChoose = 'Choose' TrackChoiceGuiCancel = lCancel TrackChoiceGuiHEAL = 'Toonup lets you heal other Toons in battle.' TrackChoiceGuiTRAP = 'Traps are powerful gags that must be used with Lure.' TrackChoiceGuiLURE = 'Use Lure to stun Cogs or draw them into traps.' TrackChoiceGuiSOUND = 'Sound gags affect all Cogs, but are not very powerful.' TrackChoiceGuiZAP = 'Push gags are weak, but when paired with squirt, they can shortcircuit a cog and deal 2x damage.' TrackChoiceGuiDROP = 'Drop gags do lots of damage, but are not very accurate.' EmotePageTitle = 'Expressions / Emotions' EmotePageDance = 'You have built the following dance sequence:' EmoteJump = 'Jump' EmoteDance = 'Dance' EmoteHappy = 'Happy' EmoteSad = 'Sad' EmoteAnnoyed = 'Annoyed' EmoteSleep = 'Sleepy' TIPPageTitle = 'TIP' SuitBaseNameWithLevel = '%(name)s\n%(dept)s\nLevel %(level)s' HealthForceAcknowledgeMessage = 'You cannot leave the playground until your Laff meter is smiling!' InventoryTotalGags = 'Total gags\n%d / %d' InventroyPinkSlips = '%s Pink Slips' InventroyPinkSlip = '1 Pink Slip' InventoryDelete = 'DELETE' InventoryDeleteAll = 'DELETE ALL' InventoryDeleteConfirm = "Are you sure you want to delete all your gags? Don't worry, your level 7 gags will be safe" InventoryDone = 'DONE' InventoryDeleteHelp = 'Click on a gag to DELETE it.' InventorySkillCredit = 'Skill credit: %s' InventorySkillCreditNone = 'Skill credit: None' InventoryDetailAmount = '%(numItems)s / %(maxItems)s' InventoryDetailData = 'Accuracy: %(accuracy)s\n%(damageString)s: %(damage)d%(bonus)s\n%(singleOrGroup)s' InventoryTrackExp = '%(curExp)s / %(nextExp)s' InventoryUberTrackExp = '%(nextExp)s to Go!' InventoryGuestExp = 'Guest Limit' GuestLostExp = 'Over Guest Limit' InventoryAffectsOneCog = 'Affects: One ' + Cog InventoryAffectsOneToon = 'Affects: One Toon' InventoryAffectsAllToons = 'Affects: All Toons' InventoryAffectsAllCogs = 'Affects: All ' + Cogs InventoryHealString = 'Toon-up' InventoryDamageString = 'Damage' InventoryLureString = 'Rounds active' InventoryBattleMenu = 'BATTLE MENU' InventoryRun = 'RUN' InventorySOS = 'SOS' InventoryPass = 'PASS' InventoryFire = 'FIRE' InventoryLevelsShow = 'SHOW LEVELS' InventoryLevelsHide = 'HIDE LEVELS' InventoryClickToAttack = 'Click a\ngag to\nattack' InventoryDamageBonus = '(+%d)' NPCForceAcknowledgeMessage = "You must ride the trolley before leaving.\n\n\n\n\n\n\n\n\nYou can find the trolley next to Goofy's Gag Shop." NPCForceAcknowledgeMessage2 = 'You must return to Toon Headquarters before leaving.\n\n\n\n\n\n\n\n\n\nToon Headquarters is located near the center of the playground.' NPCForceAcknowledgeMessage3 = "Remember to ride the trolley.\n\n\n\n\n\n\n\nYou can find the trolley next to Goofy's Gag Shop." NPCForceAcknowledgeMessage4 = 'Congratulations! You found and rode the trolley!\n\n\n\n\n\n\n\n\n\nNow report back to Toon Headquarters.' NPCForceAcknowledgeMessage5 = "Don't forget your ToonTask!\n\n\n\n\n\n\n\n\n\n\nYou can find Cogs to defeat on the other side of tunnels like this." NPCForceAcknowledgeMessage6 = 'Great job defeating those Cogs!\n\n\n\n\n\n\n\n\nHead back to Toon Headquarters as soon as possible.' NPCForceAcknowledgeMessage7 = "Don't forget to make a friend!\n\n\n\n\n\n\nClick on another player and use the New Friend button." NPCForceAcknowledgeMessage8 = 'Great! You made a new friend!\n\n\n\n\n\n\n\n\nYou should go back at Toon Headquarters now.' NPCForceAcknowledgeMessage9 = 'Good job using the phone!\n\n\n\n\n\n\n\n\nReturn to Toon Headquarters to claim your reward.' ToonSleepString = '. . . ZZZ . . .' MovieTutorialReward1 = 'You received 1 Throw point! When you get 10, you will get a new gag!' MovieTutorialReward2 = 'You received 1 Squirt point! When you get 10, you will get a new gag!' MovieTutorialReward3 = 'Good job! You completed your first ToonTask!' MovieTutorialReward4 = 'Go to Toon Headquarters for your reward!' MovieTutorialReward5 = 'Have fun!' BattleGlobalTracks = ['toon-up', 'trap', 'lure', 'sound', 'throw', 'squirt', 'push', 'drop'] BattleGlobalNPCTracks = ['restock', 'toons hit', 'cogs miss'] BattleGlobalAvPropStrings = (('Feather', 'Megaphone', 'Lipstick', 'Bamboo Cane', 'Pixie Dust', 'Juggling Balls', 'High Dive'), ('Banana Peel', 'Rake', 'Marbles', 'Quicksand', 'Trapdoor', 'TNT', 'Railroad'), ('$1 bill', 'Small Magnet', '$5 bill', 'Big Magnet', '$10 bill', 'Hypno-goggles', 'Presentation'), ('Bike Horn', 'Whistle', 'Bugle', 'Aoogah', 'Elephant Trunk', 'Foghorn', 'Opera Singer'), ('Cupcake', 'Fruit Pie Slice', 'Cream Pie Slice', 'Whole Fruit Pie', 'Whole Cream Pie', 'Birthday Cake', 'Wedding Cake'), ('Squirting Flower', 'Glass of Water', 'Squirt Gun', 'Seltzer Bottle', 'Fire Hose', 'Storm Cloud', 'Geyser'), ('Hand Spring Gun', 'Firm Stick No Penis', 'Leaf Blower', 'Reverse Magnet', 'Medium Burp', 'Minecraft Piston', 'Big Fan'), ('Flower Pot', 'Sandbag', 'Anvil', 'Big Weight', 'Safe', 'Grand Piano', 'Toontanic')) BattleGlobalAvPropStringsSingular = (('a Feather', 'a Megaphone', 'a Lipstick', 'a Bamboo Cane', 'a Pixie Dust', 'a set of Juggling Balls', 'a High Dive'), ('a Banana Peel', 'a Rake', 'a set of Marbles', 'a patch of Quicksand', 'a Trapdoor', 'a TNT', 'a Railroad'), ('a $1 bill', 'a Small Magnet', 'a $5 bill', 'a Big Magnet', 'a $10 bill', 'a pair of Hypno-goggles', 'a Presentation'), ('a Bike Horn', 'a Whistle', 'a Bugle', 'an Aoogah', 'an Elephant Trunk', 'a Foghorn', 'an Opera Singer'), ('a Cupcake', 'a Fruit Pie Slice', 'a Cream Pie Slice', 'a Whole Fruit Pie', 'a Whole Cream Pie', 'a Birthday Cake', 'a Wedding Cake'), ('a Squirting Flower', 'a Glass of Water', 'a Squirt Gun', 'a Seltzer Bottle', 'a Fire Hose', 'a Storm Cloud', 'a Geyser'), ('a Hand Spring Gun', 'a Firm Stick No Penis', 'a Leaf Blower', 'a Reverse Magnet', 'a Medium Burp', 'a Minecraft Piston', 'a Big Fan'), ('a Flower Pot', 'a Sandbag', 'an Anvil', 'a Big Weight', 'a Safe', 'a Grand Piano', 'the Toontanic')) BattleGlobalAvPropStringsPlural = (('Feathers', 'Megaphones', 'Lipsticks', 'Bamboo Canes', 'Pixie Dusts', 'sets of Juggling Balls', 'High Dives'), ('Banana Peels', 'Rakes', 'sets of Marbles', 'patches of Quicksand', 'Trapdoors', 'TNTs', 'Railroads'), ('$1 bills', 'Small Magnets', '$5 bills', 'Big Magnets', '$10 bills', 'pairs of Hypno-goggles', 'Presentations'), ('Bike Horns', 'Whistles', 'Bugles', 'Aoogahs', 'Elephant Trunks', 'Foghorns', 'Opera Singers'), ('Cupcakes', 'Fruit Pie Slices', 'Cream Pie Slices', 'Whole Fruit Pies', 'Whole Cream Pies', 'Birthday Cakes', 'Wedding cakes'), ('Squirting Flowers', 'Glasses of Water', 'Squirt Guns', 'Seltzer Bottles', 'Fire Hoses', 'Storm Clouds', 'Geysers'), ('Hand Spring Guns', 'Firm Stick No Penises', 'Leaf Blowers', 'Reverse Magnets', 'Medium Burps', 'Minecraft Pistons', 'Big Fans'), ('Flower Pots', 'Sandbags', 'Anvils', 'Big Weights', 'Safes', 'Grand Pianos', 'Oceanliners')) BattleGlobalAvTrackAccStrings = ('Medium', 'Perfect', 'Low', 'High', 'Medium', 'High', 'Medium', 'Low') BattleGlobalLureAccLow = 'Low' BattleGlobalLureAccMedium = 'Medium' AttackMissed = 'MISSED' NPCCallButtonLabel = 'CALL' LoaderLabel = 'Loading...' StarringIn = 'Starring In...' HeadingToHood = '%(hood)s' HeadingToYourEstate = 'The Estate' HeadingToEstate = "%s's Estate" HeadingToFriend = "%s's Friend's Estate" HeadingToPlayground = 'The Playground' HeadingToStreet = '%(street)s' TownBattleRun = 'Run all the way back to the playground?' TownBattleChooseAvatarToonTitle = 'WHICH TOON?' TownBattleChooseAvatarCogTitle = 'WHICH ' + Cog.upper() + '?' TownBattleChooseAvatarBack = 'BACK' FireCogTitle = 'PINK SLIPS LEFT:%s\nFIRE WHICH COG?' FireCogLowTitle = 'PINK SLIPS LEFT:%s\nNOT ENOUGH SLIPS!' TownBattleSOSNoFriends = 'No friends to call!' TownBattleSOSWhichFriend = 'Call which friend?' TownBattleSOSNPCFriends = 'Rescued Toons' TownBattleSOSBack = 'BACK' TownBattleToonSOS = 'SOS' TownBattleToonFire = 'Fire' TownBattleUndecided = '?' TownBattleHealthText = '%(hitPoints)s/%(maxHit)s' TownBattleWaitTitle = 'Waiting for\nother players...' TownSoloBattleWaitTitle = 'Please wait...' TownBattleWaitBack = 'BACK' TownBattleSOSPetSearchTitle = 'Searching for doodle\n%s...' TownBattleSOSPetInfoTitle = '%s is %s' TownBattleSOSPetInfoOK = lOK TrolleyHFAMessage = 'You may not board the trolley until your Laff meter is smiling.' TrolleyTFAMessage = 'You may not board the trolley until ' + Mickey + ' says so.' TrolleyHopOff = 'Hop off' FishingExit = 'Exit' FishingCast = 'Cast' FishingAutoReel = 'Auto Reel' FishingItemFound = 'You caught:' FishingCrankTooSlow = 'Too\nslow' FishingCrankTooFast = 'Too\nfast' FishingFailure = "You didn't catch anything!" FishingFailureTooSoon = "Don't start to reel in the line until you see a nibble. Wait for your float to bob up and down rapidly!" FishingFailureTooLate = 'Be sure to reel in the line while the fish is still nibbling!' FishingFailureAutoReel = "The auto-reel didn't work this time. Turn the crank by hand, at just the right speed, for your best chance to catch something!" FishingFailureTooSlow = 'You turned the crank too slowly. Some fish are faster than others. Try to keep the speed bar centered!' FishingFailureTooFast = 'You turned the crank too quickly. Some fish are slower than others. Try to keep the speed bar centered!' FishingOverTankLimit = 'Your fish bucket is full. Go sell your fish to the Pet Shop Clerk and come back.' FishingBroke = 'You do not have any more Jellybeans for bait! Ride the trolley or sell fish to the Pet Shop Clerks to earn more Jellybeans.' FishingHowToFirstTime = 'Click and drag down from the Cast button. The farther down you drag, the stronger your cast will be. Adjust your angle to hit the fish targets.\n\nTry it now!' FishingHowToFailed = 'Click and drag down from the Cast button. The farther down you drag, the stronger your cast will be. Adjust your angle to hit the fish targets.\n\nTry it again now!' FishingBootItem = 'An old boot' FishingJellybeanItem = '%s Jellybeans' FishingNewEntry = 'New Species!' FishingNewRecord = 'New Record!' FishPokerCashIn = 'Cash In\n%s\n%s' FishPokerLock = 'Lock' FishPokerUnlock = 'Unlock' FishPoker5OfKind = '5 of a Kind' FishPoker4OfKind = '4 of a Kind' FishPokerFullHouse = 'Full House' FishPoker3OfKind = '3 of a Kind' FishPoker2Pair = '2 Pair' FishPokerPair = 'Pair' TutorialGreeting1 = 'Hi %s!' TutorialGreeting2 = 'Hi %s!\nCome over here!' TutorialGreeting3 = 'Hi %s!\nCome over here!\nUse the arrow keys!' TutorialMickeyWelcome = 'Welcome to Toontown!' TutorialFlippyIntro = 'Let me introduce you to my friend %s...' % Flippy TutorialFlippyHi = 'Hi, %s!' TutorialQT1 = 'You can talk by using this.' TutorialQT2 = 'You can talk by using this.\nClick it, then choose "Hi".' TutorialChat1 = 'You can talk using either of these buttons.' TutorialChat2 = 'The blue button lets you chat with the keyboard.' TutorialChat3 = "Be careful! Most other players won't understand what you say you when you use the keyboard." TutorialChat4 = 'The green button opens the %s.' TutorialChat5 = 'Everyone can understand you if you use the %s.' TutorialChat6 = 'Try saying "Hi".' TutorialBodyClick1 = 'Very good!' TutorialBodyClick2 = 'Pleased to meet you! Want to be friends?' TutorialBodyClick3 = 'To make friends with %s, click on him...' % Flippy TutorialHandleBodyClickSuccess = 'Good Job!' TutorialHandleBodyClickFail = 'Not quite. Try clicking right on %s...' % Flippy TutorialFriendsButton = "Now click the 'Friends' button under %s's picture in the right hand corner." % Flippy TutorialHandleFriendsButton = "And then click on the 'Yes' button.." TutorialOK = lOK TutorialYes = lYes TutorialNo = lNo TutorialFriendsPrompt = 'Would you like to make friends with %s?' % Flippy TutorialFriendsPanelMickeyChat = "%s has agreed to be your friend. Click 'Ok' to finish up." % Flippy TutorialFriendsPanelYes = '%s said yes!' % Flippy TutorialFriendsPanelNo = "That's not very friendly!" TutorialFriendsPanelCongrats = 'Congratulations! You made your first friend.' TutorialFlippyChat1 = 'Come see me when you are ready for your first ToonTask!' TutorialFlippyChat2 = "I'll be in ToonHall!" TutorialAllFriendsButton = 'You can view all your friends by clicking the friends button. Try it out...' TutorialEmptyFriendsList = "Right now your list is empty because %s isn't a real player." % Flippy TutorialCloseFriendsList = "Click the 'Close'\nbutton to make the\nlist go away" TutorialShtickerButton = 'The button in the lower, right corner opens your Shticker Book. Try it...' TutorialBook1 = 'The book contains lots of useful information like this map of Toontown.' TutorialBook2 = 'You can also check the progress of your ToonTasks.' TutorialBook3 = 'When you are done click the book button again to make it close' TutorialLaffMeter1 = 'You will also need this...' TutorialLaffMeter2 = "You will also need this...\nIt's your Laff meter." TutorialLaffMeter3 = 'When ' + Cogs + ' attack you, it gets lower.' TutorialLaffMeter4 = 'When you are in playgrounds like this one, it goes back up.' TutorialLaffMeter5 = 'When you complete ToonTasks, you will get rewards, like increasing your Laff limit.' TutorialLaffMeter6 = 'Be careful! If the ' + Cogs + ' defeat you, you will lose all your gags.' TutorialLaffMeter7 = 'To get more gags, play trolley games.' TutorialTrolley1 = 'Follow me to the trolley!' TutorialTrolley2 = 'Hop on board!' TutorialBye1 = 'Play some games!' TutorialBye2 = 'Play some games!\nBuy some gags!' TutorialBye3 = 'Go see %s when you are done!' % Flippy TutorialForceAcknowledgeMessage = 'You are going the wrong way! Go find %s!' % Mickey PetTutorialTitle1 = 'The Doodle Panel' PetTutorialTitle2 = 'Doodle SpeedChat' PetTutorialTitle3 = 'Doodle Cattlelog' PetTutorialNext = 'Next Page' PetTutorialPrev = 'Previous Page' PetTutorialDone = 'Done' PetTutorialPage1 = 'Click on a Doodle to display the Doodle panel. From here you can feed, scratch, and call the Doodle.' PetTutorialPage2 = "Use the new 'Pets' area in the SpeedChat menu to get a Doodle to do a trick. If he does it, reward him and he'll get better!" PetTutorialPage3 = "Purchase new Doodle tricks from Clarabelle's Cattlelog. Better tricks give better Toon-Ups!" def getPetGuiAlign(): from pandac.PandaModules import TextNode return TextNode.ACenter GardenTutorialTitle1 = 'Gardening' GardenTutorialTitle2 = 'Flowers' GardenTutorialTitle3 = 'Trees' GardenTutorialTitle4 = 'How-to' GardenTutorialTitle5 = 'Statues' GardenTutorialNext = 'Next Page' GardenTutorialPrev = 'Previous Page' GardenTutorialDone = 'Done' GardenTutorialPage1 = 'Toon up your Estate with a garden! You can plant flowers, grow trees, harvest super-powerful gags, and decorate with statues!' GardenTutorialPage2 = 'Flowers are finicky and require unique jellybean recipes. Once grown, put them in the wheelbarrow to sell them and work toward Laff boosts!' GardenTutorialPage3 = 'Use a gag from your inventory to plant a tree. After a few days, that gag will do more damage! Remember to keep it healthy or the damage boost will go away.' GardenTutorialPage4 = 'Walk up to these spots to plant, water, dig up or harvest your garden.' GardenTutorialPage5 = "Statues can be purchased in Clarabelle's Cattlelog. Increase your skill to unlock the more extravagant statues!" PlaygroundDeathAckMessage = TheCogs + ' took all your gags!\n\nYou are sad. You may not leave the playground until you are happy.' ForcedLeaveFactoryAckMsg = 'The ' + Foreman + ' was defeated before you could reach him. You did not recover any Cog parts.' ForcedLeaveMintAckMsg = 'The Mint Supervisor was defeated before you could reach him. You did not recover any Cogbucks.' HeadingToFactoryTitle = '%s' ForemanConfrontedMsg = '%s is battling the ' + Foreman + '!' MintBossConfrontedMsg = '%s is battling the Mint Supervisor!' StageBossConfrontedMsg = '%s is battling the District Attorney!' stageToonEnterElevator = '%s \nhas entered the elevator' ForcedLeaveStageAckMsg = 'The Lawbot District Attorney was defeated before you could reach him. You did not recover any Jury Notices.' MinigameWaitingForOtherPlayers = 'Waiting for other players to join...' MinigamePleaseWait = 'Please wait...' DefaultMinigameTitle = 'Minigame Title' DefaultMinigameInstructions = 'Minigame Instructions' HeadingToMinigameTitle = '%s' MinigamePowerMeterLabel = 'Power Meter' MinigamePowerMeterTooSlow = 'Too\nslow' MinigamePowerMeterTooFast = 'Too\nfast' MinigameTemplateTitle = 'Minigame Template' MinigameTemplateInstructions = 'This is a template minigame. Use it to create new minigames.' CannonGameTitle = 'Cannon Game' CannonGameInstructions = 'Shoot your toon into the water tower as quickly as you can. Use the mouse or the arrow keys to aim the cannon. Be quick and win a big reward for everyone!' CannonGameReward = 'REWARD' TwoDGameTitle = 'Toon Escape' TwoDGameInstructions = 'Escape from the ' + Cog + ' den as soon as you can. Use arrow keys to run/jump and Ctrl to squirt a ' + Cog + '. Collect ' + Cog + ' treasures to gain even more points.' TwoDGameElevatorExit = 'EXIT' TugOfWarGameTitle = 'Tug-of-War' TugOfWarInstructions = "Alternately tap the left and right arrow keys just fast enough to line up the green bar with the red line. Don't tap them too slow or too fast, or you'll end up in the water!" TugOfWarGameGo = 'GO!' TugOfWarGameReady = 'Ready...' TugOfWarGameEnd = 'Good game!' TugOfWarGameTie = 'You tied!' TugOfWarPowerMeter = 'Power meter' PatternGameTitle = 'Match Kion' PatternGameInstructions = 'Kion' + ' will show you a dance sequence. ' + 'Try to repeat ' + 'Kion' + "'s dance just the way you see it using the arrow keys!" PatternGameWatch = 'Watch these dance steps...' PatternGameGo = 'GO!' PatternGameRight = 'Good, %s!' PatternGameWrong = 'Oops!' PatternGamePerfect = 'That was perfect, %s!' PatternGameBye = 'Thanks for playing!' PatternGameWaitingOtherPlayers = 'Waiting for other players...' PatternGamePleaseWait = 'Please wait...' PatternGameFaster = 'You were\nfaster!' PatternGameFastest = 'You were\nthe fastest!' PatternGameYouCanDoIt = 'Come on!\nYou can do it!' PatternGameOtherFaster = '\nwas faster!' PatternGameOtherFastest = '\nwas the fastest!' PatternGameGreatJob = 'Great Job!' PatternGameRound = 'Round %s!' PatternGameImprov = 'You did great! Now Improv!' RaceGameTitle = 'Race Game' RaceGameInstructions = 'Click a number. Choose wisely! You only advance if no one else picked the same number.' RaceGameWaitingChoices = 'Waiting for other players to choose...' RaceGameCardText = '%(name)s draws: %(reward)s' RaceGameCardTextBeans = '%(name)s receives: %(reward)s' RaceGameCardTextHi1 = '%(name)s is one Fabulous Toon!' RaceGameForwardOneSpace = ' forward 1 space' RaceGameForwardTwoSpaces = ' forward 2 spaces' RaceGameForwardThreeSpaces = ' forward 3 spaces' RaceGameBackOneSpace = ' back 1 space' RaceGameBackTwoSpaces = ' back 2 spaces' RaceGameBackThreeSpaces = ' back 3 spaces' RaceGameOthersForwardThree = ' all others forward \n3 spaces' RaceGameOthersBackThree = 'all others back \n3 spaces' RaceGameInstantWinner = 'Instant Winner!' RaceGameJellybeans2 = '2 Jellybeans' RaceGameJellybeans4 = '4 Jellybeans' RaceGameJellybeans10 = '10 Jellybeans!' RingGameTitle = 'Ring Game' RingGameInstructionsSinglePlayer = 'Try to swim through as many of the %s rings as you can. Use the arrow keys to swim.' RingGameInstructionsMultiPlayer = 'Try to swim through the %s rings. Other players will try for the other colored rings. Use the arrow keys to swim.' RingGameMissed = 'MISSED' RingGameGroupPerfect = 'GROUP\nPERFECT!!' RingGamePerfect = 'PERFECT!' RingGameGroupBonus = 'GROUP BONUS' ColorRed = 'red' ColorGreen = 'green' ColorOrange = 'orange' ColorPurple = 'purple' ColorWhite = 'white' ColorBlack = 'black' ColorYellow = 'yellow' DivingGameTitle = 'Treasure Dive' DivingInstructionsSinglePlayer = 'Treasures will appear at the bottom of the lake. Use the arrow keys to swim. Avoid the fish and get the treasures up to the boat!' DivingInstructionsMultiPlayer = 'Treasures will appear at the bottom of the lake. Use the arrow keys to swim. Work together to get the treasures up to the boat!' DivingGameTreasuresRetrieved = 'Treasures Retrieved' TargetGameTitle = 'Toon Slingshot' TargetGameInstructionsSinglePlayer = 'Land on targets to score points' TargetGameInstructionsMultiPlayer = 'Land on targets to score points' TargetGameBoard = 'Round %s - Keeping Best Score' TargetGameCountdown = 'Forced launch in %s seconds' TargetGameCountHelp = 'Pound left and right arrows for power, stop to launch' TargetGameFlyHelp = 'Press down to open umbrella' TargetGameFallHelp = 'Use the arrow keys to land on target' TargetGameBounceHelp = ' Bouncing can knock you off target' PhotoGameScoreTaken = '%s: %s\nYou: %s' PhotoGameScoreBlank = 'Score: %s' PhotoGameScoreOther = '\n%s' PhotoGameScoreYou = '\nBest Bonus!' TagGameTitle = 'Tag Game' TagGameInstructions = 'Collect the treasures. You cannot collect treasure when you are IT!' TagGameYouAreIt = 'You Are IT!' TagGameSomeoneElseIsIt = '%s is IT!' MazeGameTitle = 'Maze Game' MazeGameInstructions = 'Collect the treasures. Try to get them all, but look out for the ' + Cogs + '!' CatchGameTitle = 'Catching Game' CatchGameInstructions = 'Catch as many %(fruit)s as you can. Watch out for the ' + Cogs + ", and try not to 'catch' any %(badThing)s!" CatchGamePerfect = 'PERFECT!' CatchGameApples = 'apples' CatchGameOranges = 'oranges' CatchGamePears = 'pears' CatchGameCoconuts = 'coconuts' CatchGameWatermelons = 'watermelons' CatchGamePineapples = 'pineapples' CatchGameAnvils = 'anvils' PieTossGameTitle = 'Pie Toss Game' PieTossGameInstructions = 'Toss pies at the targets.' PhotoGameInstructions = 'Capture photos matching the toons shown at the bottom. Aim the camera with the mouse, and left click to take a picture. Press Ctrl to zoom in/out, and look around with the arrow keys. Pictures with higher ratings get more points!' PhotoGameTitle = 'Photo Fun' PhotoGameFilm = 'FILM' PhotoGameScore = 'Team Score: %s\n\nBest Photos: %s\n\nTotal Score: %s' CogThiefGameTitle = 'Cog Thief' CogThiefGameInstructions = 'Stop the Cogs from stealing our gags! Press the Alt or Delete key to throw pies. Be careful - they have a tendancy to explode.' CogThiefBarrelsSaved = '%(num)d Barrels\nSaved!' CogThiefBarrelSaved = '%(num)d Barrel\nSaved!' CogThiefNoBarrelsSaved = 'No Barrels\nSaved' CogThiefPerfect = 'PERFECT!' MinigameRulesPanelPlay = 'PLAY' GagShopName = "Goofy's Gag Shop" GagShopPlayAgain = 'PLAY\nAGAIN' GagShopBackToPlayground = 'EXIT BACK TO\nPLAYGROUND' GagShopYouHave = 'You have %s Jellybeans to spend' GagShopYouHaveOne = 'You have 1 jellybean to spend' GagShopTooManyProps = 'Woah there! Your Gag Pouch is full.' GagShopDoneShopping = 'DONE\nSHOPPING' GagShopTooManyOfThatGag = 'Sorry, you have enough %s already' GagShopInsufficientSkill = 'You do not have enough skill for that yet' GagShopYouPurchased = 'You purchased %s' GagShopOutOfJellybeans = 'Sorry, you are all out of Jellybeans!' GagShopWaitingOtherPlayers = 'Waiting for other players...' GagShopPlayerDisconnected = '%s has disconnected' GagShopPlayerExited = '%s has exited' GagShopPlayerPlayAgain = 'Play Again' GagShopPlayerBuying = 'Buying' GenderShopQuestionMickey = 'To make a boy toon, click on me!' GenderShopQuestionMinnie = 'To make a girl toon, click on me!' GenderShopFollow = 'Follow me!' GenderShopSeeYou = 'See you later!' GenderShopBoyButtonText = 'Boy' GenderShopGirlButtonText = 'Girl' BodyShopHead = 'Head' BodyShopBody = 'Body' BodyShopLegs = 'Legs' ColorShopToon = 'Toon Color' ColorShopHead = 'Head' ColorShopBody = 'Body' ColorShopLegs = 'Legs' ColorShopParts = 'Multi Color' ColorShopAll = 'Single Color' ClothesShopShorts = 'Shorts' ClothesShopShirt = 'Shirts' ClothesShopBottoms = 'Bottoms' ClothesShopShirtsStyle = 'Shirts Style' ClothesShopShirtsColor = 'Shirts Color' ClothesShopShortsStyle = 'Shorts Style' ClothesShopShortsColor = 'Shorts Color' ClothesShopBottomsStyle = 'Bottoms Style' ClothesShopBottomsColor = 'Bottoms Color' PromptTutorial = "Congratulations!!\nYou are Toontown's newest citizen!\n\nWould you like to continue to the Toontorial or teleport directly to Toontown Central?" MakeAToonSkipTutorial = 'Skip Toontorial' MakeAToonEnterTutorial = 'Enter Toontorial' MakeAToonDone = 'Done' MakeAToonCancel = lCancel MakeAToonNext = lNext MakeAToonLast = 'Back' CreateYourToon = 'Click the arrows to create your toon.' CreateYourToonTitle = 'Choose Boy or Girl' ShapeYourToonTitle = 'Choose Your Type' PaintYourToonTitle = 'Choose Your Color' PickClothesTitle = 'Choose Your Clothes' NameToonTitle = 'Choose Your Name' CreateYourToonHead = "Click the 'head' arrows to pick different animals." MakeAToonClickForNextScreen = 'Click the arrow below to go to the next screen.' PickClothes = 'Click the arrows to pick clothes!' PaintYourToon = 'Click the arrows to paint your toon!' MakeAToonYouCanGoBack = 'You can go back to change your body too!' MakeAFunnyName = 'Choose a funny name for your toon with my Pick-A-Name game!' MustHaveAFirstOrLast1 = "Your toon should have a first or last name, don't you think?" MustHaveAFirstOrLast2 = "Don't you want your toon to have a first or last name?" ApprovalForName1 = "That's it, your toon deserves a great name!" ApprovalForName2 = 'Toon names are the best kind of names!' MakeAToonLastStep = 'Last step before going to Toontown!' PickANameYouLike = 'Pick a name you like!' TitleCheckBox = 'Title' FirstCheckBox = 'First' LastCheckBox = 'Last' RandomButton = 'Random' ShuffleButton = 'Shuffle' NameShopSubmitButton = 'Submit' TypeANameButton = 'Type-A-Name' TypeAName = "Don't like these names?\nClick here -->" PickAName = 'Try the PickAName game!\nClick here -->' PickANameButton = 'Pick-A-Name' RejectNameText = 'That name is not allowed. Please try again.' WaitingForNameSubmission = 'Submitting your name...' PetNameMaster = 'PetNameMasterEnglish.txt' PetNameIndexMAX = 2713 PetshopUnknownName = 'Name: ???' PetshopDescGender = 'Gender:\t%s' PetshopDescCost = 'Cost:\t%s Jellybeans' PetshopDescTrait = 'Traits:\t%s' PetshopDescStandard = 'Standard' PetshopCancel = lCancel PetshopSell = 'Sell Fish' PetshopAdoptAPet = 'Adopt a Doodle' PetshopReturnPet = 'Return your Doodle' PetshopAdoptConfirm = 'Adopt %s for %d Jellybeans?' PetshopGoBack = 'Go Back' PetshopAdopt = 'Adopt' PetshopReturnConfirm = 'Return %s?' PetshopReturn = 'Return' PetshopChooserTitle = "TODAY'S DOODLES" PetshopGoHomeText = 'Would you like to go to your estate to play with your new Doodle?' NameShopNameMaster = 'NameMasterEnglish.txt' NameShopPay = 'Subscribe' NameShopPlay = 'Free Trial' NameShopOnlyPaid = 'Only paid users\nmay name their Toons.\nUntil you subscribe\nyour name will be\n' NameShopContinueSubmission = 'Continue Submission' NameShopChooseAnother = 'Choose Another Name' NameShopToonCouncil = 'The Toon Council\nwill review your\nname. ' + 'Review may\ntake a few days.\nWhile you wait\nyour name will be\n ' PleaseTypeName = 'Please type your name:' AllNewNames = 'All new names must be\napproved by the Toon Council.' NameMessages = 'Be creative, and remember:\nno NPC names, please.' NameShopNameRejected = 'The name you\nsubmitted has\nbeen rejected.' NameShopNameAccepted = 'Congratulations!\nThe name you\nsubmitted has\nbeen accepted!' NoPunctuation = "You can't use punctuation marks in your name!" PeriodOnlyAfterLetter = 'You can use a period in your name, but only after a letter.' ApostropheOnlyAfterLetter = 'You can use an apostrophe in your name, but only after a letter.' NoNumbersInTheMiddle = 'Numeric digits may not appear in the middle of a word.' ThreeWordsOrLess = 'Your name must be three words or fewer.' CopyrightedNames = ('mickey', 'mickey mouse', 'mickeymouse', 'minnie', 'minnie mouse', 'minniemouse', 'donald', 'donald duck', 'donaldduck', 'pluto', 'goofy') NumToColor = ['White', 'Peach', 'Bright Red', 'Red', 'Maroon', 'Sienna', 'Brown', 'Tan', 'Coral', 'Orange', 'Yellow', 'Cream', 'Citrine', 'Lime', 'Sea Green', 'Green', 'Light Blue', 'Aqua', 'Blue', 'Periwinkle', 'Royal Blue', 'Slate Blue', 'Purple', 'Lavender', 'Pink', 'Plum', 'Black', 'Rose Pink', 'Ice Blue', 'Mint Green', 'Emerald', 'Teal', 'Apricot', 'Amber', 'Crimson', 'Dark Green', 'Steel Blue', 'ToonFest Blue', 'Mountain Green', 'Icy Blue', 'Desert Sand', 'Mint', 'Charcoal', 'Hot Pink', 'Honey Mustard', 'Gray', 'Neon Orange', 'Sapphire', 'Crimson', 'Emerald', 'Bronze', 'African Violet', 'Magenta', 'Medium Purple', 'Ivory', 'Thistle', 'Spring Green', 'Goldenrod', 'Cadium Yellow', 'Peach Puff', 'Toony Teal', 'Salmon', 'Banana Yellow', 'Dim Gray'] AnimalToSpecies = {'dog': 'Dog', 'cat': 'Cat', 'mouse': 'Mouse', 'horse': 'Horse', 'rabbit': 'Rabbit', 'duck': 'Duck', 'monkey': 'Monkey', 'bear': 'Bear', 'pig': 'Pig'} NameTooLong = 'That name is too long. Please try again.' ToonAlreadyExists = 'You already have a toon named %s!' NameAlreadyInUse = 'That name is already used!' EmptyNameError = 'You must enter a name first.' NameError = 'Sorry. That name will not work.' NCTooShort = 'That name is too short.' NCNoDigits = 'Your name cannot contain numbers.' NCNeedLetters = 'Each word in your name must contain some letters.' NCNeedVowels = 'Each word in your name must contain some vowels.' NCAllCaps = 'Your name cannot be all capital letters.' NCMixedCase = 'That name has too many capital letters.' NCBadCharacter = "Your name cannot contain the character '%s'" NCGeneric = 'Sorry, that name will not work.' NCTooManyWords = 'Your name cannot be more than four words long.' NCDashUsage = "Dashes may only be used to connect two words together (like in 'Boo-Boo')." NCCommaEdge = 'Your name may not begin or end with a comma.' NCCommaAfterWord = 'You may not begin a word with a comma.' NCCommaUsage = 'That name does not use commas properly. Commas must join two words together, like in the name "Dr. Quack, MD". Commas must also be followed by a space.' NCPeriodUsage = 'That name does not use periods properly. Periods are only allowed in words like "Mr.", "Mrs.", "J.T.", etc.' NCApostrophes = 'That name has too many apostrophes.' RemoveTrophy = lToonHQ + ': ' + TheCogs + ' took over one of the buildings you rescued!' STOREOWNER_TOOKTOOLONG = 'Need more time to think?' STOREOWNER_GOODBYE = 'See you later!' STOREOWNER_NEEDJELLYBEANS = 'You need to ride the Trolley to get some Jellybeans.' STOREOWNER_GREETING = 'Choose what you want to buy.' STOREOWNER_BROWSING = 'You can browse, but you need a clothing ticket to buy.' STOREOWNER_BROWSING_JBS = 'You can browse, but you need at least 200 Jellybeans to buy.' STOREOWNER_NOCLOTHINGTICKET = 'You need a clothing ticket to shop for clothes.' STOREOWNER_NOFISH = 'Come back here to sell fish to the Pet Shop for Jellybeans.' STOREOWNER_THANKSFISH = 'Thanks! The Pet Shop will love these. Bye!' STOREOWNER_THANKSFISH_PETSHOP = 'These are some fine specimens! Thanks.' STOREOWNER_PETRETURNED = "Don't worry. We'll find a good home for your Doodle." STOREOWNER_PETADOPTED = 'Congratulations on purchasing a Doodle! You can play with your new friend at your estate.' STOREOWNER_PETCANCELED = 'Remember, if you see a Doodle you like, make sure to adopt him before someone else does!' STOREOWNER_NOROOM = 'Hmm...you might want to make room in your closet before you buy new clothes.\n' STOREOWNER_CONFIRM_LOSS = 'Your closet is full. You will lose the clothes you were wearing.' STOREOWNER_OK = lOK STOREOWNER_CANCEL = lCancel STOREOWNER_TROPHY = 'Wow! You collected %s of %s fish. That deserves a trophy and a Laff boost!' SuitInvasionBegin1 = lToonHQ + ': A Cog Invasion has begun...' SuitInvasionBegin2 = lToonHQ + ': %s have taken over Toontown!!!' SuitInvasionEnd1 = lToonHQ + ': The %s Invasion has ended!!!' SuitInvasionEnd2 = lToonHQ + ': The Toons have saved the day once again!!!' SuitInvasionUpdate1 = lToonHQ + ': The Cog Invasion is now at %s Cogs!!!' SuitInvasionUpdate2 = lToonHQ + ': We must defeat those %s!!!' SuitInvasionBulletin1 = lToonHQ + ': There is a Cog Invasion in progress...' SuitInvasionBulletin2 = lToonHQ + ': %s have taken over Toontown!!!' LeaderboardTitle = 'Toon Platoon' QuestScriptTutorialMickey_1 = 'Toontown has a new citizen! Do you have some extra gags?' QuestScriptTutorialMickey_2 = 'Sure, %s!' QuestScriptTutorialMickey_3 = 'Tutorial Tom will tell you all about the Cogs.\x07Gotta go!' QuestScriptTutorialMickey_4 = 'Come here! Use the arrow keys to move.' QuestScriptTutorialMinnie_1 = 'Toontown has a new citizen! Do you have some extra gags?' QuestScriptTutorialMinnie_2 = 'Sure, %s!' QuestScriptTutorialMinnie_3 = 'Tutorial Tom will tell you all about the Cogs.\x07Gotta go!' QuestScript101_1 = 'These are Cogs. They are robots that are trying to take over Toontown.' QuestScript101_2 = 'There are many different kinds of Cogs and...' QuestScript101_3 = '...they turn happy Toon buildings...' QuestScript101_4 = '...into ugly Cog buildings!' QuestScript101_5 = "But Cogs can't take a joke!" QuestScript101_6 = 'A good gag will stop them.' QuestScript101_7 = 'There are lots of gags, but take these to start.' QuestScript101_8 = 'Oh! You also need a Laff meter!' QuestScript101_9 = "If your Laff meter gets too low, you'll be sad!" QuestScript101_10 = 'A happy Toon is a healthy Toon!' QuestScript101_11 = "OH NO! There's a Cog outside my shop!" QuestScript101_12 = 'HELP ME, PLEASE! Defeat the Cog!' QuestScript101_13 = 'Here is your first ToonTask!' QuestScript101_14 = 'Hurry up! Go defeat the Flunky!' QuestScript110_1 = 'Good work defeating the Flunky. Let me give you a Shticker Book...' QuestScript110_2 = 'The book is full of good stuff.' QuestScript110_3 = "Open it, and I'll show you." QuestScript110_4 = "The map shows where you've been." QuestScript110_5 = 'Turn the page to see your gags...' QuestScript110_6 = 'Uh oh! You have no gags! I will assign you a task.' QuestScript110_7 = 'Turn the page to see your tasks.' QuestScript110_8 = 'Take a ride on the trolley, and earn jelly beans to buy gags!' QuestScript110_9 = 'To get to the trolley, go out the door behind me and head for the playground.' QuestScript110_10 = 'Now, close the book and find the trolley!' QuestScript110_11 = 'Return to Toon HQ when you are done. Bye!' QuestScriptTutorialBlocker_1 = 'Why, hello there!' QuestScriptTutorialBlocker_2 = 'Hello?' QuestScriptTutorialBlocker_3 = "Oh! You don't know how to use SpeedChat!" QuestScriptTutorialBlocker_4 = 'Click on the button to say something.' QuestScriptTutorialBlocker_5 = 'Very good!\x07Where you are going there are many Toons to talk to.' QuestScriptTutorialBlocker_6 = "If you want to chat with other Toons using the keyboard, there's another button you can use." QuestScriptTutorialBlocker_7 = "It's called the SpeedChat Plus button!" QuestScriptTutorialBlocker_8 = 'Good luck! See you later!' QuestScriptGagShop_1 = 'Welcome to the Gag Shop!' QuestScriptGagShop_1a = 'This is where Toons come to buy gags to use against the Cogs.' QuestScriptGagShop_3 = 'To buy gags, click on the gag buttons. Try getting some now!' QuestScriptGagShop_4 = 'Good! You can use these gags in battle against the Cogs.' QuestScriptGagShop_5 = "Here's a peek at the advanced throw and squirt gags..." QuestScriptGagShop_6 = "When you're done buying gags, click this button to return to the Playground." QuestScriptGagShop_7 = 'Normally you can use this button to play another Trolley Game...' QuestScriptGagShop_8 = "...but there's no time for another game right now. You're needed in Toon HQ!" QuestScript120_1 = "Good job finding the trolley!\x07By the way, have you met Banker Bob?\x07He has quite a sweet tooth.\x07Why don't you introduce yourself by taking him this candy bar as a gift." QuestScript120_2 = 'Banker Bob is over in the Toontown Bank.' QuestScript121_1 = "Yum, thank you for the Candy Bar.\x07Say, if you can help me, I'll give you a reward.\x07Those Cogs stole the keys to my safe. Defeat Cogs to find a stolen key.\x07When you find a key, bring it back to me." QuestScript130_1 = 'Good job finding the trolley!\x07By the way, I received a package for Professor Pete today.\x07It must be his new chalk he ordered.\x07Can you please take it to him?\x07He is over in the school house.' QuestScript131_1 = 'Oh, thanks for the chalk.\x07What?!?\x07Those Cogs stole my blackboard. Defeat Cogs to find my stolen blackboard.\x07When you find it, bring it back to me.' QuestScript140_1 = 'Good job finding the trolley!\x07By the way, I have this friend, Librarian Larry, who is quite a book worm.\x07I picked this book up for him last time I was over in ' + lDonaldsDock + '.\x07Could you take it over to him, he is usually in the Library.' QuestScript141_1 = 'Oh, yes, this book almost completes my collection.\x07Let me see...\x07Uh oh...\x07Now where did I put my glasses?\x07I had them just before those Cogs took over my building.\x07Defeat Cogs to find my stolen glasses.\x07When you find them, bring them back to me for a reward.' QuestScript145_1 = 'I see you had no problem with the trolley!\x07Listen, the Cogs have stolen our blackboard eraser.\x07Go into the streets and fight Cogs until you recover the eraser.\x07To reach the streets go through one of the tunnels like this:' QuestScript145_2 = "When you find our eraser, bring it back here.\x07Don't forget, if you need gags, ride the trolley.\x07Also, if you need to recover Laff points, collect ice cream cones in the Playground." MissingKeySanityCheck = 'Ignore me' SellbotBossName = 'Senior V. P.' CashbotBossName = 'C. F. O.' LawbotBossName = 'Chief Justice' BossCogNameWithDept = '%(name)s\n%(dept)s' BossCogPromoteDoobers = 'You are hereby promoted to full-fledged %s. Congratulations!' BossCogDoobersAway = {'s': 'Go! And make that sale!'} BossCogWelcomeToons = 'Welcome, new Cogs!' BossCogPromoteToons = 'You are hereby promoted to full-fledged %s. Congratu--' CagedToonInterruptBoss = 'Hey! Hiya! Hey over there!' CagedToonRescueQuery = 'So, did you Toons come to rescue me?' BossCogDiscoverToons = 'Huh? Toons! In disguise!' BossCogAttackToons = 'Attack!!' CagedToonDrop = ["Great job! You're wearing him down!", "Keep after him! He's on the run!", 'You guys are doing great!', "Fantastic! You've almost got him now!"] CagedToonPrepareBattleTwo = "Look out, he's trying to get away!\x07Help me, everyone--get up here and stop him!" CagedToonPrepareBattleThree = "Hooray, I'm almost free!\x07Now you need to attack the V.P. Cog directly.\x07I've got a whole bunch of pies you can use!\x07Jump up and touch the bottom of my cage and I'll give you some pies.\x07Press the Delete key to throw pies once you've got them!" BossBattleNeedMorePies = 'You need to get more pies!' BossBattleHowToGetPies = 'Jump up to touch the cage to get pies.' BossBattleHowToThrowPies = 'Press the Delete key to throw pies!' CagedToonYippee = 'Yippee!' CagedToonThankYou = "It's great to be free!\x07Thanks for all your help!\x07I am in your debt.\x07Here's my card. If you ever need a hand in battle, give a shout!\x07Just click on your SOS button." CagedToonPromotion = "\x07Say--that V.P. Cog left behind your promotion papers.\x07I'll file them for you on the way out, so you'll get your promotion!" CagedToonLastPromotion = "\x07Wow, you've reached level %s on your Cog suit!\x07Cogs don't get promoted higher than that.\x07You can't upgrade your Cog suit anymore, but you can certainly keep rescuing Toons!" CagedToonHPBoost = "\x07You've rescued a lot of Toons from this HQ.\x07The Toon Council has decided to give you another Laff point. Congratulations!" CagedToonMaxed = '\x07I see that you have a level %s Cog suit. Very impressive!\x07On behalf of the Toon Council, thank you for coming back to rescue more Toons!' CagedToonGoodbye = 'See ya!' CagedToonBattleThree = {10: 'Nice jump, %(toon)s. Here are some pies!', 11: 'Hi, %(toon)s! Have some pies!', 12: "Hey there, %(toon)s! You've got some pies now!", 20: 'Hey, %(toon)s! Jump up to my cage and get some pies to throw!', 21: 'Hi, %(toon)s! Use the Ctrl key to jump up and touch my cage!', 100: 'Press the Delete key to throw a pie.', 101: 'The blue power meter shows how high your pie will go.', 102: 'First try to lob a pie inside his undercarriage to gum up his works.', 103: 'Wait for the door to open, and throw a pie straight inside.', 104: "When he's dizzy, hit him in the face or chest to knock him back!", 105: "You'll know you've got a good hit when you see the splat in color.", 106: 'If you hit a Toon with a pie, it gives that Toon a Laff point!'} CagedToonBattleThreeMaxGivePies = 12 CagedToonBattleThreeMaxTouchCage = 21 CagedToonBattleThreeMaxAdvice = 106 CashbotBossHadEnough = "That's it. I've had enough of these pesky Toons!" CashbotBossOuttaHere = "I've got a train to catch!" ResistanceToonName = 'Mata Hairy' ResistanceToonCongratulations = "You did it! Congratulations!\x07You're an asset to the Resistance!\x07Here's a special phrase you can use in a tight spot:\x07%s\x07When you say it, %s.\x07But you can only use it once, so choose that time well!" ResistanceToonToonupInstructions = 'all the Toons near you will gain %s Laff points' ResistanceToonToonupAllInstructions = 'all the Toons near you will gain full Laff points' ResistanceToonMoneyInstructions = 'all the Toons near you will gain %s Jellybeans' ResistanceToonMoneyAllInstructions = 'all the Toons near you will fill their jellybean jars' ResistanceToonRestockInstructions = 'all the Toons near you will restock their "%s" gags' ResistanceToonRestockAllInstructions = 'all the Toons near you will restock all their gags' ResistanceToonLastPromotion = "\x07Wow, you've reached level %s on your Cog suit!\x07Cogs don't get promoted higher than that.\x07You can't upgrade your Cog suit anymore, but you can certainly keep working for the Resistance!" ResistanceToonHPBoost = "\x07You've done a lot of work for the Resistance.\x07The Toon Council has decided to give you another Laff point. Congratulations!" ResistanceToonMaxed = '\x07I see that you have a level %s Cog suit. Very impressive!\x07On behalf of the Toon Council, thank you for coming back to rescue more Toons!' CashbotBossCogAttack = 'Get them!!!' ResistanceToonWelcome = 'Hey, you made it! Follow me to the main vault before the C.F.O. finds us!' ResistanceToonTooLate = "Blast it! We're too late!" CashbotBossDiscoverToons1 = 'Ah-HAH!' CashbotBossDiscoverToons2 = 'I thought I smelled something a little toony in here! Imposters!' ResistanceToonKeepHimBusy = "Keep him busy! I'm going to set a trap!" ResistanceToonWatchThis = 'Watch this!' CashbotBossGetAwayFromThat = 'Hey! Get away from that!' ResistanceToonCraneInstructions1 = 'Control a magnet by stepping up to a podium.' ResistanceToonCraneInstructions2 = 'Use the arrow keys to move the crane, and press the Ctrl key to grab an object.' ResistanceToonCraneInstructions3 = "Grab a safe with a magnet and knock the C.F.O.'s safe-ty helmet off." ResistanceToonCraneInstructions4 = 'Once his helmet is gone, grab a disabled goon and hit him in the head!' ResistanceToonGetaway = 'Eek! Gotta run!' CashbotCraneLeave = 'Leave Crane' CashbotCraneAdvice = 'Use the arrow keys to move the overhead crane.' CashbotMagnetAdvice = 'Hold down the control key to pick things up.' CashbotCraneLeaving = 'Leaving crane' MintElevatorRejectMessage = 'You cannot enter the Mints until you have completed your %s Cog Suit.' BossElevatorRejectMessage = 'You cannot board this elevator until you have earned a promotion.' NotYetAvailable = 'This elevator is not yet available.' SellbotRentalSuitMessage = "Wear this Rental Suit so you can get close enough to the VP to attack.\n\nYou won't earn merits or promotions, but you can rescue a Toon for an SOS reward!" SellbotCogSuitNoMeritsMessage = "Your Sellbot Disguise will get you in, but since you don't have enough merits, you won't earn a promotion.\n\nIf you rescue the trapped Toon, you will earn an SOS Toon reward!" SellbotCogSuitHasMeritsMessage = "It's Operation: Storm Sellbot!\n\nBring 5 or more Rental Suit Toons with you to defeat the VP and earn credit towards a reward!" FurnitureTypeName = 'Furniture' PaintingTypeName = 'Painting' ClothingTypeName = 'Clothing' ChatTypeName = 'SpeedChat Phrase' EmoteTypeName = 'Acting Lessons' BeanTypeName = 'Jellybeans' PoleTypeName = 'Fishing Pole' WindowViewTypeName = 'Window View' PetTrickTypeName = 'Doodle Training' GardenTypeName = 'Garden Supplies' RentalTypeName = 'Rental Item' GardenStarterTypeName = 'Gardening Kit' NametagTypeName = 'Name tag' AccessoryTypeName = 'Accessory' CatalogItemTypeNames = {0: 'INVALID_ITEM', 1: FurnitureTypeName, 2: ChatTypeName, 3: ClothingTypeName, 4: EmoteTypeName, 5: 'WALLPAPER', 6: 'Window View', 7: 'FLOORING', 8: 'MOULDING', 9: 'WAINSCOTING', 10: PoleTypeName, 11: PetTrickTypeName, 12: BeanTypeName, 13: GardenTypeName, 14: RentalTypeName, 15: GardenStarterTypeName, 16: NametagTypeName, 17: 'TOON_STATUE', 18: 'ANIMATED FURNITURE', 19: AccessoryTypeName} HatStylesDescriptions = {'hbb1': 'Green Baseball Cap', 'hbb2': 'Blue Baseball Cap', 'hbb3': 'Orange Baseball Cap', 'hsf1': 'Beige Safari Hat', 'hsf2': 'Brown Safari Hat', 'hsf3': 'Green Safari Hat', 'hrb1': 'Pink Bow', 'hrb2': 'Red Bow', 'hrb3': 'Purple Bow', 'hht1': 'Pink Heart', 'hht2': 'Yellow Heart', 'htp1': 'Black Top Hat', 'htp2': 'Blue Top Hat', 'hav1': 'Anvil Hat', 'hfp1': 'Flower Hat', 'hsg1': 'Sandbag Hat', 'hwt1': 'Weight Hat', 'hfz1': 'Fez Hat', 'hgf1': 'Golf Hat', 'hpt1': 'Party Hat', 'hpt2': 'Toon Party Hat', 'hpb1': 'Fancy Hat', 'hcr1': 'Crown', 'hcw1': 'Cowboy Hat', 'hpr1': 'Pirate Hat', 'hpp1': 'Propeller Hat', 'hfs1': 'Fishing Hat', 'hsb1': 'Sombrero Hat', 'hst1': 'Straw Hat', 'hsu1': 'Sun Hat', 'hrb4': 'Yellow Bow', 'hrb5': 'Checker Bow', 'hrb6': 'Light Red Bow', 'hrb7': 'Rainbow Bow', 'hat1': 'Antenna Thingy', 'hhd1': 'Beehive Hairdo', 'hbw1': 'Bowler Hat', 'hch1': 'Chef Hat', 'hdt1': 'Detective Hat', 'hft1': 'Fancy Feathers Hat', 'hfd1': 'Fedora', 'hmk1': "Mickey's Band Hat", 'hft2': 'Feather Headband', 'hhd2': 'Pompadour Hairdo', 'hpc1': 'Princess Hat', 'hrh1': 'Archer Hat', 'hhm1': 'Roman Helmet', 'hat2': 'Spider Antenna Thingy', 'htr1': 'Tiara', 'hhm2': 'Viking Helmet', 'hwz1': 'Witch Hat', 'hwz2': 'Wizard Hat', 'hhm3': 'Conquistador Helmet', 'hhm4': 'Firefighter Helmet', 'hfp2': 'Anti-Cog Control Hat', 'hhm5': 'Miner Hat', 'hnp1': 'Napoleon Hat', 'hpc2': 'Pilot Cap', 'hph1': 'Cop Hat', 'hwg1': 'Rainbow Wacky Wig', 'hbb4': 'Yellow Baseball Cap', 'hbb5': 'Red Baseball Cap', 'hbb6': 'Aqua Baseball Cap', 'hsl1': 'Sailor Hat', 'hfr1': 'Samba Hat', 'hby1': 'Bobby Hat', 'hrb8': 'Pink Dots Bow', 'hjh1': 'Jester Hat', 'hbb7': 'Purple Baseball Cap', 'hrb9': 'Green Checker Bow', 'hwt2': 'Winter Hat', 'hhw1': 'Bandana', 'hhw2': 'Toonosaur Hat', 'hob1': 'Jamboree Hat', 'hbn1': 'Bird Hat by Brianna'} GlassesStylesDescriptions = {'grd1': 'Round Glasses', 'gmb1': 'White Mini Blinds', 'gnr1': 'Purple Narrow Glasses', 'gst1': 'Yellow Star Glasses', 'g3d1': 'Movie Glasses', 'gav1': 'Aviator', 'gce1': 'Cateye Glasses', 'gdk1': 'Nerd Glasses', 'gjo1': 'Celebrity Shades', 'gsb1': 'Scuba Mask', 'ggl1': 'Goggles', 'ggm1': 'Groucho Glasses', 'ghg1': 'Heart Glasses', 'gie1': 'Bug Eye Glasses', 'gmt1': 'Black Secret ID Mask', 'gmt2': 'Blue Secret ID Mask', 'gmt3': 'Blue Carnivale Mask', 'gmt4': 'Purple Carnivale Mask', 'gmt5': 'Aqua Carnivale Mask', 'gmn1': 'Monocle', 'gmo1': 'Smooch Glasses', 'gsr1': 'Square Frame Glasses', 'ghw1': 'Skull Eyepatch', 'ghw2': 'Gem Eyepatch', 'gag1': 'Alien Eyes by Alexandra'} BackpackStylesDescriptions = {'bpb1': 'Blue Backpack', 'bpb2': 'Orange Backpack', 'bpb3': 'Purple BackPack', 'bpd1': 'Red Dot Backpack', 'bpd2': 'Yellow Dot Backpack', 'bwg1': 'Bat Wings', 'bwg2': 'Bee Wings', 'bwg3': 'DragonFly Wings', 'bst1': 'Scuba Tank', 'bfn1': 'Shark Fin', 'baw1': 'White Angel Wings', 'baw2': 'Rainbow Angel Wings', 'bwt1': 'Toys Backpack', 'bwg4': 'Butterfly Wings', 'bwg5': 'Pixie Wings', 'bwg6': 'Dragon Wings', 'bjp1': 'Jet Pack', 'blg1': 'Bug Backpack', 'bsa1': 'Plush Bear Pack', 'bwg7': 'Bird wings', 'bsa2': 'Plush Cat Pack', 'bsa3': 'Plush Dog Pack', 'bap1': 'Airplane Wings', 'bhw1': 'Pirate Sword', 'bhw2': 'Super Toon Cape', 'bhw3': 'Vampire Cape', 'bhw4': 'Toonosaur Backpack', 'bob1': 'Jamboree Pack', 'bfg1': 'Gag Attack Pack', 'bfl1': 'Cog Pack by Savanah'} ShoesStylesDescriptions = {'sat1': 'Green Athletic Shoes', 'sat2': 'Red Athletic Shoes', 'smb1': 'Green Toon Boots', 'scs1': 'Green Sneakers', 'swt1': 'Wingtips', 'smj1': 'Black Fancy Shoes', 'sdk1': 'Boat Shoes', 'sat3': 'Yellow Athletic Shoes', 'scs2': 'Black Sneakers', 'scs3': 'White Sneakers', 'scs4': 'Pink Sneakers', 'scb1': 'Cowboy Boots', 'sfb1': 'Purple Boots', 'sht1': 'Green Hi Top Sneakers', 'smj2': 'Brown Fancy Shoes', 'smj3': 'Red Fancy Shoes', 'ssb1': 'Red Super Toon Boots', 'sts1': 'Green Tennis Shoes', 'sts2': 'Pink Tennis Shoes', 'scs5': 'Red Sneakers', 'smb2': 'Aqua Toon Boots', 'smb3': 'Brown Toon Boots', 'smb4': 'Yellow Toon Boots', 'sfb2': 'Blue Square Boots', 'sfb3': 'Green Hearts Boots', 'sfb4': 'Grey Dots Boots', 'sfb5': 'Orange Stars Boots', 'sfb6': 'Pink Stars Boots', 'slf1': 'Loafers', 'smj4': 'Purple Fancy Shoes', 'smt1': 'Motorcycle Boots', 'sox1': 'Oxfords', 'srb1': 'Pink Rain Boots', 'sst1': 'Jolly Boots', 'swb1': 'Beige Winter Boots', 'swb2': 'Pink Winter Boots', 'swk1': 'Work Boots', 'scs6': 'Yellow Sneakers', 'smb5': 'Pink Toon Boots', 'sht2': 'Pink Hi Top Sneakers', 'srb2': 'Red Dots Rain Boots', 'sts3': 'Purple Tennis Shoes', 'sts4': 'Violet Tennis Shoes', 'sts5': 'Yellow Tennis Shoes', 'srb3': 'Blue Rain Boots', 'srb4': 'Yellow Rain Boots', 'sat4': 'Black Athletic Shoes', 'shw1': 'Pirate Shoes', 'shw2': 'Toonosaur Feet'} AccessoryNamePrefix = {0: 'hat unisex ', 1: 'glasses unisex ', 2: 'backpack unisex ', 3: 'shoes unisex ', 4: 'hat boy ', 5: 'glasses boy ', 6: 'backpack boy ', 7: 'shoes boy ', 8: 'hat girl ', 9: 'glasses girl ', 10: 'backpack girl ', 11: 'shoes girl '} AwardManagerAccessoryNames = {} AccessoryTypeNames = {} for accessoryId in CatalogAccessoryItemGlobals.AccessoryTypes.keys(): accessoryInfo = CatalogAccessoryItemGlobals.AccessoryTypes[accessoryId] if accessoryInfo[0] % 4 == 0: accessoryStyleDescription = HatStylesDescriptions elif accessoryInfo[0] % 4 == 1: accessoryStyleDescription = GlassesStylesDescriptions elif accessoryInfo[0] % 4 == 2: accessoryStyleDescription = BackpackStylesDescriptions else: accessoryStyleDescription = ShoesStylesDescriptions if accessoryInfo[3]: AwardManagerAccessoryNames[accessoryId] = AccessoryNamePrefix[accessoryInfo[0]] + accessoryStyleDescription[accessoryInfo[1]] AccessoryTypeNames[accessoryId] = accessoryStyleDescription[accessoryInfo[1]] ShirtStylesDescriptions = {'bss1': 'solid', 'bss2': 'single stripe', 'bss3': 'collar', 'bss4': 'double stripe', 'bss5': 'multiple stripes', 'bss6': 'collar w/ pocket', 'bss7': 'hawaiian', 'bss8': 'collar w/ 2 pockets', 'bss9': 'bowling shirt', 'bss10': 'vest (special)', 'bss11': 'collar w/ ruffles', 'bss12': 'soccer jersey (special)', 'bss13': 'lightning bolt (special)', 'bss14': 'jersey 19 (special)', 'bss15': 'guayavera', 'gss1': 'girl solid', 'gss2': 'girl single stripe', 'gss3': 'girl collar', 'gss4': 'girl double stripes', 'gss5': 'girl collar w/ pocket', 'gss6': 'girl flower print', 'gss7': 'girl flower trim (special)', 'gss8': 'girl collar w/ 2 pockets', 'gss9': 'girl denim vest (special)', 'gss10': 'girl peasant', 'gss11': 'girl peasant w/ mid stripe', 'gss12': 'girl soccer jersey (special)', 'gss13': 'girl hearts', 'gss14': 'girl stars (special)', 'gss15': 'girl flower', 'c_ss1': 'yellow hooded - Series 1', 'c_ss2': 'yellow with palm tree - Series 1', 'c_ss3': 'purple with stars - Series 2', 'c_bss1': 'blue stripes (boys only) - Series 1', 'c_bss2': 'orange (boys only) - Series 1', 'c_bss3': 'lime green with stripe (boys only) - Series 2', 'c_bss4': 'red kimono with checkerboard (boys only) - Series 2', 'c_gss1': 'girl blue with yellow stripes (girls only) - Series 1', 'c_gss2': 'girl pink and beige with flower (girls only) - Series 1', 'c_gss3': 'girl Blue and gold with wavy stripes (girls only) - Series 2', 'c_gss4': 'girl Blue and pink with bow (girls only) - Series 2', 'c_gss5': 'girl Aqua kimono white stripe (girls only) - UNUSED', 'c_ss4': 'Tie dye shirt (boys and girls) - Series 3', 'c_ss5': 'light blue with blue and white stripe (boys only) - Series 3', 'c_ss6': 'cowboy shirt 1 : Series 4', 'c_ss7': 'cowboy shirt 2 : Series 4', 'c_ss8': 'cowboy shirt 3 : Series 4', 'c_ss9': 'cowboy shirt 4 : Series 4', 'c_ss10': 'cowboy shirt 5 : Series 4', 'c_ss11': 'cowboy shirt 6 : Series 4', 'hw_ss1': 'Halloween Ghost', 'hw_ss2': 'Halloween Pumpkin', 'hw_ss3': 'Halloween Vampire', 'hw_ss4': 'Halloween Turtle', 'hw_ss5': 'Halloween Bee', 'hw_ss6': 'Halloween Pirate', 'hw_ss7': 'Halloween SuperToon', 'hw_ss8': 'Halloween Vampire NoCape', 'hw_ss9': 'Halloween Dinosaur', 'wh_ss1': 'Winter Holiday 1', 'wh_ss2': 'Winter Holiday 2', 'wh_ss3': 'Winter Holiday 3', 'wh_ss4': 'Winter Holiday 4', 'vd_ss1': 'girl Valentines day, pink with red hearts (girls)', 'vd_ss2': 'Valentines day, red with white hearts', 'vd_ss3': 'Valentines day, white with winged hearts (boys)', 'vd_ss4': ' Valentines day, pink with red flamed heart', 'vd_ss5': '2009 Valentines day, white with red cupid', 'vd_ss6': '2009 Valentines day, blue with green and red hearts', 'vd_ss7': '2010 Valentines day, red with white wings', 'sd_ss1': "St Pat's Day, four leaf clover shirt", 'sd_ss2': "St Pat's Day, pot o gold shirt", 'sd_ss3': 'Ides of March greenToon shirt', 'tc_ss1': 'T-Shirt Contest, Fishing Vest', 'tc_ss2': 'T-Shirt Contest, Fish Bowl', 'tc_ss3': 'T-Shirt Contest, Paw Print', 'tc_ss4': 'T-Shirt Contest, Backpack', 'tc_ss5': 'T-Shirt Contest, Lederhosen ', 'tc_ss6': 'T-Shirt Contest, Watermelon ', 'tc_ss7': 'T-Shirt Contest, Race Shirt', 'j4_ss1': 'July 4th, Flag', 'j4_ss2': 'July 4th, Fireworks', 'c_ss12': 'Catalog series 7, Green w/ yellow buttons', 'c_ss13': 'Catalog series 7, Purple w/ big flower', 'pj_ss1': 'Blue Banana Pajama shirt', 'pj_ss2': 'Red Horn Pajama shirt', 'pj_ss3': 'Purple Glasses Pajama shirt', 'sa_ss1': 'Award Striped Shirt', 'sa_ss2': 'Award Fishing Shirt 1', 'sa_ss3': 'Award Fishing Shirt 2', 'sa_ss4': 'Award Gardening Shirt 1', 'sa_ss5': 'Award Gardening Shirt 2', 'sa_ss6': 'Award Party Shirt 1', 'sa_ss7': 'Award Party Shirt 2', 'sa_ss8': 'Award Racing Shirt 1', 'sa_ss9': 'Award Racing Shirt 2', 'sa_ss10': 'Award Summer Shirt 1', 'sa_ss11': 'Award Summer Shirt 2', 'sa_ss12': 'Award Golf Shirt 1', 'sa_ss13': 'Award Golf Shirt 2', 'sa_ss14': 'Award Halloween Bee Shirt', 'sa_ss15': 'Award Halloween SuperToon Shirt', 'sa_ss16': 'Award Matathon Shirt 1', 'sa_ss17': 'Award Save Building Shirt 1', 'sa_ss18': 'Award Save Building Shirt 2', 'sa_ss19': 'Award Toontask Shirt 1', 'sa_ss20': 'Award Toontask Shirt 2', 'sa_ss21': 'Award Trolley Shirt 1', 'sa_ss22': 'Award Trolley Shirt 2', 'sa_ss23': 'Award Winter Shirt 1', 'sa_ss24': 'Award Halloween Skeleton Shirt', 'sa_ss25': 'Award Halloween Spider Shirt', 'sa_ss26': 'Award Most Cogs Defeated Shirt', 'sa_ss27': 'Award Most V.P.s Defeated Shirt', 'sa_ss28': 'Award Sellbot Smasher Shirt', 'sa_ss29': 'Award Most C.J.s Defeated Shirt', 'sa_ss30': 'Award Lawbot Smasher Shirt', 'sa_ss31': 'Award Racing Shirt 3', 'sa_ss32': 'Award Fishing Shirt 4', 'sa_ss33': 'Award Golf Shirt 3', 'sa_ss34': 'Award Most Cogs Defeated Shirt 2', 'sa_ss35': 'Award Racing Shirt 4', 'sa_ss36': 'Award Save Building Shirt 3', 'sa_ss37': 'Award Trolley Shirt 3', 'sa_ss38': 'Award Fishing Shirt 5', 'sa_ss39': 'Award Golf Shirt 4', 'sa_ss40': 'Award Halloween Witchy Moon Shirt', 'sa_ss41': 'Award Winter Holiday Sled Shirt', 'sa_ss42': 'Award Halloween Batty Moon Shirt', 'sa_ss43': 'Award Winter Holiday Mittens Shirt', 'sa_ss44': 'Award Fishing Shirt 6', 'sa_ss45': 'Award Fishing Shirt 7', 'sa_ss46': 'Award Golf Shirt 5', 'sa_ss47': 'Award Racing Shirt 5', 'sa_ss48': 'Award Racing Shirt 6', 'sa_ss49': 'Award Most Cogs Defeated shirt 3', 'sa_ss50': 'Award Most Cogs Defeated shirt 4', 'sa_ss51': 'Award Trolley shirt 4', 'sa_ss52': 'Award Trolley shirt 5', 'sa_ss53': 'Award Save Building Shirt 4', 'sa_ss54': 'Award Save Building Shirt 5', 'sa_ss55': 'Award Anniversary', 'sc_1': 'Scientist top 1', 'sc_2': 'Scientist top 2', 'sc_3': 'Scientist top 3', 'sil_1': 'Silly Mailbox Shirt', 'sil_2': 'Silly Trash Can Shirt', 'sil_3': 'Loony Labs Shirt', 'sil_4': 'Silly Hydrant Shirt', 'sil_5': 'Sillymeter Whistle Shirt', 'sil_6': 'Silly Cog-Crusher Shirt', 'sil_7': 'Victory Party Shirt 1', 'sil_8': 'Victory Party Shirt 2', 'emb_us1': 'placeholder emblem shirt 1', 'emb_us2': 'placeholder emblem shirt 2', 'emb_us3': 'placeholder emblem shirt 3', 'sb_1': 'Sellbot Icon Shirt', 'lb_1': 'Lawbot Icon Shirt', 'jb_1': 'Jellybean Shirt', 'jb_2': 'Doodle Shirt', 'ugcms': 'Get Connected Mover & Shaker'} BottomStylesDescriptions = {'bbs1': 'plain w/ pockets', 'bbs2': 'belt', 'bbs3': 'cargo', 'bbs4': 'hawaiian', 'bbs5': 'side stripes (special)', 'bbs6': 'soccer shorts', 'bbs7': 'side flames (special)', 'bbs8': 'denim', 'vd_bs1': 'Valentines shorts', 'vd_bs2': 'Green with red heart', 'vd_bs3': 'Blue denim with green and red heart', 'c_bs1': 'Orange with blue side stripes', 'c_bs2': 'Blue with gold cuff stripes', 'c_bs5': 'Green stripes - series 7', 'sd_bs1': 'St. Pats leprechaun shorts', 'sd_bs2': 'Ides of March greenToon shorts', 'pj_bs1': 'Blue Banana Pajama pants', 'pj_bs2': 'Red Horn Pajama pants', 'pj_bs3': 'Purple Glasses Pajama pants', 'wh_bs1': 'Winter Holiday Shorts Style 1', 'wh_bs2': 'Winter Holiday Shorts Style 2', 'wh_bs3': 'Winter Holiday Shorts Style 3', 'wh_bs4': 'Winter Holiday Shorts Style 4', 'hw_bs1': 'Halloween Bee Shorts male', 'hw_bs2': 'Halloween Pirate Shorts male', 'hw_bs5': 'Halloween SuperToon Shorts male', 'hw_bs6': 'Halloween Vampire NoCape Shorts male', 'hw_bs7': 'Halloween Dinosaur Shorts male', 'sil_bs1': 'Silly Cog-Crusher Shorts', 'gsk1': 'solid', 'gsk2': 'polka dots (special)', 'gsk3': 'vertical stripes', 'gsk4': 'horizontal stripe', 'gsk5': 'flower print', 'gsk6': '2 pockets (special) ', 'gsk7': 'denim skirt', 'gsh1': 'plain w/ pockets', 'gsh2': 'flower', 'gsh3': 'denim shorts', 'c_gsk1': 'blue skirt with tan border and button', 'c_gsk2': 'purple skirt with pink and ribbon', 'c_gsk3': 'teal skirt with yellow and star', 'vd_gs1': 'red skirt with hearts', 'vd_gs2': 'Pink flair skirt with polka hearts', 'vd_gs3': 'Blue denim skirt with green and red heart', 'c_gsk4': 'rainbow skirt - Series 3', 'sd_gs1': 'St. Pats day shorts', 'sd_gs2': 'Ides of March greenToon skirt', 'c_gsk5': 'Western skirts 1', 'c_gsk6': 'Western skirts 2', 'c_bs3': 'Western shorts 1', 'c_bs4': 'Western shorts 2', 'j4_bs1': 'July 4th shorts', 'j4_gs1': 'July 4th Skirt', 'c_gsk7': 'Blue with flower - series 7', 'pj_gs1': 'Blue Banana Pajama pants', 'pj_gs2': 'Red Horn Pajama pants', 'pj_gs3': 'Purple Glasses Pajama pants', 'wh_gsk1': 'Winter Holiday Skirt Style 1', 'wh_gsk2': 'Winter Holiday Skirt Style 2', 'wh_gsk3': 'Winter Holiday Skirt Style 3', 'wh_gsk4': 'Winter Holiday Skirt Style 4', 'sa_bs1': 'Award Fishing Shorts', 'sa_bs2': 'Award Gardening Shorts', 'sa_bs3': 'Award Party Shorts', 'sa_bs4': 'Award Racing Shorts', 'sa_bs5': 'Award Summer Shorts', 'sa_bs6': 'Award Golf Shorts 1', 'sa_bs7': 'Award Halloween Bee Shorts', 'sa_bs8': 'Award Halloween SuperToon Shorts', 'sa_bs9': 'Award Save Building Shorts 1', 'sa_bs10': 'Award Trolley Shorts 1', 'sa_bs11': 'Award Halloween Spider Shorts', 'sa_bs12': 'Award Halloween Skeleton Shorts', 'sa_bs13': 'Award Sellbot Smasher Shorts male', 'sa_bs14': 'Award Lawbot Smasher Shorts male', 'sa_bs15': 'Award Racing Shorts 1', 'sa_bs16': 'Award Golf Shorts 3', 'sa_bs17': 'Award Racing Shorts 4', 'sa_bs18': 'Award Golf Shorts 4', 'sa_bs19': 'Award Golf Shorts 5', 'sa_bs20': 'Award Racing Shorts 5', 'sa_bs21': 'Award Racing Shorts 6', 'sa_gs1': 'Award Fishing Skirt', 'sa_gs2': 'Award Gardening Skirt', 'sa_gs3': 'Award Party Skirt', 'sa_gs4': 'Award Racing Skirt', 'sa_gs5': 'Award Summer Skirt', 'sa_gs6': 'Award Golf Skirt 1', 'sa_gs7': 'Award Halloween Bee Skirt', 'sa_gs8': 'Award Halloween SuperToon Skirt', 'sa_gs9': 'Award Save Building Skirt 1', 'sa_gs10': 'Award Trolley Skirt 1', 'sa_gs11': 'Award Halloween Skeleton Skirt', 'sa_gs12': 'Award Halloween Spider Skirt', 'sa_gs13': 'Award Sellbot Smasher Shorts female', 'sa_gs14': 'Award Lawbot Smasher Shorts female', 'sa_gs15': 'Award Racing Skirt 1', 'sa_gs16': 'Award Golf Skirt 2', 'sa_gs17': 'Award Racing Skirt 4', 'sa_gs18': 'Award Golf Skirt 3', 'sa_gs19': 'Award Golf Skirt 4', 'sa_gs20': 'Award Racing Skirt 5', 'sa_gs21': 'Award Racing Skirt 6', 'sc_bs1': 'Scientist bottom male 1', 'sc_bs2': 'Scientist bottom male 2', 'sc_bs3': 'Scientist bottom male 3', 'sc_gs1': 'Scientist bottom female 1', 'sc_gs2': 'Scientist bottom female 2', 'sc_gs3': 'Scientist bottom female 3', 'sil_bs1': 'Silly Cog-Crusher Shorts male', 'sil_gs1': 'Silly Cog-Crusher Shorts female', 'hw_bs3': 'Halloween Vampire Shorts male', 'hw_gs3': 'Halloween Vampire Shorts female', 'hw_bs4': 'Halloween Turtle Shorts male', 'hw_gs4': 'Halloween Turtle Shorts female', 'hw_gs1': 'Halloween Bee Shorts female', 'hw_gs2': 'Halloween Pirate Shorts female', 'hw_gs5': 'Halloween SuperToon Shorts female', 'hw_gs6': 'Halloween Vampire NoCape Shorts female', 'hw_gs7': 'Halloween Dinosaur Shorts female', 'hw_gsk1': 'Halloween Pirate Skirt'} AwardMgrBoy = 'boy' AwardMgrGirl = 'girl' AwardMgrUnisex = 'unisex' AwardMgrShorts = 'shorts' AwardMgrSkirt = 'skirt' AwardMgrShirt = 'shirt' SpecialEventMailboxStrings = {1: 'A special item from the Toon Council just for you!', 2: "Here is your Melville's Fishing Tournament prize! Congratulations!", 3: "Here is your Billy Budd's Fishing Tournament prize! Congratulations!", 4: 'Here is your Acorn Acres April Invitational prize! Congratulations!', 5: 'Here is your Acorn Acres C.U.P. Championship prize! Congratulations!', 6: 'Here is your Gift-Giving Extravaganza prize! Congratulations!', 7: "Here is your Top Toons New Year's Day Marathon prize! Congratulations!", 8: 'Here is your Perfect Trolley Games Weekend prize! Congratulations!', 9: 'Here is your Trolley Games Madness prize! Congratulations!', 10: 'Here is your Grand Prix Weekend prize! Congratulations!', 11: 'Here is your ToonTask Derby prize! Congratulations!', 12: 'Here is your Save a Building Marathon prize! Congratulations!', 13: 'Here is your Most Cogs Defeated Tournament prize! Congratulations!', 14: 'Here is your Most V.P.s Defeated Tournament prize! Congratulations!', 15: 'Here is your Operation: Storm Sellbot prize! Congratulations!', 16: 'Here is your Most C.J.s Defeated Tournament prize! Congratulations!', 17: 'Here is your Operation: Lawbots Lose prize! Congratulations!'} RentalHours = 'Hours' RentalOf = 'Of' RentalCannon = 'Cannons!' RentalGameTable = 'Game Table!' EstateCannonGameEnd = 'The Cannon Game rental is over.' GameTableRentalEnd = 'The Game Table rental is over.' MessageConfirmRent = 'Begin rental? Cancel to save the rental for later' MessageConfirmGarden = 'Are you sure you want to start a garden?' NametagPaid = 'Citizen Name Tag' NametagAction = 'Action Name Tag' NametagFrilly = 'Frilly Name Tag' FurnitureYourOldCloset = 'your old wardrobe' FurnitureYourOldBank = 'your old bank' FurnitureYourOldTrunk = 'your old trunk' TrunkHatGUI = 'Hats' TrunkGlassesGUI = 'Glasses' TrunkBackpackGUI = 'Backpacks' TrunkShoesGUI = 'Shoes' ChatItemQuotes = '"%s"' FurnitureNames = {100: 'Armchair', 105: 'Armchair', 110: 'Chair', 120: 'Desk Chair', 130: 'Log Chair', 140: 'Lobster Chair', 145: 'Lifejacket Chair', 150: 'Saddle Stool', 160: 'Native Chair', 170: 'Cupcake Chair', 200: 'Bed', 205: 'Bed', 210: 'Bed', 220: 'Bathtub Bed', 230: 'Leaf Bed', 240: 'Boat Bed', 250: 'Cactus Hammock', 260: 'Ice Cream Bed', 270: "Olivia Erin & Cat's Bed", 300: 'Player Piano', 310: 'Pipe Organ', 400: 'Fireplace', 410: 'Fireplace', 420: 'Round Fireplace', 430: 'Fireplace', 440: 'Apple Fireplace', 450: "Erin's Fireplace", 460: "Erin's Lit Fireplace", 470: 'Lit Fireplace', 480: 'Round Lit Fireplace', 490: 'Lit Fireplace', 491: 'Lit Fireplace', 492: 'Apple Lit Fireplace', 500: 'Wardrobe', 502: '15 item Wardrobe', 504: '20 item Wardrobe', 506: '25 item Wardrobe', 508: '50 item Wardrobe', 510: 'Wardrobe', 512: '15 item Wardrobe', 514: '20 item Wardrobe', 516: '25 item Wardrobe', 518: '50 item Wardrobe', 600: 'Short Lamp', 610: 'Tall Lamp', 620: 'Table Lamp', 625: 'Table Lamp', 630: 'Daisy Lamp', 640: 'Daisy Lamp', 650: 'Jellyfish Lamp', 660: 'Jellyfish Lamp', 670: 'Cowboy Lamp', 680: 'Candle', 681: 'Lit Candle', 700: 'Cushioned Chair', 705: 'Cushioned Chair', 710: 'Couch', 715: 'Couch', 720: 'Hay Couch', 730: 'Shortcake Couch', 800: 'Desk', 810: 'Log Desk', 900: 'Umbrella Stand', 910: 'Coat Rack', 920: 'Trash Can', 930: 'Red Mushroom', 940: 'Yellow Mushroom', 950: 'Coat Rack', 960: 'Barrel Stand', 970: 'Cactus Plant', 980: 'Teepee', 990: "Juliette's Fan", 1000: 'Large Rug', 1010: 'Round Rug', 1015: 'Round Rug', 1020: 'Small Rug', 1030: 'Leaf Mat', 1040: 'Presents', 1050: 'Sled', 1100: 'Display Cabinet', 1110: 'Display Cabinet', 1120: 'Tall Bookcase', 1130: 'Low Bookcase', 1140: 'Sundae Chest', 1200: 'End Table', 1210: 'Small Table', 1215: 'Small Table', 1220: 'Coffee Table', 1230: 'Coffee Table', 1240: "Snorkeler's Table", 1250: 'Cookie Table', 1260: 'Bedroom Table', 1300: 'Jellybean Bank', # 1000 (original value) 1310: '2500 Bean Bank', 1320: '5000 Bean Bank', 1330: '7500 Bean Bank', 1340: '10000 Bean Bank', 1350: '60000 Bean Bank', 1399: 'Telephone', 1400: 'Cezanne Toon', 1410: 'Flowers', 1420: 'Modern Mickey', 1430: 'Rembrandt Toon', 1440: 'Toonscape', 1441: "Whistler's Horse", 1442: 'Toon Star', 1443: 'Not a Pie', 1450: 'Mickey and Minnie', 1500: 'Radio', 1510: 'Radio', 1520: 'Radio', 1530: 'Television', 1600: 'Short Vase', 1610: 'Tall Vase', 1620: 'Short Vase', 1630: 'Tall Vase', 1640: 'Short Vase', 1650: 'Short Vase', 1660: 'Coral Vase', 1661: 'Shell Vase', 1670: 'Rose Vase', 1680: 'Rose Watercan', 1700: 'Popcorn Cart', 1710: 'Ladybug', 1720: 'Fountain', 1725: 'Washing Machine', 1800: 'Fish Bowl', 1810: 'Fish Bowl', 1900: 'Swordfish', 1910: 'Hammerhead', 1920: 'Hanging Horns', 1930: 'Simple Sombrero', 1940: 'Fancy Sombrero', 1950: 'Dream Catcher', 1960: 'Horseshoe', 1970: 'Bison Portrait', 2000: 'Candy Swing Set', 2010: 'Cake Slide', 3000: 'Banana Split Tub', 4000: 'Boy Trunk', 4010: 'Girl Trunk', 10000: 'Short Pumpkin', 10010: 'Tall Pumpkin', 10020: 'Christmas Tree', 10030: 'Winter Wreath'} AwardManagerFurnitureNames = {100: 'Armchair A - Series 1', 105: 'Armchair A - Series 7', 110: 'Chair - Series 1', 120: 'Desk Chair - Series 2', 130: 'Log Chair - Series 2', 140: 'Lobster Chair - Series 3', 145: 'Lifejacket Chair - Series 3', 150: 'Saddle Stool - Series 4', 160: 'Native Chair - Series 4', 170: 'Cupcake Chair - Series 6', 200: "Bed Boy's bed - Initial Furniture", 205: "Bed Boy's bed Series 7", 210: "Bed Girl's bed - Series 1", 220: 'Bathtub Bed', 230: 'Leaf Bed', 240: 'Boat Bed', 250: 'Cactus Hammock', 260: 'Ice Cream Bed', 270: "Olivia Erin & Cat's Bed - Trolley Bed", 300: 'Player Piano', 310: 'Pipe Organ', 400: 'Fireplace - Square Fireplace Initial Furniture', 410: 'Fireplace - Girly Fireplace Series 1', 420: 'Round Fireplace', 430: 'Fireplace - bug room series 2', 440: 'Apple Fireplace', 450: "Erin's Fireplace - coral", 460: "Erin's Lit Fireplace - coral", 470: 'Lit Fireplace - square fireplace with fire', 480: 'Round Lit Fireplace', 490: 'Lit Fireplac - girl fireplace with firee', 491: 'Lit Fireplace - bug room fireplace', 492: 'Apple Lit Fireplace', 500: 'boy Wardrobe - 10 items initial', 502: 'boy 15 item Wardrobe', 504: 'boy 20 item Wardrobe', 506: 'boy 25 item Wardrobe', 508: 'boy 50 item Wardrobe', 510: 'girl Wardrobe - 10 items initial', 512: 'girl 15 item Wardrobe', 514: 'girl 20 item Wardrobe', 516: 'girl 25 item Wardrobe', 518: 'girl 50 item Wardrobe', 600: 'Short Lamp', 610: 'Tall Lamp', 620: 'Table Lamp - Series 1', 625: 'Table Lamp - Series 7', 630: 'Daisy Lamp 1', 640: 'Daisy Lamp 2', 650: 'Jellyfish Lamp 1', 660: 'Jellyfish Lamp 2', 670: 'Cowboy Lamp', 680: 'Candle', 681: 'Lit Candle', 700: 'Cushioned Chair - Series 1', 705: 'Cushioned Chair - Series 7', 710: 'Couch - series 1', 715: 'Couch - series 7', 720: 'Hay Couch', 730: 'Shortcake Couch', 800: 'Desk', 810: 'Log Desk', 900: 'Umbrella Stand', 910: 'Coat Rack - series 1', 920: 'Trash Can', 930: 'Red Mushroom', 940: 'Yellow Mushroom', 950: 'Coat Rack - underwater', 960: 'Barrel Stand', 970: 'Cactus Plant', 980: 'Teepee', 990: "Juliette's Fan - gag fan", 1000: 'Large Rug', 1010: 'Round Rug - Series 1', 1015: 'Round Rug - Series 7', 1020: 'Small Rug', 1030: 'Leaf Mat', 1040: 'Presents', 1050: 'Sled', 1100: 'Display Cabinet - Red', 1110: 'Display Cabinet - Yellow', 1120: 'Tall Bookcase', 1130: 'Low Bookcase', 1140: 'Sundae Chest', 1200: 'End Table', 1210: 'Small Table - series 1 ', 1215: 'Small Table - series 7', 1220: 'Coffee Table sq', 1230: 'Coffee Table bw', 1240: "Snorkeler's Table", 1250: 'Cookie Table', 1260: 'Bedroom Table', 1300: '1000 Bean Bank', 1310: '2500 Bean Bank', 1320: '5000 Bean Bank', 1330: '7500 Bean Bank', 1340: '10000 Bean Bank', 1350: '60000 Bean Bank', 1399: 'Telephone', 1400: 'Cezanne Toon', 1410: 'Flowers', 1420: 'Modern Mickey', 1430: 'Rembrandt Toon', 1440: 'Toonscape', 1441: "Whistler's Horse", 1442: 'Toon Star', 1443: 'Not a Pie', 1450: 'Mickey and Minnie', 1500: 'Radio A series 2', 1510: 'Radio B series 1', 1520: 'Radio C series 2', 1530: 'Television', 1600: 'Short Vase A', 1610: 'Tall Vase A', 1620: 'Short Vase B', 1630: 'Tall Vase B', 1640: 'Short Vase C', 1650: 'Short Vase D', 1660: 'Coral Vase', 1661: 'Shell Vase', 1670: 'Rose Vase', 1680: 'Rose Watercan', 1700: 'Popcorn Cart', 1710: 'Ladybug', 1720: 'Fountain', 1725: 'Washing Machine', 1800: 'Fish Bowl skull', 1810: 'Fish Bowl lizard', 1900: 'Swordfish', 1910: 'Hammerhead', 1920: 'Hanging Horns', 1930: 'Simple Sombrero', 1940: 'Fancy Sombrero', 1950: 'Dream Catcher', 1960: 'Horseshoe', 1970: 'Bison Portrait', 2000: 'Candy Swing Set', 2010: 'Cake Slide', 3000: 'Banana Split Tub', 4000: 'Boy Trunk', 4010: 'Girl Trunk', 10000: 'Short Pumpkin', 10010: 'Tall Pumpkin', 10020: 'Winter Tree', 10030: 'Winter Wreath'} ClothingArticleNames = ('Shirt', 'Shirt', 'Shirt', 'Shorts', 'Shorts', 'Skirt', 'Shorts') ClothingTypeNames = {1001: 'Ghost Shirt', 1002: 'Pumpkin Shirt', 1112: 'Bee Shirt', 1113: 'Pirate Shirt', 1114: 'Super Toon Shirt', 1115: 'Vampire Shirt', 1116: 'Toonosaur Shirt', 1117: 'Bee Shorts', 1118: 'Pirate Shorts', 1119: 'Super Toon Shorts', 1120: 'Vampire Shorts', 1121: 'Toonosaur Shorts', 1122: 'Bee Shorts', 1123: 'Pirate Shorts', 1124: 'Super Toon Shorts', 1125: 'Vampire Shorts', 1126: 'Toonosaur Shorts', 1127: 'Pirate Skirt', 1304: "O'Shirt", 1305: "O'Shorts", 1306: "O'Skirt", 1400: "Matthew's Shirt", 1401: "Jessica's Shirt", 1402: "Marissa's Shirt", 1600: 'Trap Outfit', 1601: 'Sound Outfit', 1602: 'Lure Outfit', 1603: 'Trap Outfit', 1604: 'Sound Outfit', 1605: 'Lure Outfit', 1606: 'Trap Outfit', 1607: 'Sound Outfit', 1608: 'Lure Outfit', 1723: 'Bee Shirt', 1724: 'SuperToon Shirt', 1734: 'Bee Shorts', 1735: 'SuperToon Shorts', 1739: 'Bee Skirt', 1740: 'SuperToon Skirt', 1743: 'Skeleton Shirt', 1744: 'Spider Shirt', 1745: 'Spider Shorts', 1746: 'Skeleton Shorts', 1747: 'Skeleton Skirt', 1748: 'Spider Skirt', 1749: 'Silly Mailbox Shirt', 1750: 'Silly Trash Can Shirt', 1751: 'Loony Labs Shirt', 1752: 'Silly Hydrant Shirt', 1753: 'Silly Meter Shirt', 1754: 'Cog-Crusher Shirt', 1755: 'Cog-Crusher Shorts', 1756: 'Cog-Crusher Shorts', 1757: 'Victory Party Shirt', 1758: 'Relaxed Victory Shirt', 1763: 'Smashed Sellbot Shirt', 1764: 'Most V.P.s Defeated Shirt', 1765: 'Sellbot Smasher Shirt', 1766: 'Sellbot Smasher Shorts', 1767: 'Sellbot Smasher Shorts', 1768: 'Jellybean Bank Shirt', 1769: 'Doodle Shirt', 1770: 'Vampire Shirt', 1771: 'Turtle Shirt', 1772: 'Vampire Shorts', 1773: 'Vampire Shorts', 1774: 'Turtle Shorts', 1775: 'Turtle Shorts', 1776: 'Get Connected Mover & Shaker Shirt', 1777: 'Smashed Lawbot Shirt', 1778: 'Most C.J.s Defeated Shirt', 1779: 'Lawbot Smasher Shirt', 1780: 'Lawbot Smasher Shorts', 1781: 'Lawbot Smasher Shorts', 1782: 'Racing Shirt 3', 1783: 'Racing Shorts 1', 1784: 'Racing Skirt 1', 1801: 'Batty Moon Shirt', 1802: 'Mittens Shirt'} AccessoryArticleNames = ('Hat', 'Glasses', 'Backpack', 'Shoes', 'Hat', 'Glasses', 'Backpack', 'Shoes', 'Hat', 'Glasses', 'Backpack', 'Shoes') SurfaceNames = ('Wallpaper', 'Moulding', 'Flooring', 'Wainscoting', 'Border') WallpaperNames = {1000: 'Parchment', 1100: 'Milan', 1200: 'Dover', 1300: 'Victoria', 1400: 'Newport', 1500: 'Pastoral', 1600: 'Harlequin', 1700: 'Moon', 1800: 'Stars', 1900: 'Flowers', 2000: 'Spring Garden', 2100: 'Formal Garden', 2200: 'Race Day', 2300: 'Touchdown!', 2400: 'Cloud 9', 2500: 'Climbing Vine', 2600: 'Springtime', 2700: 'Kokeshi', 2800: 'Posies', 2900: 'Angel Fish', 3000: 'Bubbles', 3100: 'Bubbles', 3200: 'Go Fish', 3300: 'Stop Fish', 3400: 'Sea Horse', 3500: 'Sea Shells', 3600: 'Underwater', 3700: 'Boots', 3800: 'Cactus', 3900: 'Cowboy Hat', 10100: 'Cats', 10200: 'Bats', 11000: 'Snowflakes', 11100: 'Hollyleaf', 11200: 'Snowman', 12000: 'ValenToons', 12100: 'ValenToons', 12200: 'ValenToons', 12300: 'ValenToons', 13000: 'Shamrock', 13100: 'Shamrock', 13200: 'Rainbow', 13300: 'Shamrock'} FlooringNames = {1000: 'Hardwood Floor', 1010: 'Carpet', 1020: 'Diamond Tile', 1030: 'Diamond Tile', 1040: 'Grass', 1050: 'Beige Bricks', 1060: 'Red Bricks', 1070: 'Square Tile', 1080: 'Stone', 1090: 'Boardwalk', 1100: 'Dirt', 1110: 'Wood Tile', 1120: 'Tile', 1130: 'Honeycomb', 1140: 'Water', 1150: 'Beach Tile', 1160: 'Beach Tile', 1170: 'Beach Tile', 1180: 'Beach Tile', 1190: 'Sand', 10000: 'Ice Cube', 10010: 'Igloo', 11000: 'Shamrock', 11010: 'Shamrock', 11020: 'Debbie Dick'} MouldingNames = {1000: 'Knotty', 1010: 'Painted', 1020: 'Dental', 1030: 'Flowers', 1040: 'Flowers', 1050: 'Ladybug', 1060: 'ValenToons', 1070: 'Beach', 1080: 'Winter Lights 1', 1085: 'Winter Lights 2', 1090: 'Winter Lights 3', 1100: "ValenToon's Cupid", 1110: "ValenToon's Heart 1", 1120: "ValenToon's Heart 2"} WainscotingNames = {1000: 'Painted', 1010: 'Wood Panel', 1020: 'Wood', 1030: 'ValenToons', 1040: 'Underwater'} WindowViewNames = {10: 'Large Garden', 20: 'Wild Garden', 30: 'Greek Garden', 40: 'Cityscape', 50: 'Wild West', 60: 'Under the Sea', 70: 'Tropical Island', 80: 'Starry Night', 90: 'Tiki Pool', 100: 'Frozen Frontier', 110: 'Farm Country', 120: 'Native Camp', 130: 'Main Street'} SpecialEventNames = {1: 'Generic Award', 2: "Melville's Fishing Tournament", 3: "Billy Budd's Fishing Tournament", 4: 'Acorn Acres April Invitational', 5: 'Acorn Acres C.U.P. Championship', 6: 'Gift-Giving Extravaganza', 7: "Top Toons New Year's Day Marathon", 8: 'Perfect Trolley Games Weekend', 9: 'Trolley Games Madness', 10: 'Grand Prix Weekend', 11: 'ToonTask Derby', 12: 'Save a Building Marathon', 13: 'Most Cogs Defeated', 14: 'Most V.P.s Defeated', 15: 'Operation Storm Sellbot Event', 16: 'Most C.J.s Defeated', 17: 'Operation Lawbots Lose Event'} NewCatalogNotify = 'There are new items available to order at your phone!' NewDeliveryNotify = 'A new delivery has just arrived at your mailbox!' CatalogNotifyFirstCatalog = 'Your first cattlelog has arrived! You may use this to order new items for yourself or for your house.' CatalogNotifyNewCatalog = 'Your cattlelog #%s has arrived! You can go to your phone to order items from this cattlelog.' CatalogNotifyNewCatalogNewDelivery = 'A new delivery has arrived at your mailbox! Also, your cattlelog #%s has arrived!' CatalogNotifyNewDelivery = 'A new delivery has arrived at your mailbox!' CatalogNotifyNewCatalogOldDelivery = 'Your cattlelog #%s has arrived, and there are still items waiting in your mailbox!' CatalogNotifyOldDelivery = 'There are still items waiting in your mailbox for you to pick up!' CatalogNotifyInstructions = 'Click the "Go home" button on the map page in your Shticker Book, then walk up to the phone inside your house.' CatalogNewDeliveryButton = 'New\nDelivery!' CatalogNewCatalogButton = 'New\nCattlelog' CatalogSaleItem = 'Sale! ' DistributedMailboxEmpty = 'Your mailbox is empty right now. Come back here to look for deliveries after you place an order from your phone!' DistributedMailboxWaiting = 'Your mailbox is empty right now, but the package you ordered is on its way. Check back later!' DistributedMailboxReady = 'Your order has arrived!' DistributedMailboxNotOwner = 'Sorry, this is not your mailbox.' DistributedPhoneEmpty = "You can use any phone to order special items for you and your house. New items will become available to order over time.\n\nYou don't have any items available to order right now, but check back later!" Clarabelle = 'Clarabelle' MailboxExitButton = 'Close Mailbox' MailboxAcceptButton = 'Take this item' MailBoxDiscard = 'Discard this item' MailboxAcceptInvite = 'Accept this invite' MailBoxRejectInvite = 'Reject this invite' MailBoxDiscardVerify = 'Are you sure you want to Discard %s?' MailBoxRejectVerify = 'Are you sure you want to Reject %s?' MailboxOneItem = 'Your mailbox contains 1 item.' MailboxNumberOfItems = 'Your mailbox contains %s items.' MailboxGettingItem = 'Taking %s from mailbox.' MailboxGiftTag = 'Gift From: %s' MailboxGiftTagAnonymous = 'Anonymous' MailboxItemNext = 'Next\nItem' MailboxItemPrev = 'Previous\nItem' MailboxDiscard = 'Discard' MailboxReject = 'Reject' MailboxLeave = 'Keep' CatalogCurrency = 'beans' CatalogHangUp = 'Hang Up' CatalogNew = 'NEW' CatalogBackorder = 'BACKORDER' CatalogSpecial = 'SPECIAL' CatalogEmblem = 'EMBLEM' CatalogPagePrefix = 'Page' CatalogGreeting = "Hello! Thanks for calling Clarabelle's Cattlelog. Can I help you?" CatalogGoodbyeList = ['Bye now!', 'Call back soon!', 'Thanks for calling!', 'Ok, bye now!', 'Bye!'] CatalogHelpText1 = 'Turn the page to see items for sale.' CatalogSeriesLabel = 'Series %s' CatalogGiftFor = 'Buy Gift for:' CatalogGiftTo = 'To: %s' CatalogGiftToggleOn = 'Stop Gifting' CatalogGiftToggleOff = 'Buy Gifts' CatalogGiftToggleWait = 'Trying!...' CatalogGiftToggleNoAck = 'Unavailable' CatalogPurchaseItemAvailable = 'Congratulations on your new purchase! You can start using it right away.' CatalogPurchaseGiftItemAvailable = 'Excellent! %s can start using your gift right away.' CatalogPurchaseItemOnOrder = 'Congratulations! Your purchase will be delivered to your mailbox soon.' CatalogPurchaseGiftItemOnOrder = 'Excellent! Your gift to %s will be delivered to their mailbox.' CatalogAnythingElse = 'Anything else I can get you today?' CatalogPurchaseClosetFull = 'Your closet is full. You may purchase this item anyway, but if you do you will need to delete something from your closet to make room for it when it arrives.\n\nDo you still want to purchase this item?' CatalogPurchaseNoTrunk = 'In order to wear this item, you need to buy a trunk.\n\nDo you still want to purchase this item?' CatalogPurchaseTrunkFull = 'Your trunk is full. If you purchase this item, you\xe2\x80\x99ll need to delete another item from your trunk to make more room.\n\nDo you still want to purchase this item?' CatalogAcceptClosetFull = 'Your closet is full. You must go inside and delete something from your closet to make room for this item before you can take it out of your mailbox.' CatalogAcceptNoTrunk = "You don't have a trunk. You must buy a trunk before you can take this item out of your mailbox." CatalogAcceptTrunkFull = 'Your trunk is full. You must delete something from your trunk before you can take this item out of your mailbox.' CatalogAcceptShirt = 'You are now wearing your new hat. The hat you were wearing before has been moved to your trunk.' CatalogAcceptShorts = 'You are now wearing your new shorts. What you were wearing before has been moved to your closet.' CatalogAcceptSkirt = 'You are now wearing your new skirt. What you were wearing before has been moved to your closet.' CatalogAcceptHat = 'You are now wearing your new hat. The hat you were wearing before has been moved to your trunk.' CatalogAcceptGlasses = 'You are now wearing your new glasses. The glasses you were wearing before have been moved to your trunk.' CatalogAcceptBackpack = 'You are now wearing your new backpack. The backpack you were wearing before has been moved to your trunk.' CatalogAcceptShoes = 'You are now wearing your new shoes. The shoes you were wearing before have been moved to your trunk.' CatalogAcceptPole = "You're now ready to go catch some bigger fish with your new pole!" CatalogAcceptPoleUnneeded = 'You already have a better pole than this one!' CatalogAcceptChat = 'You now have a new SpeedChat!' CatalogAcceptEmote = 'You now have a new Emotion!' CatalogAcceptBeans = 'You received some jelly beans!' CatalogAcceptRATBeans = 'Your Toon recruit reward has arrived!' CatalogAcceptPartyRefund = "Your party was never started. Here's your refund!" CatalogAcceptNametag = 'Your new name tag has arrived!' CatalogAcceptGarden = 'Your garden supplies have arrived!' CatalogAcceptPet = 'You now have a new Pet Trick!' CatalogPurchaseHouseFull = 'Your house is full. You may purchase this item anyway, but if you do you will need to delete something from your house to make room for it when it arrives.\n\nDo you still want to purchase this item?' CatalogAcceptHouseFull = 'Your house is full. You can not accept this item until you free up some room. Would you like to discard this item now?' CatalogAcceptInAttic = 'Your new item is now in your attic. You can put it in your house by going inside and clicking on the "Move Furniture" button.' CatalogAcceptInAtticP = 'Your new items are now in your attic. You can put them in your house by going inside and clicking on the "Move Furniture" button.' CatalogPurchaseMailboxFull = "Your mailbox is full! You can't purchase this item until you take some items out of your mailbox to make room." CatalogPurchaseGiftMailboxFull = "%s's mailbox is full! You can't purchase this item." CatalogPurchaseOnOrderListFull = "You have too many items currently on order. You can't order any more items until some of the ones you have already ordered arrive." CatalogPurchaseGiftOnOrderListFull = '%s has too many items currently on order.' CatalogPurchaseGeneralError = 'The item could not be purchased because of some internal game error: error code %s.' CatalogPurchaseGiftGeneralError = 'The item could not be gifted to %(friend)s because of some internal game error: error code %(error)s.' CatalogPurchaseGiftNotAGift = 'This item could not be sent to %s because it would be an unfair advantage.' CatalogPurchaseGiftWillNotFit = "This item could not be sent to %s because it doesn't fit them." CatalogPurchaseGiftLimitReached = "This item could not be sent to %s because they've already have it." CatalogPurchaseGiftNotEnoughMoney = "This item could not be sent to %s because you can't afford it." CatalogAcceptGeneralError = 'The item could not be removed from your mailbox because of some internal game error: error code %s.' CatalogAcceptRoomError = "You don't have any place to put this. You'll have to get rid of something." CatalogAcceptLimitError = "You already have as many of these as you can handle. You'll have to get rid of something." CatalogAcceptFitError = "This won't fit you!" CatalogAcceptInvalidError = 'This item has gone out of style!' CatalogAcceptClosetError = 'You already have a bigger closet!' MailboxOverflowButtonDicard = 'Discard' MailboxOverflowButtonLeave = 'Leave' HDMoveFurnitureButton = 'Move\nFurniture' HDStopMoveFurnitureButton = 'Done\nMoving' HDAtticPickerLabel = 'In the attic' HDInRoomPickerLabel = 'In the room' HDInTrashPickerLabel = 'In the trash' HDDeletePickerLabel = 'Delete?' HDInAtticLabel = 'Attic' HDInRoomLabel = 'Room' HDInTrashLabel = 'Trash' HDToAtticLabel = 'Send\nto attic' HDMoveLabel = 'Move' HDRotateCWLabel = 'Rotate Right' HDRotateCCWLabel = 'Rotate Left' HDReturnVerify = 'Return this item to the attic?' HDReturnFromTrashVerify = 'Return this item to the attic from the trash?' HDDeleteItem = 'Click OK to send this item to the trash, or Cancel to keep it.' HDNonDeletableItem = "You can't delete items of this type!" HDNonDeletableBank = "You can't delete your bank!" HDNonDeletableCloset = "You can't delete your wardrobe!" HDNonDeletablePhone = "You can't delete your phone!" HDNonDeletableTrunk = "You can't delete your trunk!" HDNonDeletableNotOwner = "You can't delete %s's things!" HDHouseFull = 'Your house is full. You have to delete something else from your house or attic before you can return this item from the trash.' HDHelpDict = {'DoneMoving': 'Finish room decorating.', 'Attic': 'Show list of items in attic. The attic stores items that are not in your room.', 'Room': 'Show list of items in room. Useful for finding lost items.', 'Trash': 'Show items in trash. Oldest items are deleted after a while or when trash overflows.', 'ZoomIn': 'Get a closer view of room.', 'ZoomOut': 'Get a farther view of room.', 'SendToAttic': 'Send the current furniture item to attic for storage.', 'RotateLeft': 'Turn left.', 'RotateRight': 'Turn right.', 'DeleteEnter': 'Change to delete mode.', 'DeleteExit': 'Exit delete mode.', 'FurnitureItemPanelDelete': 'Send %s to trash.', 'FurnitureItemPanelAttic': 'Place %s in room.', 'FurnitureItemPanelRoom': 'Return %s to attic.', 'FurnitureItemPanelTrash': 'Return %s to attic.'} MessagePickerTitle = 'You have too many phrases. In order to purchase\n"%s"\n you must choose one to remove:' MessagePickerCancel = lCancel MessageConfirmDelete = 'Are you sure you want to remove "%s" from your SpeedChat menu?' CatalogBuyText = 'Buy' CatalogRentText = 'Rent' CatalogGiftText = 'Gift' CatalogOnOrderText = 'On Order' CatalogPurchasedText = 'Already\nPurchased' CatalogCurrent = 'Current' CatalogGiftedText = 'Gifted\nTo You' CatalogPurchasedGiftText = 'Already\nOwned' CatalogMailboxFull = 'No Room' CatalogNotAGift = 'Not a Gift' CatalogNoFit = "Doesn't\nFit" CatalogMembersOnly = 'Members\nOnly!' CatalogSndOnText = 'Snd On' CatalogSndOffText = 'Snd Off' CatalogPurchasedMaxText = 'Already\nPurchased Max' CatalogVerifyPurchase = 'Purchase %(item)s for %(price)s Jellybeans?' CatalogVerifyPurchaseBeanSilverGold = 'Purchase %(item)s for %(price)s Jellybeans, %(silver)s silver emblems and %(gold)s gold emblems?' CatalogVerifyPurchaseBeanGold = 'Purchase %(item)s for %(price)s Jellybeans and %(gold)s gold emblems?' CatalogVerifyPurchaseBeanSilver = 'Purchase %(item)s for %(price)s Jellybeans and %(silver)s silver emblems?' CatalogVerifyPurchaseSilverGold = 'Purchase %(item)s for %(silver)s silver emblems and %(gold)s gold emblems?' CatalogVerifyPurchaseSilver = 'Purchase %(item)s for %(silver)s silver emblems?' CatalogVerifyPurchaseGold = 'Purchase %(item)s for %(gold)s gold emblems?' CatalogVerifyRent = 'Rent %(item)s for %(price)s Jellybeans?' CatalogVerifyGift = 'Purchase %(item)s for %(price)s Jellybeans as a gift for %(friend)s?' CatalogOnlyOnePurchase = 'You may only have one of these items at a time. If you purchase this one, it will replace %(old)s.\n\nAre you sure you want to purchase %(item)s for %(price)s Jellybeans?' CatalogExitButtonText = 'Hang Up' CatalogCurrentButtonText = 'To Current Items' CatalogPastButtonText = 'To Past Items' TutorialHQOfficerName = 'Harry' NPCToonNames = {20000: 'Tutorial Tom', 999: 'Toon Tailor', 1000: lToonHQ, 20001: Flippy, 2001: Flippy, 2002: 'Banker Bob', 2003: 'Professor Pete', 2004: 'Tammy', 2005: 'Librarian Larry', 2006: 'Clark', 2011: 'Clara', 2007: lHQOfficerM, 2008: lHQOfficerM, 2009: lHQOfficerF, 2010: lHQOfficerF, 2012: 'Freddy', 2018: 'Duff..err..TIP Man', 2013: 'Poppy', 2014: 'Peppy', 2015: 'Pappy', 2016: 'Pumpkin', 2017: 'Polly', 2018: 'Doctor Surlee', 2019: 'Doctor Dimm', 2020: 'Professor Prepostera', 2022: 'Alec Tinn', 2023: 'Slappy', 2024: 'Roger Dog', 2025: 'Kion', 2101: 'Dentist Daniel', 2102: 'Sheriff Sherry', 2103: 'Sneezy Kitty', 2104: lHQOfficerM, 2105: lHQOfficerM, 2106: lHQOfficerF, 2107: lHQOfficerF, 2108: 'Canary Coalmine', 2109: 'Babbles Blowhard', 2110: 'Bill Board', 2111: 'Dancing Diego', 2112: 'Dr. Tom', 2113: 'Rollo The Amazing', 2114: 'Roz Berry', 2115: 'Patty Papercut', 2116: 'Bruiser McDougal', 2117: 'Ma Putrid', 2118: 'Jesse Jester', 2119: 'Honey Haha', 2120: 'Professor Binky', 2121: 'Madam Chuckle', 2122: 'Harry Ape', 2123: 'Spamonia Biggles', 2124: 'T.P. Rolle', 2125: 'Lazy Hal', 2126: 'Professor Guffaw', 2127: 'Woody Nickel', 2128: 'Loony Louis', 2129: 'Frank Furter', 2130: 'Joy Buzzer', 2131: 'Feather Duster', 2132: 'Daffy Don', 2133: 'Dr. Euphoric', 2134: 'Silent Simone', 2135: 'Mary', 2136: 'Sal Snicker', 2137: 'Happy Heikyung', 2138: 'Muldoon', 2139: 'Dan Dribbles', 2140: 'Billy', 2201: 'Postmaster Pete', 2202: 'Shirley U. Jest', 2203: lHQOfficerM, 2204: lHQOfficerM, 2205: lHQOfficerF, 2206: lHQOfficerF, 2207: 'Will Wiseacre', 2208: 'Sticky Lou', 2209: 'Charlie Chortle', 2210: 'Tee Hee', 2211: 'Sally Spittake', 2212: 'Weird Warren', 2213: 'Lucy Tires', 2214: 'Sam Stain', 2215: 'Sid Seltzer', 2216: 'Nona Seeya', 2217: 'Sharky Jones', 2218: 'Fanny Pages', 2219: 'Chef Knucklehead', 2220: 'Rick Rockhead', 2221: 'Clovinia Cling', 2222: 'Shorty Fuse', 2223: 'Sasha Sidesplitter', 2224: 'Smokey Joe', 2225: 'Droopy', 2301: 'Dr. Pulyurleg', 2302: 'Professor Wiggle', 2303: 'Nurse Nancy', 2304: lHQOfficerM, 2305: lHQOfficerM, 2306: lHQOfficerF, 2307: lHQOfficerF, 2308: 'Nancy Gas', 2309: 'Big Bruce', 2311: 'Franz Neckvein', 2312: 'Dr. Sensitive', 2313: 'Lucy Shirtspot', 2314: 'Ned Slinger', 2315: 'Chewy Morsel', 2316: 'Cindy Sprinkles', 2318: 'Tony Maroni', 2319: 'Zippy', 2320: 'Crunchy Alfredo', 2321: 'Punchy', 2322: 'Jester Chester', 1001: 'Will', 1002: 'Bill', 1003: lHQOfficerM, 1004: lHQOfficerF, 1005: lHQOfficerM, 1006: lHQOfficerF, 1007: 'Longjohn Leroy', 1008: 'Furball', 1009: 'Barky', 1010: 'Purr', 1011: 'Bloop', 1012: 'Pickles', 1013: 'Patty', 1014: 'Byzantine', 1015: 'Frozen Bacon', 1101: 'Billy Budd', 1102: 'Captain Carl', 1103: 'Fishy Frank', 1104: 'Doctor Squall', 1105: 'Admiral Hook', 1106: 'Mrs. Starch', 1107: 'Cal Estenicks', 1108: lHQOfficerM, 1109: lHQOfficerF, 1110: lHQOfficerM, 1111: lHQOfficerF, 1112: 'Gary Glubglub', 1113: 'Lisa Luff', 1114: 'Charlie Chum', 1115: 'Sheila Squid, Atty', 1116: 'Barnacle Bessie', 1117: 'Captain Yucks', 1118: 'Choppy McDougal', 1121: 'Linda Landlubber', 1122: 'Salty Stan', 1123: 'Electra Eel', 1124: 'Flappy Docksplinter', 1125: 'Eileen Overboard', 1126: 'Barney', 1201: 'Barnacle Barbara', 1202: 'Art', 1203: 'Ahab', 1204: 'Rocky Shores', 1205: lHQOfficerM, 1206: lHQOfficerF, 1207: lHQOfficerM, 1208: lHQOfficerF, 1209: 'Professor Plank', 1210: 'Gang Wei', 1211: 'Wynn Bag', 1212: 'Toby Tonguestinger', 1213: 'Dante Dolphin', 1214: 'Gusty Kate', 1215: 'Dinah Down', 1216: 'Rod Reel', 1217: 'CC Weed', 1218: 'Pacific Tim', 1219: 'Brian Beachead', 1220: 'Carla Canal', 1221: 'Blisters McKee', 1222: 'Shep Ahoy', 1223: 'Sid Squid', 1224: 'Emily Eel', 1225: 'Bonzo Bilgepump', 1226: 'Heave Ho', 1227: 'Coral Reef', 1228: 'Reed', 1301: 'Alice', 1302: 'Melville', 1303: 'Claggart', 1304: 'Svetlana', 1305: lHQOfficerM, 1306: lHQOfficerF, 1307: lHQOfficerM, 1308: lHQOfficerF, 1309: 'Seafoam', 1310: 'Ted Tackle', 1311: 'Topsy Turvey', 1312: 'Ethan Keel', 1313: 'William Wake', 1314: 'Rusty Ralph', 1315: 'Doctor Drift', 1316: 'Wilma Wobble', 1317: 'Paula Pylon', 1318: 'Dinghy Dan', 1319: 'Davey Drydock', 1320: 'Ted Calm', 1321: 'Dinah Docker', 1322: 'Whoopie Cushion', 1323: 'Stinky Ned', 1324: 'Pearl Diver', 1325: 'Ned Setter', 1326: 'Felicia Chips', 1327: 'Cindy Splat', 1328: 'Fred Flounder', 1329: 'Shelly Seaweed', 1330: 'Porter Hole', 1331: 'Rudy Rudder', 1332: 'Shane', 3001: 'Betty Freezes', 3002: lHQOfficerM, 3003: lHQOfficerF, 3004: lHQOfficerM, 3005: lHQOfficerM, 3006: 'Lenny', 3007: 'Penny', 3008: 'Warren Bundles', 3009: 'Frizzy', 3010: 'Skip', 3011: 'Dip', 3012: 'Kipp', 3013: 'Pete', 3014: 'Penny', 3101: 'Mr. Cow', 3102: 'Auntie Freeze', 3103: 'Fred', 3104: 'Bonnie', 3105: 'Frosty Freddy', 3106: 'Gus Gooseburger', 3107: 'Patty Passport', 3108: 'Toboggan Ted', 3109: 'Kate', 3110: 'Chicken Boy', 3111: 'Snooty Sinjin', 3112: 'Lil Oldman', 3113: 'Hysterical Harry', 3114: 'Henry the Hazard', 3115: lHQOfficerM, 3116: lHQOfficerF, 3117: lHQOfficerM, 3118: lHQOfficerM, 3119: 'Creepy Carl', 3120: 'Mike Mittens', 3121: 'Joe Shockit', 3122: 'Lucy Luge', 3123: 'Frank Lloyd Ice', 3124: 'Lance Iceberg', 3125: 'Colonel Crunchmouth', 3126: 'Colestra Awl', 3127: 'Ifalla Yufalla', 3128: 'Sticky George', 3129: 'Baker Bridget', 3130: 'Sandy', 3131: 'Lazy Lorenzo', 3132: 'Ashy', 3133: 'Dr. Friezeframe', 3134: 'Lounge Lassard', 3135: 'Soggy Nell', 3136: 'Happy Sue', 3137: 'Mr. Freeze', 3138: 'Chef Bumblesoup', 3139: 'Granny Icestockings', 3140: 'Lucille', 3201: 'Aunt Arctic', 3202: 'Shakey', 3203: 'Walt', 3204: 'Dr. Ivanna Cee', 3205: 'Bumpy Noggin', 3206: 'Vidalia VaVoom', 3207: 'Dr. Mumbleface', 3208: 'Grumpy Phil', 3209: 'Giggles McGhee', 3210: 'Simian Sam', 3211: 'Fanny Freezes', 3212: 'Frosty Fred', 3213: lHQOfficerM, 3214: lHQOfficerF, 3215: lHQOfficerM, 3216: lHQOfficerM, 3217: 'Sweaty Pete', 3218: 'Blue Lou', 3219: 'Tom Tandemfrost', 3220: 'Mr. Sneeze', 3221: 'Nelly Snow', 3222: 'Mindy Windburn', 3223: 'Chappy', 3224: 'Freida Frostbite', 3225: 'Blake Ice', 3226: 'Santa Paws', 3227: 'Solar Ray', 3228: 'Wynne Chill', 3229: 'Hernia Belt', 3230: 'Balding Benjy', 3231: 'Choppy', 3232: 'Albert', 3301: 'Paisley Patches', 3302: 'Bjorn Bord', 3303: 'Dr. Peepers', 3304: 'Eddie the Yeti', 3305: 'Mack Ramay', 3306: 'Paula Behr', 3307: 'Fredrica', 3308: 'Donald Frump', 3309: 'Bootsy', 3310: 'Professor Flake', 3311: 'Connie Ferris', 3312: 'March Harry', 3313: lHQOfficerM, 3314: lHQOfficerF, 3315: lHQOfficerM, 3316: lHQOfficerF, 3317: 'Kissy Krissy', 3318: 'Johnny Cashmere', 3319: 'Sam Stetson', 3320: 'Fizzy Lizzy', 3321: 'Pickaxe Paul', 3322: 'Flue Lou', 3323: 'Dallas Borealis', 3324: 'Snaggletooth Stu', 3325: 'Groovy Garland', 3326: 'Blanche', 3327: 'Chuck Roast', 3328: 'Shady Sadie', 3329: 'Treading Ed', 4001: 'Molly Molloy', 4002: lHQOfficerM, 4003: lHQOfficerF, 4004: lHQOfficerF, 4005: lHQOfficerF, 4006: 'Doe', 4007: 'Ray', 4008: 'Tailor', 4009: 'Fanny', 4010: 'Chris', 4011: 'Neil', 4012: 'Westin Girl', 4013: 'Preston', 4014: 'Penelope', 4101: 'Tom', 4102: 'Fifi', 4103: 'Dr. Fret', 4104: lHQOfficerM, 4105: lHQOfficerF, 4106: lHQOfficerF, 4107: lHQOfficerF, 4108: 'Cleff', 4109: 'Carlos', 4110: 'Metra Gnome', 4111: 'Tom Hum', 4112: 'Fa', 4113: 'Madam Manners', 4114: 'Offkey Eric', 4115: 'Barbara Seville', 4116: 'Piccolo', 4117: 'Mandy Lynn', 4118: 'Attendant Abe', 4119: 'Moe Zart', 4120: 'Viola Padding', 4121: 'Gee Minor', 4122: 'Minty Bass', 4123: 'Lightning Ted', 4124: 'Riff Raff', 4125: 'Melody Wavers', 4126: 'Mel Canto', 4127: 'Happy Feet', 4128: 'Luciano Scoop', 4129: 'Tootie Twostep', 4130: 'Metal Mike', 4131: 'Abraham ArmoiFre', 4132: 'Lowdown Sally', 4133: 'Scott Poplin', 4134: 'Disco Dave', 4135: 'Sluggo Songbird', 4136: 'Patty Pause', 4137: 'Tony Deff', 4138: 'Cliff Cleff', 4139: 'Harmony Swell', 4140: 'Clumsy Ned', 4141: 'Jed', 4201: 'Tina', 4202: 'Barry', 4203: 'Lumber Jack', 4204: lHQOfficerM, 4205: lHQOfficerF, 4206: lHQOfficerF, 4207: lHQOfficerF, 4208: 'Hedy', 4209: 'Corny Canter', 4211: 'Carl Concerto', 4212: 'Detective Dirge', 4213: 'Fran Foley', 4214: 'Tina Toehooks', 4215: 'Tim Tailgater', 4216: 'Gummy Whistle', 4217: 'Handsome Anton', 4218: 'Wilma Wind', 4219: 'Sid Sonata', 4220: 'Curtis Finger', 4221: 'Moe Madrigal', 4222: 'John Doe', 4223: 'Penny Prompter', 4224: 'Jungle Jim', 4225: 'Holly Hiss', 4226: 'Thelma Throatreacher', 4227: 'Quiet Francesca', 4228: 'August Winds', 4229: 'June Loon', 4230: 'Julius Wheezer', 4231: 'Steffi Squeezebox', 4232: 'Hedly Hymn', 4233: 'Charlie Carp', 4234: 'Leed Guitar', 4235: 'Larry', 4301: 'Yuki', 4302: 'Anna', 4303: 'Leo', 4304: lHQOfficerM, 4305: lHQOfficerF, 4306: lHQOfficerF, 4307: lHQOfficerF, 4308: 'Tabitha', 4309: 'Marshall', 4310: 'Martha Mopp', 4311: 'Sea Shanty', 4312: 'Moe Saj', 4313: 'Dumb Dolph', 4314: 'Dana Dander', 4315: 'Karen Clockwork', 4316: 'Tim Tango', 4317: 'Stubby Toe', 4318: 'Bob Marlin', 4319: 'Rinky Dink', 4320: 'Cammy Coda', 4321: 'Luke Lute', 4322: 'Randy Rythm', 4323: 'Hanna Hogg', 4324: 'Ellie', 4325: 'Banker Bran', 4326: 'Fran Fret', 4327: 'Flim Flam', 4328: 'Wagner', 4329: 'Telly Prompter', 4330: 'Quentin', 4331: 'Mellow Costello', 4332: 'Ziggy', 4333: 'Harry', 4334: 'Fast Freddie', 4335: 'Walden', 5001: lHQOfficerM, 5002: lHQOfficerM, 5003: lHQOfficerF, 5004: lHQOfficerF, 5005: 'Peaches', 5006: 'Herb', 5007: 'Bonnie Blossom', 5008: 'Flora', 5009: 'Bo Tanny', 5010: 'Tom A. Dough', 5011: 'Doug Wood', 5012: 'Pierce', 5013: 'Peggy', 5101: 'Artie', 5102: 'Susan', 5103: 'Bud', 5104: 'Flutterby', 5105: 'Jack', 5106: 'Barber Bjorn', 5107: 'Postman Felipe', 5108: 'Innkeeper Janet', 5109: lHQOfficerM, 5110: lHQOfficerM, 5111: lHQOfficerF, 5112: lHQOfficerF, 5113: 'Dr. Spud', 5114: 'Wilt', 5115: 'Honey Dew', 5116: 'Vegetable Vern', 5117: 'Petal', 5118: 'Pop Corn', 5119: 'Barry Medly', 5120: 'Gopher', 5121: 'Paula Peapod', 5122: 'Leif Pyle', 5123: 'Diane Vine', 5124: 'Soggy Bottom', 5125: 'Sanjay Splash', 5126: 'Madam Mum', 5127: 'Polly Pollen', 5128: 'Shoshanna Sap', 5129: 'Sally', 5201: 'Jake', 5202: 'Cynthia', 5203: 'Lisa', 5204: 'Bert', 5205: 'Dan D. Lion', 5206: 'Vine Green', 5207: 'Sofie Squirt', 5208: 'Samantha Spade', 5209: lHQOfficerM, 5210: lHQOfficerM, 5211: lHQOfficerF, 5212: lHQOfficerF, 5213: 'Big Galoot', 5214: 'Itchie Bumps', 5215: 'Tammy Tuber', 5216: 'Stinky Jim', 5217: 'Greg Greenethumb', 5218: 'Rocky Raspberry', 5219: 'Lars Bicep', 5220: 'Lacy Underalls', 5221: 'Pink Flamingo', 5222: 'Whiny Wilma', 5223: 'Wet Will', 5224: 'Uncle Bumpkin', 5225: 'Pamela Puddle', 5226: 'Pete Moss', 5227: 'Begonia Biddlesmore', 5228: 'Digger Mudhands', 5229: 'Lily', 5301: lHQOfficerM, 5302: lHQOfficerM, 5303: lHQOfficerM, 5304: lHQOfficerM, 5305: 'Crystal', 5306: 'S. Cargo', 5307: 'Fun Gus', 5308: 'Naggy Nell', 5309: 'Ro Maine', 5310: 'Timothy', 5311: 'Judge McIntosh', 5312: 'Eugene', 5313: "Coach Zucchini", 5314: 'Aunt Hill', 5315: 'Uncle Mud', 5316: 'Uncle Spud', 5317: 'Detective Lima', 5318: 'Caesar', 5319: 'Rose', 5320: 'April', 5321: 'Professor Ivy', 5322: 'Rose', 8001: 'Graham Pree', 8002: 'Ivona Race', 8003: 'Anita Winn', 8004: 'Phil Errup', 9001: "Snoozin' Susan", 9002: 'Sleeping Tom', 9003: 'Drowsy Dennis', 9004: lHQOfficerF, 9005: lHQOfficerF, 9006: lHQOfficerM, 9007: lHQOfficerM, 9008: 'Jill', 9009: 'Phil', 9010: 'Worn Out Waylon', 9011: 'Freud', 9012: 'Sarah Snuze', 9013: 'Kat Knap', 9014: 'R. V. Winkle', 9015: 'Pebbles', 9016: 'Pearl', 9101: 'Ed', 9102: 'Big Mama', 9103: 'P.J.', 9104: 'Sweet Slumber', 9105: 'Professor Yawn', 9106: 'Max', 9107: 'Snuggles', 9108: 'Winky Wilbur', 9109: 'Dreamy Daphne', 9110: 'Kathy Nip', 9111: 'Powers Erge', 9112: 'Lullaby Lou', 9113: 'Jacques Clock', 9114: 'Smudgy Mascara', 9115: 'Babyface MacDougal', 9116: 'Dances with Sheep', 9117: 'Afta Hours', 9118: 'Starry Knight', 9119: 'Rocco', 9120: 'Sarah Slumber', 9121: 'Serena Shortsheeter', 9122: 'Puffy Ayes', 9123: 'Teddy Blair', 9124: 'Nina Nitelight', 9125: 'Dr. Bleary', 9126: 'Wyda Wake', 9127: 'Tabby Tucker', 9128: "Hardy O'Toole", 9129: 'Bertha Bedhog', 9130: 'Charlie Chamberpot', 9131: 'Susan Siesta', 9132: lHQOfficerF, 9133: lHQOfficerF, 9134: lHQOfficerF, 9135: lHQOfficerF, 9136: 'Taylor', 9201: 'Bernie Sandals', 9202: 'Orville', 9203: 'Nat', 9204: 'Claire de Loon', 9205: 'Zen Glen', 9206: 'Skinny Ginny', 9207: 'Jane Drain', 9208: 'Drowsy Dave', 9209: 'Dr. Floss', 9210: 'Master Mike', 9211: 'Dawn', 9212: 'Moonbeam', 9213: 'Rooster Rick', 9214: 'Dr. Blinky', 9215: 'Rip', 9216: 'Cat', 9217: 'Lawful Linda', 9218: 'Waltzing Matilda', 9219: 'The Countess', 9220: 'Grumpy Gordon', 9221: 'Zari', 9222: 'Cowboy George', 9223: 'Mark the Lark', 9224: 'Sandy Sandman', 9225: 'Fidgety Bridget', 9226: 'William Teller', 9227: 'Bed Head Ted', 9228: 'Whispering Willow', 9229: 'Rose Petals', 9230: 'Tex', 9231: 'Harry Hammock', 9232: 'Honey Moon', 9233: lHQOfficerM, 9234: lHQOfficerM, 9235: lHQOfficerM, 9236: lHQOfficerM, 9237: 'Jung', 9301: 'Phil Bettur', 9302: 'Emma Phatic', 9303: 'GiggleMesh', 9304: 'Anne Ville', 9305: 'Bud Erfingerz', 9306: 'J.S. Bark', 9307: 'Bea Sharpe', 9308: 'Otto Toon', 9309: 'Al Capella', 9310: 'Des Traction', 9311: 'Dee Version', 9312: 'Bo Nanapeel', 7001: 'N. Prisoned', 7002: 'R.E. Leaseme', 7003: 'Lemmy Owte', 7004: 'T. Rapped', 7005: 'Little Helphere', 7006: 'Gimmy Ahand', 7007: 'Dewin Tymme', 7008: 'Ima Cagedtoon', 7009: 'Jimmy Thelock', 91913: 'unused', # 9/19/13 = Closing of Toontown, just a random number to start with so we don't take up other IDs 91914: 'unused', 91915: 'unused', 91916: 'unused'} zone2TitleDict = {2513: ('Toon Hall', ''), 2514: ('Toontown Bank', ''), 2516: ('Toontown School House', ''), 2518: ('Toontown Library', ''), 2519: ('Gag Shop', ''), 2520: (lToonHQ, ''), 2521: ('Clothing Shop', ''), 2522: ('Pet Shop', ''), 2601: ('All Smiles Tooth Repair', ''), 2602: ('', ''), 2603: ('One-Liner Miners', ''), 2604: ('Hogwash & Dry', ''), 2605: ('Toontown Sign Factory', ''), 2606: ('', ''), 2607: ('Jumping Beans', ''), 2610: ('Dr. Tom Foolery', ''), 2611: ('', ''), 2616: ("Weird Beard's Disguise Shop", ''), 2617: ('Silly Stunts', ''), 2618: ('All That Razz', ''), 2621: ('Paper Airplanes', ''), 2624: ('Happy Hooligans', ''), 2625: ('House of Bad Pies', ''), 2626: ("Jesse's Joke Repair", ''), 2629: ("The Laughin' Place", ''), 2632: ('Clown Class', ''), 2633: ('Tee-Hee Tea Shop', ''), 2638: ('Toontown Playhouse', ''), 2639: ('Monkey Tricks', ''), 2643: ('Canned Bottles', ''), 2644: ('Impractical Jokes', ''), 2649: ('All Fun and Games Shop', ''), 2652: ('', ''), 2653: ('', ''), 2654: ('Laughing Lessons', ''), 2655: ('Funny Money Savings & Loan', ''), 2656: ('Used Clown Cars', ''), 2657: ("Frank's Pranks", ''), 2659: ('Joy Buzzers to the World', ''), 2660: ('Tickle Machines', ''), 2661: ('Daffy Taffy', ''), 2662: ('Dr. I.M. Euphoric', ''), 2663: ('Toontown Cinerama', ''), 2664: ('The Merry Mimes', ''), 2665: ("Mary's Go Around Travel Company", ''), 2666: ('Laughing Gas Station', ''), 2667: ('Happy Times', ''), 2669: ("Muldoon's Maroon Balloons", ''), 2670: ('Soup Forks', ''), 2671: ('', ''), 2701: ('', ''), 2704: ('Movie Multiplex', ''), 2705: ("Wiseacre's Noisemakers", ''), 2708: ('Blue Glue', ''), 2711: ('Toontown Post Office', ''), 2712: ('Chortle Cafe', ''), 2713: ('Laughter Hours Cafe', ''), 2714: ('Kooky CinePlex', ''), 2716: ('Soup and Crack Ups', ''), 2717: ('Bottled Cans', ''), 2720: ('Crack Up Auto Repair', ''), 2725: ('', ''), 2727: ('Seltzer Bottles and Cans', ''), 2728: ('Vanishing Cream', ''), 2729: ('14 Karat Goldfish', ''), 2730: ('News for the Amused', ''), 2731: ('', ''), 2732: ('Spaghetti and Goofballs', ''), 2733: ('Cast Iron Kites', ''), 2734: ('Suction Cups and Saucers', ''), 2735: ('The Kaboomery', ''), 2739: ("Sidesplitter's Mending", ''), 2740: ('Used Firecrackers', ''), 2741: ('', ''), 2742: ('', ''), 2743: ('Ragtime Dry Cleaners', ''), 2744: ('', ''), 2747: ('Visible Ink', ''), 2748: ('Jest for Laughs', ''), 2801: ('Sofa Whoopee Cushions', ''), 2802: ('Inflatable Wrecking Balls', ''), 2803: ('The Karnival Kid', ''), 2804: ('Dr. Pulyurleg, Chiropractor', ''), 2805: ('', ''), 2809: ('The Punch Line Gym', ''), 2814: ('Toontown Theatre', ''), 2818: ('The Flying Pie', ''), 2821: ('', ''), 2822: ('Rubber Chicken Sandwiches', ''), 2823: ('Sundae Funnies Ice Cream', ''), 2824: ('Punchline Movie Palace', ''), 2829: ('Phony Baloney', ''), 2830: ("Zippy's Zingers", ''), 2831: ("Professor Wiggle's House of Giggles", ''), 2832: ('', ''), 2833: ('', ''), 2834: ('Funny Bone Emergency Room', ''), 2836: ('', ''), 2837: ('Hardy Harr Seminars', ''), 2839: ('Barely Palatable Pasta', ''), 2841: ('', ''), 1506: ('Gag Shop', ''), 1507: ('Toon Headquarters', ''), 1508: ('Clothing Shop', ''), 1510: ('', ''), 1602: ('Used Life Preservers', ''), 1604: ('Wet Suit Dry Cleaners', ''), 1606: ("Hook's Clock Repair", ''), 1608: ("Luff 'N Stuff", ''), 1609: ('Every Little Bait', ''), 1612: ('Dime & Quarterdeck Bank', ''), 1613: ('Squid Pro Quo, Attorneys at Law', ''), 1614: ('Trim the Nail Boutique', ''), 1615: ("Yacht's All, Folks!", ''), 1616: ("Blackbeard's Beauty Parlor", ''), 1617: ('Out to See Optics', ''), 1619: ('Disembark! Tree Surgeons', ''), 1620: ('From Fore to Aft', ''), 1621: ('Poop Deck Gym', ''), 1622: ('Bait and Switches Electrical Shop', ''), 1624: ('Soles Repaired While U Wait', ''), 1626: ('Salmon Chanted Evening Formal Wear', ''), 1627: ("Billy Budd's Big Bargain Binnacle Barn", ''), 1628: ('Piano Tuna', ''), 1629: ('', ''), 1701: ('Buoys and Gulls Nursery School', ''), 1703: ('Wok the Plank Chinese Food', ''), 1705: ('Sails for Sale', ''), 1706: ('Peanut Butter and Jellyfish', ''), 1707: ('Gifts With a Porpoise', ''), 1709: ('Windjammers and Jellies', ''), 1710: ('Barnacle Bargains', ''), 1711: ('Deep Sea Diner', ''), 1712: ('Able-Bodied Gym', ''), 1713: ("Art's Smart Chart Mart", ''), 1714: ("Reel 'Em Inn", ''), 1716: ('Mermaid Swimwear', ''), 1717: ('Be More Pacific Ocean Notions', ''), 1718: ('Run Aground Taxi Service', ''), 1719: ("Duck's Back Water Company", ''), 1720: ('The Reel Deal', ''), 1721: ('All For Nautical', ''), 1723: ("Squid's Seaweed", ''), 1724: ("That's a Moray!", ''), 1725: ("Ahab's Prefab Sea Crab Center", ''), 1726: ('Root Beer Afloats', ''), 1727: ('This Oar That', ''), 1728: ('Good Luck Horseshoe Crabs', ''), 1729: ('', ''), 1802: ('Nautical But Nice', ''), 1804: ('Mussel Beach Gymnasium', ''), 1805: ('Tackle Box Lunches', ''), 1806: ('Cap Size Hat Store', ''), 1807: ('Keel Deals', ''), 1808: ('Knots So Fast', ''), 1809: ('Rusty Buckets', ''), 1810: ('Anchor Management', ''), 1811: ("What's Canoe With You?", ''), 1813: ('Pier Pressure Plumbing', ''), 1814: ('The Yo Ho Stop and Go', ''), 1815: ("What's Up, Dock?", ''), 1818: ('Seven Seas Cafe', ''), 1819: ("Docker's Diner", ''), 1820: ('Hook, Line, and Sinker Prank Shop', ''), 1821: ("King Neptoon's Cannery", ''), 1823: ('The Clam Bake Diner', ''), 1824: ('Dog Paddles', ''), 1825: ('Wholly Mackerel! Fish Market', ''), 1826: ("Claggart's Clever Clovis Closet", ''), 1828: ("Alice's Ballast Palace", ''), 1829: ('Seagull Statue Store', ''), 1830: ('Lost and Flounder', ''), 1831: ('Kelp Around the House', ''), 1832: ("Melville's Massive Mizzenmast Mart", ''), 1833: ('This Transom Man Custom Tailored Suits', ''), 1834: ('Rudderly Ridiculous!', ''), 1835: ('', ''), 4503: ('Gag Shop', ''), 4504: ('Toon Headquarters', ''), 4506: ('Clothing Shop', ''), 4508: ('', ''), 4603: ("Tom-Tom's Drums", ''), 4604: ('In Four-Four Time', ''), 4605: ("Fifi's Fiddles", ''), 4606: ('Casa De Castanets', ''), 4607: ('Catchy Toon Apparel', ''), 4609: ('Do, Rae, Me Piano Keys', ''), 4610: ('Please Refrain', ''), 4611: ('Tuning Forks and Spoons', ''), 4612: ("Dr. Fret's Dentistry", ''), 4614: ('Shave and a Haircut for a Song', ''), 4615: ("Piccolo's Pizza", ''), 4617: ('Happy Mandolins', ''), 4618: ('Rests Rooms', ''), 4619: ('More Scores', ''), 4622: ('Chin Rest Pillows', ''), 4623: ('Flats Sharpened', ''), 4625: ('Tuba Toothpaste', ''), 4626: ('Notations', ''), 4628: ('Accidental Insurance', ''), 4629: ("Riff's Paper Plates", ''), 4630: ('Music Is Our Forte', ''), 4631: ('Canto Help You', ''), 4632: ('Dance Around the Clock Shop', ''), 4635: ('Tenor Times', ''), 4637: ('For Good Measure', ''), 4638: ('Hard Rock Shop', ''), 4639: ('Four Score Antiques', ''), 4641: ('Blues News', ''), 4642: ('Ragtime Dry Cleaners', ''), 4645: ('Club 88', ''), 4646: ('', ''), 4648: ('Carry a Toon Movers', ''), 4649: ('', ''), 4652: ('Full Stop Shop', ''), 4653: ('', ''), 4654: ('Pitch Perfect Roofing', ''), 4655: ("The Treble Chef's Cooking School", ''), 4656: ('', ''), 4657: ('Barbershop Quartet', ''), 4658: ('Plummeting Pianos', ''), 4659: ('', ''), 4701: ('The Schmaltzy Waltz School of Dance', ''), 4702: ('Timbre! Equipment for the Singing Lumberjack', ''), 4703: ('I Can Handel It!', ''), 4704: ("Tina's Concertina Concerts", ''), 4705: ('Zither Here Nor There', ''), 4707: ("Doppler's Sound Effects Studio", ''), 4709: ('On Ballet! Climbing Supplies', ''), 4710: ('Hurry Up, Slow Polka! School of Driving', ''), 4712: ('C-Flat Tire Repair', ''), 4713: ('B-Sharp Fine Menswear', ''), 4716: ('Four-Part Harmonicas', ''), 4717: ('Sonata Your Fault! Discount Auto Insurance', ''), 4718: ('Chopin Blocks and Other Kitchen Supplies', ''), 4719: ('Madrigal Motor Homes', ''), 4720: ('Name That Toon', ''), 4722: ('Overture Understudies', ''), 4723: ('Haydn Go Seek Playground Supplies', ''), 4724: ('White Noise for Girls and Boys', ''), 4725: ('The Baritone Barber', ''), 4727: ('Vocal Chords Braided', ''), 4728: ("Sing Solo We Can't Hear You", ''), 4729: ('Double Reed Bookstore', ''), 4730: ('Lousy Lyrics', ''), 4731: ('Toon Tunes', ''), 4732: ('Etude Brute? Theatre Company', ''), 4733: ('', ''), 4734: ('', ''), 4735: ('Accordions, If You Want In, Just Bellow!', ''), 4736: ('Her and Hymn Wedding Planners', ''), 4737: ('Harp Tarps', ''), 4738: ('Canticle Your Fancy Gift Shop', ''), 4739: ('', ''), 4801: ("Marshall's Stacks", ''), 4803: ('What a Mezzo! Maid Service', ''), 4804: ('Mixolydian Scales', ''), 4807: ('Relax the Bach', ''), 4809: ("I Can't Understanza!", ''), 4812: ('', ''), 4817: ('The Ternary Pet Shop', ''), 4819: ("Yuki's Ukeleles", ''), 4820: ('', ''), 4821: ("Anna's Cruises", ''), 4827: ('Common Time Watches', ''), 4828: ("Schumann's Shoes for Men", ''), 4829: ("Pachelbel's Canonballs", ''), 4835: ('Ursatz for Kool Katz', ''), 4836: ('Reggae Regalia', ''), 4838: ('Kazoology School of Music', ''), 4840: ('Coda Pop Musical Beverages', ''), 4841: ('Lyre, Lyre, Pants on Fire!', ''), 4842: ('The Syncopation Corporation', ''), 4843: ('', ''), 4844: ('Con Moto Cycles', ''), 4845: ("Ellie's Elegant Elegies", ''), 4848: ('Lotsa Lute Savings & Loan', ''), 4849: ('', ''), 4850: ('The Borrowed Chord Pawn Shop', ''), 4852: ('Flowery Flute Fleeces', ''), 4853: ("Leo's Fenders", ''), 4854: ("Wagner's Vocational Violin Videos", ''), 4855: ('The Teli-Caster Network', ''), 4856: ('', ''), 4862: ("Quentin's Quintessen\x03tial Quadrilles", ''), 4867: ("Mr. Costello's Yellow Cellos", ''), 4868: ('', ''), 4870: ("Ziggy's Zoo of Zigeuner\x03musik", ''), 4871: ("Harry's House of Harmonious Humbuckers", ''), 4872: ("Fast Freddie's Fretless Fingerboards", ''), 4873: ('', ''), 5501: ('Gag Shop', ''), 5502: (lToonHQ, ''), 5503: ('Clothing Shop', ''), 5505: ('', ''), 5601: ('Eye of the Potato Optometry', ''), 5602: ("Artie Choke's Neckties", ''), 5603: ('Lettuce Alone', ''), 5604: ('Cantaloupe Bridal Shop', ''), 5605: ('Vege-tables and Chairs', ''), 5606: ('Petals', ''), 5607: ('Compost Office', ''), 5608: ('Mom and Pop Corn', ''), 5609: ('Berried Treasure', ''), 5610: ("Black-eyed Susan's Boxing Lessons", ''), 5611: ("Gopher's Gags", ''), 5613: ('Crop Top Barbers', ''), 5615: ("Bud's Bird Seed", ''), 5616: ('Dew Drop Inn', ''), 5617: ("Flutterby's Butterflies", ''), 5618: ("Peas and Q's", ''), 5619: ("Jack's Beanstalks", ''), 5620: ('Rake It Inn', ''), 5621: ('Grape Expectations', ''), 5622: ('Petal Pusher Bicycles', ''), 5623: ('Bubble Bird Baths', ''), 5624: ("Mum's the Word", ''), 5625: ('Leaf It Bees', ''), 5626: ('Pine Needle Crafts', ''), 5627: ('', ''), 5701: ('From Start to Spinach', ''), 5702: ("Jake's Rakes", ''), 5703: ("Photo Cynthia's Camera Shop", ''), 5704: ('Lisa Lemon Used Cars', ''), 5705: ('Poison Oak Furniture', ''), 5706: ('14 Carrot Jewelers', ''), 5707: ('Musical Fruit', ''), 5708: ("We'd Be Gone Travel Agency", ''), 5709: ('Astroturf Mowers', ''), 5710: ('Tuft Guy Gym', ''), 5711: ('Garden Hosiery', ''), 5712: ('Silly Statues', ''), 5713: ('Trowels and Tribulations', ''), 5714: ('Spring Rain Seltzer Bottles', ''), 5715: ('Hayseed News', ''), 5716: ('Take It or Leaf It Pawn Shop', ''), 5717: ('The Squirting Flower', ''), 5718: ('The Dandy Lion Exotic Pets', ''), 5719: ('Trellis the Truth! Private Investi\x03gators', ''), 5720: ('Vine and Dandy Menswear', ''), 5721: ('Root 66 Diner', ''), 5725: ('Barley, Hops, and Malt Shop', ''), 5726: ("Bert's Dirt", ''), 5727: ('Gopher Broke Savings & Loan', ''), 5728: ('', ''), 5802: (lToonHQ, ''), 5804: ('Just Vase It', ''), 5805: ('Snail Mail', ''), 5809: ('Fungi Clown School', ''), 5810: ('Honeydew This', ''), 5811: ('Lettuce Inn', ''), 5815: ('Grass Roots', ''), 5817: ('Apples and Oranges', ''), 5819: ('Green Bean Jeans', ''), 5821: ('Squash and Stretch Gym', ''), 5826: ('Ant Farming Supplies', ''), 5827: ('Dirt. Cheap.', ''), 5828: ('Couch Potato Furniture', ''), 5830: ('Spill the Beans', ''), 5833: ('The Salad Bar', ''), 5835: ('Flower Bed and Breakfast', ''), 5836: ("April's Showers and Tubs", ''), 5837: ('School of Vine Arts', ''), 9501: ('Lullaby Library', ''), 9503: ('The Snooze Bar', ''), 9504: ('Gag Shop', ''), 9505: (lToonHQ, ''), 9506: ('Clothing Shop', ''), 9508: ('', ''), 9601: ('Snuggle Inn', ''), 9602: ('Forty Winks for the Price of Twenty', ''), 9604: ("Ed's Red Bed Spreads", ''), 9605: ('Cloud Nine Design', ''), 9607: ("Big Mama's Bahama Pajamas", ''), 9608: ('Cat Nip for Cat Naps', ''), 9609: ('Deep Sleep for Cheap', ''), 9613: ('Clock Cleaners', ''), 9616: ('Lights Out Electric Co.', ''), 9617: ('Crib Notes - Music to Sleep By', ''), 9619: ('Relax to the Max', ''), 9620: ("PJ's Taxi Service", ''), 9622: ('Sleepy Time Pieces', ''), 9625: ('Curl Up Beauty Parlor', ''), 9626: ('Bed Time Stories', ''), 9627: ('The Sleepy Teepee', ''), 9628: ('Call It a Day Calendars', ''), 9629: ('Silver Lining Jewelers', ''), 9630: ('Rock to Sleep Quarry', ''), 9631: ('Down Time Watch Repair', ''), 9633: ('The Dreamland Screening Room', ''), 9634: ('Mind Over Mattress', ''), 9636: ('Insomniac Insurance', ''), 9639: ('House of Hibernation', ''), 9640: ('Nightstand Furniture Company', ''), 9642: ('Sawing Wood Slumber Lumber', ''), 9643: ('Shut-Eye Optometry', ''), 9644: ('Pillow Fights Nightly', ''), 9645: ('The All Tucked Inn', ''), 9647: ('Make Your Bed! Hardware Store', ''), 9649: ('Snore or Less', ''), 9650: ('Crack of Dawn Repairs', ''), 9651: ('For Richer or Snorer', ''), 9652: ('', ''), 9703: ('Fly By Night Travel Agency', ''), 9704: ('Night Owl Pet Shop', ''), 9705: ('Asleep At The Wheel Car Repair', ''), 9706: ('Tooth Fairy Dentistry', ''), 9707: ("Dawn's Yawn & Garden Center", ''), 9708: ('Bed Of Roses Florist', ''), 9709: ('Pipe Dream Plumbers', ''), 9710: ('REM Optometry', ''), 9711: ('Wake-Up Call Phone Company', ''), 9712: ("Counting Sheep - So You Don't Have To!", ''), 9713: ('Wynken, Blynken & Nod, Attorneys at Law', ''), 9714: ('Dreamboat Marine Supply', ''), 9715: ('First Security Blanket Bank', ''), 9716: ('Wet Blanket Party Planners', ''), 9717: ("Baker's Dozin' Doughnuts", ''), 9718: ("Sandman's Sandwiches", ''), 9719: ('Armadillo Pillow Company', ''), 9720: ('Talking In Your Sleep Voice Training', ''), 9721: ('Snug As A Bug Rug Dealer', ''), 9722: ('Dream On Talent Agency', ''), 9725: ("Cat's Pajamas", ''), 9727: ('You Snooze, You Lose', ''), 9736: ('Dream Jobs Employment Agency', ''), 9737: ("Waltzing Matilda's Dance School", ''), 9738: ('House of Zzzzzs', ''), 9740: ('Hit The Sack Fencing School', ''), 9741: ("Don't Let The Bed Bugs Bite Exterminators", ''), 9744: ("Rip Van Winkle's Wrinkle Cream", ''), 9752: ('Midnight Oil & Gas Company', ''), 9753: ("Moonbeam's Ice Creams", ''), 9754: ('Sleepless in the Saddle All Night Pony Rides', ''), 9755: ('Bedknobs & Broomsticks Movie House', ''), 9756: ('', ''), 9759: ('Sleeping Beauty Parlor', ''), 3507: ('Gag Shop', ''), 3508: (lToonHQ, ''), 3509: ('Clothing Shop', ''), 3511: ('', ''), 3601: ('Northern Lights Electric Company', ''), 3602: ("Nor'easter Bonnets", ''), 3605: ('', ''), 3607: ('The Blizzard Wizard', ''), 3608: ('Nothing to Luge', ''), 3610: ("Mike's Massive Mukluk Mart", ''), 3611: ("Mr. Cow's Snow Plows", ''), 3612: ('Igloo Design', ''), 3613: ('Ice Cycle Bikes', ''), 3614: ('Snowflakes Cereal Company', ''), 3615: ('Fried Baked Alaskas', ''), 3617: ('Cold Air Balloon Rides', ''), 3618: ('Snow Big Deal! Crisis Management', ''), 3620: ('Skiing Clinic', ''), 3621: ('The Melting Ice Cream Bar', ''), 3622: ('', ''), 3623: ('The Mostly Toasty Bread Company', ''), 3624: ('Subzero Sandwich Shop', ''), 3625: ("Auntie Freeze's Radiator Supply", ''), 3627: ('St. Bernard Kennel Club', ''), 3629: ('Pea Soup Cafe', ''), 3630: ('Icy London, Icy France Travel Agency', ''), 3634: ('Easy Chair Lifts', ''), 3635: ('Used Firewood', ''), 3636: ('Affordable Goosebumps', ''), 3637: ("Kate's Skates", ''), 3638: ('Toboggan or Not Toboggan', ''), 3641: ("Fred's Red Sled Beds", ''), 3642: ('Eye of the Storm Optics', ''), 3643: ('Snowball Hall', ''), 3644: ('Melted Ice Cubes', ''), 3647: ('The Sanguine Penguin Tuxedo Shop', ''), 3648: ('Instant Ice', ''), 3649: ('Hambrrrgers', ''), 3650: ('Antarctic Antiques', ''), 3651: ("Frosty Freddy's Frozen Frankfurters", ''), 3653: ('Ice House Jewelry', ''), 3654: ('', ''), 3702: ('Winter Storage', ''), 3703: ('', ''), 3705: ('Icicles Built for Two', ''), 3706: ("Shiverin' Shakes Malt Shop", ''), 3707: ('Snowplace Like Home', ''), 3708: ("Pluto's Place", ''), 3710: ('Dropping Degrees Diner', ''), 3711: ('', ''), 3712: ('Go With the Floe', ''), 3713: ('Chattering Teeth, Subzero Dentist', ''), 3715: ("Aunt Arctic's Soup Shop", ''), 3716: ('Road Salt and Pepper', ''), 3717: ('Juneau What I Mean?', ''), 3718: ('Designer Inner Tubes', ''), 3719: ('Ice Cube on a Stick', ''), 3721: ("Noggin's Toboggan Bargains", ''), 3722: ('Snow Bunny Ski Shop', ''), 3723: ("Shakey's Snow Globes", ''), 3724: ('The Chattering Chronicle', ''), 3725: ('You Sleigh Me', ''), 3726: ('Solar Powered Blankets', ''), 3728: ('Lowbrow Snowplows', ''), 3729: ('', ''), 3730: ('Snowmen Bought & Sold', ''), 3731: ('Portable Fireplaces', ''), 3732: ('The Frozen Nose', ''), 3734: ('Icy Fine, Do You? Optometry', ''), 3735: ('Polar Ice Caps', ''), 3736: ('Diced Ice at a Nice Price', ''), 3737: ('Downhill Diner', ''), 3738: ("Heat-Get It While It's Hot", ''), 3739: ('', ''), 3801: ('Toon HQ', ''), 3806: ('Alpine Chow Line', ''), 3807: ('Used Groundhog Shadows', ''), 3808: ('The Sweater Lodge', ''), 3809: ('Ice Saw It Too', ''), 3810: ('A Better Built Quilt', ''), 3811: ('Your Snow Angel', ''), 3812: ('Mittens for Kittens', ''), 3813: ("Snowshoes You Can't Refuse", ''), 3814: ('Malt in Your Mouth Soda Fountain', ''), 3815: ('The Toupee Chalet', ''), 3816: ('Just So Mistletoe', ''), 3817: ('Winter Wonderland Walking Club', ''), 3818: ('The Shovel Hovel', ''), 3819: ('Clean Sweep Chimney Service', ''), 3820: ('Snow Whitening', ''), 3821: ('Hibernation Vacations', ''), 3823: ('Precipitation Foundation', ''), 3824: ('Open Fire Chestnut Roasting', ''), 3825: ('Cool Cat Hats', ''), 3826: ('Oh My Galoshes!', ''), 3827: ('Choral Wreaths', ''), 3828: ("Snowman's Land", ''), 3829: ('Pinecone Zone', ''), 3830: ('Wait and See Goggle Defogging', '')} ClosetTimeoutMessage = 'Sorry, you ran out\n of time.' ClosetNotOwnerMessage = "This isn't your closet, but you may try on the clothes." ClosetPopupOK = lOK ClosetPopupCancel = lCancel ClosetDiscardButton = 'Remove' ClosetAreYouSureMessage = 'You have deleted some clothes. Do you really want to delete them?' ClosetYes = lYes ClosetNo = lNo ClosetVerifyDelete = 'Really delete %s?' ClosetShirt = 'this shirt' ClosetShorts = 'these shorts' ClosetSkirt = 'this skirt' ClosetDeleteShirt = 'Delete\nshirt' ClosetDeleteShorts = 'Delete\nshorts' ClosetDeleteSkirt = 'Delete\nskirt' TrunkNotOwnerMessage = "This isn't your trunk, but you may try on the accessories." TrunkNotPaidMessage = 'Only Paid Members can wear accessories, but you may try them on.' TrunkAreYouSureMessage = 'You have deleted some accessories. Do you really want to delete them?' TrunkHat = 'this hat' TrunkGlasses = 'these glasses' TrunkBackpack = 'this backpack' TrunkShoes = 'these shoes' TrunkDeleteHat = 'Delete\nhat' TrunkDeleteGlasses = 'Delete\nglasses' TrunkDeleteBackpack = 'Delete\nbackpack' TrunkDeleteShoes = 'Delete\nshoes' EstateOwnerLeftMessage = "Sorry, the owner of this estate left. You'll be sent to the playground in %s seconds" EstatePopupOK = lOK EstateTeleportFailed = "Couldn't go home. Try again!" EstateTeleportFailedNotFriends = "Sorry, %s is in a toon's estate that you are not friends with." EstateTargetGameStart = 'The Toon-up Target game has started!' EstateTargetGameInst = "The more you hit the red target, the more you'll get Tooned up." EstateTargetGameEnd = 'The Toon-up Target game is now over...' AvatarsHouse = '%s\n House' BankGuiCancel = lCancel BankGuiOk = lOK DistributedBankNoOwner = 'Sorry, this is not your bank.' DistributedBankNotOwner = 'Sorry, this is not your bank.' FishGuiCancel = lCancel FishGuiOk = 'Sell All' FishTankValue = 'Hi, %(name)s! You have %(num)s fish in your bucket worth a total of %(value)s Jellybeans. Do you want to sell them all?' FlowerGuiCancel = lCancel FlowerGuiOk = 'Sell All' FlowerBasketValue = '%(name)s, you have %(num)s flowers in your basket worth a total of %(value)s Jellybeans. Do you want to sell them all?' def GetPossesive(name, place): if name[-1:] == 's': possesive = name + "'" else: possesive = name + "'s" return possesive PetTrait2descriptions = {'hungerThreshold': ('Always Hungry', 'Often Hungry', 'Sometimes Hungry', 'Rarely Hungry'), 'boredomThreshold': ('Always Bored', 'Often Bored', 'Sometimes Bored', 'Rarely Bored'), 'angerThreshold': ('Always Grumpy', 'Often Grumpy', 'Sometimes Grumpy', 'Rarely Grumpy'), 'forgetfulness': ('Always Forgets', 'Often Forgets', 'Sometimes Forgets', 'Rarely Forgets'), 'excitementThreshold': ('Very Calm', 'Pretty Calm', 'Pretty Excitable', 'Very Excitable'), 'sadnessThreshold': ('Always Sad', 'Often Sad', 'Sometimes Sad', 'Rarely Sad'), 'restlessnessThreshold': ('Always Restless', 'Often Restless', 'Sometimes Restless', 'Rarely Restless'), 'playfulnessThreshold': ('Rarely Playful', 'Sometimes Playful', 'Often Playful', 'Always Playful'), 'lonelinessThreshold': ('Always Lonely', 'Often Lonely', 'Sometimes Lonely', 'Rarely Lonely'), 'fatigueThreshold': ('Always Tired', 'Often Tired', 'Sometimes Tired', 'Rarely Tired'), 'confusionThreshold': ('Always Confused', 'Often Confused', 'Sometimes Confused', 'Rarely Confused'), 'surpriseThreshold': ('Always Surprised', 'Often Surprised', 'Sometimes Surprised', 'Rarely Surprised'), 'affectionThreshold': ('Rarely Affectionate', 'Sometimes Affectionate', 'Often Affectionate', 'Always Affectionate')} # Regular fireworks stuff FireworksInstructions = lToonHQ + ': Hit the "Page Up" key to see better.' startFireworksResponse = "Usage: startFireworksShow ['num']\n 'num' = %s - New Years\n %s - Party Summer \n %s - 4th of July" FireworksJuly4Beginning = lToonHQ + ': Welcome to summer fireworks! Enjoy the show!' FireworksJuly4Ending = lToonHQ + ': Hope you enjoyed the show! Have a great summer!' FireworksNewYearsEveBeginning = lToonHQ + ': Happy New Year! Enjoy the fireworks show!' FireworksNewYearsEveEnding = lToonHQ + ': Hope you enjoyed the show! Have a Toontastic New Year!' FireworksComboBeginning = lToonHQ + ': Enjoy lots of Laffs with Toon fireworks!' FireworksComboEnding = lToonHQ + ': Thank you, Toons! Hope you enjoyed the show!' BlockerTitle = 'LOADING TOONTOWN...' BlockerLoadingTexts = ['Rewriting history', 'Baking pie crusts', 'Heating pie filling', 'Loading Doodle chow', 'Stringing Jungle Vines', 'Uncaging those spiders who crawl down jungle vines', 'Planting squirting flower seeds', 'Stretching trampolines', 'Herding pigs', "Tweaking 'SPLAT' sounds", 'Cleaning Hypno-glasses', 'Unbottling ink for Toon News', 'Clipping TNT fuses', "Setting up 'Under Construction' sign in Acorn Acres", 'Waking Donald Duck', 'Teaching new moves to dancing fire hydrants', 'Binding Shticker Books', 'Analyzing quacks', 'Harvesting jellybean pods', 'Emptying fish buckets', 'Corralling trashcan trash', 'Spreading Cog grease', 'Polishing kart trophies', 'Balancing scale for weighing 1 Ton weights', 'Practicing Victory Dances', 'Preparing wackiness', "Giving Mickey Mouse the 'five minutes' sign", 'Testing white gloves', 'Bending underwater rings', 'Spooling red tape', 'Freezing Brrrgh ice', 'Tuning falling pianos'] TIP_NONE = 0 TIP_GENERAL = 1 TIP_STREET = 2 TIP_MINIGAME = 3 TIP_COGHQ = 4 TIP_ESTATE = 5 TIP_KARTING = 6 TIP_GOLF = 7 TipTitle = 'TOON TIP:' TipDict = {TIP_NONE: ('',), TIP_GENERAL: ('Quickly check your ToonTask progress by holding down the "End" key.', 'Quickly check your Gag page by holding down the "Home" key.', 'Open your Friends List by pressing the "F7" key.', 'Open or close your Shticker Book by pressing the "F8" key.', 'You can look up by pressing the "Page Up" key and look down by pressing the "Page Down" key.', 'Press the "Control" key to jump.', 'Press the "F9" key to take a screenshot, which will be saved in your Town Toon Wacky Silly 3 folder on your computer.', 'You can change your screen resolution, adjust audio, and control other options on the Options Page in the Shticker Book.', "Try on your friend's clothing at the closet in their house.", 'You can go to your house using the "Go Home" button on your map.', 'Every time you turn in a completed ToonTask your Laff points are automatically refilled.', 'You can browse the selection at Clothing Stores even without a clothing ticket.', 'Rewards for some ToonTasks allow you to carry more gags and Jellybeans.', 'You can have up to 50 friends on your Friends List.', 'Some ToonTask rewards let you teleport to playgrounds in Toontown by using the Map Page in the Shticker Book.', 'Increase your Laff points in the Playgrounds by collecting treasures like stars and ice cream cones.', 'To heal quickly after a battle, go to your estate and play with your Doodle.', 'Change to different views of your Toon by pressing the Tab Key.', 'Sometimes you can find several different ToonTasks offered for the same reward. Shop around!', 'Finding friends with similar ToonTasks is a fun way to progress through the game.', 'You never need to save your Toontown progress. The Town Toon Wacky Silly 3 servers continually save all the necessary information.', 'You can whisper to other Toons either by clicking on them or by selecting them from your Friends List.', 'Some SpeedChat phrases play emotion animations on your Toon.', 'If the area you are in is crowded, try changing Districts. Go to the District Page in the Shticker Book and select a different one.', 'If you actively rescue buildings you will get a bronze, silver, or gold star above your Toon.', 'If you rescue enough buildings to get a star above your head you may find your name on the blackboard in a Toon HQ.', 'Rescued buildings are sometimes recaptured by the Cogs. The only way to keep your star is to go out and rescue more buildings!', 'The names of your True Friends will appear in Blue.', 'See if you can collect all the fish in Toontown!', 'Different ponds hold different fish. Try them all!', 'When your fishing bucket is full sell your fish to the Fishermen in the Playgrounds.', 'You can sell your fish to the Fishermen or inside Pet Shops.', 'Stronger fishing rods catch heavier fish but cost more Jellybeans to use.', 'You can purchase stronger fishing rods in the Cattlelog.', 'Heavier fish are worth more Jellybeans to the Pet Shop.', 'Rare fish are worth more Jellybeans to the Pet Shop.', 'You can sometimes find bags of Jellybeans while fishing.', 'Some ToonTasks require fishing items out of the ponds.', 'Fishing ponds in the Playgrounds have different fish than ponds on the streets.', 'Some fish are really rare. Keep fishing until you collect them all!', 'The pond at your estate has fish that can only be found there.', 'For every 10 species you catch, you will get a fishing trophy!', 'You can see what fish you have collected in your Shticker Book.', 'Some fishing trophies reward you with a Laff boost.', 'Fishing is a good way to earn more Jellybeans.', 'Adopt a Doodle at the Pet Shop!', 'Pet Shops get new Doodles to sell every day.', 'Visit the Pet Shops every day to see what new Doodles they have.', 'Different neighborhoods have different Doodles offered for adoption.', "Show off your stylin' ride and turbo-boost your Laff limit at Goofy Speedway.", 'Enter Goofy Speedway through the tire-shaped tunnel in Toontown Central Playground.', 'Earn Laff points at Goofy Speedway.', 'Goofy Speedway has six different race tracks. '), TIP_STREET: ('There are five types of Cogs: Lawbots, Cashbots, Sellbots, Bossbots, and Marketingbots.', 'Each Gag Track has different amounts of accuracy and damage.', 'Sound gags will affect all Cogs but will wake up any lured Cogs.', 'Defeating Cogs in strategic order can greatly increase your chances of winning battles.', 'The Toon-Up Gag Track lets you heal other Toons in battle.', 'Gag experience points are doubled during a Cog Invasion!', 'Multiple Toons can team up and use the same Gag Track in battle to get bonus Cog damage.', 'In battle, gags are used in order from top to bottom as displayed on the Gag Menu.', 'The row of circular lights over Cog Building elevators show how many floors will be inside.', 'Click on a Cog to see more details.', 'Using high level gags against low level Cogs will not earn any experience points.', 'A gag that will earn experience has a blue background on the Gag Menu in battle.', 'Gag experience is multiplied when used inside Cog Buildings. Higher floors have higher multipliers.', 'When a Cog is defeated, each Toon in that round will get credit for the Cog when the battle is over.', 'Each street in Toontown has different Cog levels and types.', 'Sidewalks are safe from Cogs.', 'On the streets, side doors tell knock-knock jokes when approached.', 'Some ToonTasks train you for new Gag Tracks. You only get to choose six of the seven Gag Tracks, so choose carefully!', 'Traps are only useful if you or your friends coordinate using Lure in battle.', 'Higher level Lures are less likely to miss.', 'Lower level gags have a lower accuracy against high level Cogs.', 'Cogs cannot attack once they have been lured in battle.', 'When you and your friends defeat a Cog building you are rewarded with portraits inside the rescued Toon Building.', 'Using a Toon-Up gag on a Toon with a full Laff meter will not earn Toon-Up experience.', 'Cogs will be briefly stunned when hit by any gag. This increases the chance that other gags in the same round will hit.', 'Drop gags have low chance of hitting, but accuracy is increased when Cogs are first hit by another gag in the same round.', 'When you\'ve defeated enough Cogs, use the "Cog Radar" by clicking the Cog icons on the Cog Gallery page in your Shticker Book.', 'During a battle, you can tell which Cog your teammates are attacking by looking at the dashes (-) and Xs.', 'During a battle, Cogs have a light on them that displays their health; green is healthy, red is nearly destroyed.', 'A maximum of four Toons can battle at once.', 'On the street, Cogs are more likely to join a fight against multiple Toons than just one Toon.', 'The two most difficult Cogs of each type are only found in buildings.', 'Drop gags never work against lured Cogs.', 'Cogs tend to attack the Toon that has done them the most damage.', 'Sound gags do not get bonus damage against lured Cogs.', 'If you wait too long to attack a lured Cog, it will wake up. Higher level lures last longer.', 'In Lawbot Field Offices, be sure to refuel your propeller often!', 'In Lawbot Field Offices, pick up feathers guarded by Legal Eagles for a laff boost.', 'In Lawbot Field Offices, pick up red tape to protect yourself from Legal Eagles.', 'In Lawbot Field Offices, watch out for Legal Eagles! They will take away some of your laff.', 'In Lawbot Field Offices, fly over fans with streamers to get a boost!', 'In Lawbot Field Offices, be sure to avoid whirlwinds. They will lock you in place, wasting precious fuel.', 'In Sellbot Field Offices, pick up jokes dropped by Cogs to get a laff boost.', 'In Sellbot Field Offices, falling cabinets will pop your water balloon.', 'In Sellbot Field Offices, Mover & Shaker cogs take two hits to defeat.', 'There are fishing ponds on every street in Toontown. Some streets have unique fish.'), TIP_MINIGAME: ('After you fill up your jellybean jar, any Jellybeans you get from Trolley Games automatically spill over into your bank.', 'You can use the arrow keys instead of the mouse in the "Match Kion" Trolley Game.', 'In the Cannon Game you can use the arrow keys to move your cannon and press the "Control" key to fire.', 'In the Ring Game, bonus points are awarded when the entire group successfully swims through its rings.', 'A perfect game of Match Kion will double your points.', 'In the Tug-of-War you are awarded more Jellybeans if you play against a tougher Cog.', 'Trolley Game difficulty varies by neighborhood; ' + lToontownCentral + ' has the easiest and ' + lDonaldsDreamland + ' has the hardest.', 'Certain Trolley Games can only be played in a group.'), TIP_COGHQ: ('You must complete your Sellbot Disguise before visiting the V.P.', 'You must complete your Cashbot Disguise before visiting the C.F.O.', 'You must complete your Lawbot Disguise before visiting the Chief Justice.', 'You can jump on Cog Goons to temporarily disable them.', 'Collect Cog Merits by defeating Sellbot Cogs in battle.', 'Collect Cogbucks by defeating Cashbot Cogs in battle.', 'Collect Jury Notices by defeating Lawbot Cogs in battle.', 'Collect Stock Options by defeating Bossbot Cogs in battle.', 'You get more Merits, Cogbucks, Jury Notices, or Stock Options from higher level Cogs.', 'When you collect enough Cog Merits to earn a promotion, go see the Sellbot V.P.!', 'When you collect enough Cogbucks to earn a promotion, go see the Cashbot C.F.O.!', 'When you collect enough Jury Notices to earn a promotion, go see the Lawbot Chief Justice!', 'When you collect enough Stock Options to earn a promotion, go see the Bossbot C.E.O.!', 'You can talk like a Cog when you are wearing your Cog Disguise.', 'Up to eight Toons can join together to fight the Sellbot V.P.', 'Up to eight Toons can join together to fight the Cashbot C.F.O.', 'Up to eight Toons can join together to fight the Lawbot Chief Justice.', 'Up to eight Toons can join together to fight the Bossbot C.E.O.', 'Inside Cog Headquarters follow stairs leading up to find your way.', 'Each time you battle through a Sellbot HQ factory, you will gain one part of your Sellbot Cog Disguise.', 'You can check the progress of your Cog Disguise in your Shticker Book.', 'You can check your promotion progress on your Disguise Page in your Shticker Book.', 'Make sure you have full gags and a full Laff Meter before going to Cog Headquarters.', 'As you get promoted, your Cog disguise updates.', 'You must defeat the ' + Foreman + ' to recover a Sellbot Cog Disguise part.', "Earn Cashbot disguise suit parts as rewards for completing ToonTasks in Donald's Dreamland.", 'Cashbots manufacture and distribute their currency, Cogbucks, in three Mints - Coin, Dollar and Bullion.', 'Wait until the C.F.O. is dizzy to throw a safe, or he will use it as a helmet! Hit the helmet with another safe to knock it off.', 'Earn Lawbot disguise suit parts as rewards for completing ToonTasks for Professor Flake.', "It pays to be puzzled: the virtual Cogs in Lawbot HQ won't reward you with Jury Notices."), TIP_ESTATE: ('Doodles can understand some SpeedChat phrases. Try them!', 'Use the "Pet" SpeedChat menu to ask your Doodle to do tricks.', "You can teach Doodles tricks with training lessons from Clarabelle's Cattlelog.", 'Reward your Doodle for doing tricks.', "If you visit a friend's estate, your Doodle will come too.", 'Feed your Doodle a jellybean when it is hungry.', 'Click on a Doodle to get a menu where you can Feed, Scratch, and Call him.', 'Doodles love company. Invite your friends over to play!', 'All Doodles have unique personalities.', 'You can return your Doodle and adopt a new one at the Pet Shops.', 'When a Doodle performs a trick, the Toons around it heal.', 'Doodles become better at tricks with practice. Keep at it!', 'More advanced Doodle tricks heal Toons faster.', 'Experienced Doodles can perform more tricks before getting tired.', 'You can see a list of nearby Doodles in your Friends List.', "Purchase furniture from Clarabelle's Cattlelog to decorate your house.", 'The bank inside your house holds extra Jellybeans.', 'The closet inside your house holds extra clothes.', "Go to your friend's house and try on his clothes.", "Purchase better fishing rods from Clarabelle's Cattlelog.", 'Call Clarabelle using the phone inside your house.', 'Clarabelle sells a larger closet that holds more clothing.', 'Make room in your closet before using a Clothing Ticket.', 'Clarabelle sells everything you need to decorate your house.', 'Check your mailbox for deliveries after ordering from Clarabelle.', "Clothing from Clarabelle's Cattlelog takes one hour to be delivered.", "Wallpaper and flooring from Clarabelle's Cattlelog take one hour to be delivered.", "Furniture from Clarabelle's Cattlelog takes a full day to be delivered.", 'Store extra furniture in your attic.', 'You will get a notice from Clarabelle when a new Cattlelog is ready.', 'You will get a notice from Clarabelle when a Cattlelog delivery arrives.', 'New Cattlelogs are delivered each week.', 'Look for limited-edition holiday items in the Cattlelog.', 'Move unwanted furniture to the trash can.', 'Some fish, like the Holey Mackerel, are more commonly found in Toon Estates.', 'You can invite your friends to your Estate using SpeedChat.', 'Did you know the color of your house matches the color of your Pick-A-Toon panel?'), TIP_KARTING: ("Buy a Roadster, TUV, or Cruiser kart in Goofy's Auto Shop.", "Customize your kart with decals, rims and more in Goofy's Auto Shop.", 'Earn tickets by kart racing at Goofy Speedway.', "Tickets are the only currency accepted at Goofy's Auto Shop.", 'Tickets are required as deposits to race.', 'A special page in the Shticker Book allows you to customize your kart.', 'A special page in the Shticker Book allows you to view records on each track.', 'A special page in the Shticker Book allows you to display trophies.', 'Screwball Stadium is the easiest track at Goofy Speedway.', 'Airborne Acres has the most hills and jumps of any track at Goofy Speedway.', 'Blizzard Boulevard is the most challenging track at Goofy Speedway.'), TIP_GOLF: ('Press the Tab key to see a top view of the golf course.', 'Press the Up Arrow key to point yourself towards the golf hole.', 'Swinging the club is just like throwing a pie.')} FishGenusNames = {0: 'Balloon Fish', 2: 'Cat Fish', 4: 'Clown Fish', 6: 'Frozen Fish', 8: 'Star Fish', 10: 'Holey Mackerel', 12: 'Dog Fish', 14: 'Amore Eel', 16: 'Nurse Shark', 18: 'King Crab', 20: 'Moon Fish', 22: 'Sea Horse', 24: 'Pool Shark', 26: 'Bear Acuda', 28: 'Cutthroat Trout', 30: 'Piano Tuna', 32: 'Peanut Butter & Jellyfish', 34: 'Devil Ray'} FishSpeciesNames = {0: ('Balloon Fish', 'Hot Air Balloon Fish', 'Weather Balloon Fish', 'Water Balloon Fish', 'Red Balloon Fish'), 2: ('Cat Fish', 'Siamese Cat Fish', 'Alley Cat Fish', 'Tabby Cat Fish', 'Tom Cat Fish'), 4: ('Clown Fish', 'Sad Clown Fish', 'Party Clown Fish', 'Circus Clown Fish'), 6: ('Frozen Fish',), 8: ('Star Fish', 'Five Star Fish', 'Rock Star Fish', 'Shining Star Fish', 'All Star Fish'), 10: ('Holey Mackerel',), 12: ('Dog Fish', 'Bull Dog Fish', 'Hot Dog Fish', 'Dalmatian Dog Fish', 'Puppy Dog Fish'), 14: ('Amore Eel', 'Electric Amore Eel'), 16: ('Nurse Shark', 'Clara Nurse Shark', 'Florence Nurse Shark'), 18: ('King Crab', 'Alaskan King Crab', 'Old King Crab'), 20: ('Moon Fish', 'Full Moon Fish', 'Half Moon Fish', 'New Moon Fish', 'Crescent Moon Fish', 'Harvest Moon Fish'), 22: ('Sea Horse', 'Rocking Sea Horse', 'Clydesdale Sea Horse', 'Arabian Sea Horse'), 24: ('Pool Shark', 'Kiddie Pool Shark', 'Swimming Pool Shark', 'Olympic Pool Shark'), 26: ('Brown Bear Acuda', 'Black Bear Acuda', 'Koala Bear Acuda', 'Honey Bear Acuda', 'Polar Bear Acuda', 'Panda Bear Acuda', 'Kodiac Bear Acuda', 'Grizzly Bear Acuda'), 28: ('Cutthroat Trout', 'Captain Cutthroat Trout', 'Scurvy Cutthroat Trout'), 30: ('Piano Tuna', 'Grand Piano Tuna', 'Baby Grand Piano Tuna', 'Upright Piano Tuna', 'Player Piano Tuna'), 32: ('Peanut Butter & Jellyfish', 'Grape PB&J Fish', 'Crunchy PB&J Fish', 'Strawberry PB&J Fish', 'Concord Grape PB&J Fish'), 34: ('Devil Ray',)} CogPartNames = ('Upper Left Leg', 'Lower Left Leg', 'Left Foot', 'Upper Right Leg', 'Lower Right Leg', 'Right Foot', 'Left Shoulder', 'Right Shoulder', 'Chest', 'Health Meter', 'Pelvis', 'Upper Left Arm', 'Lower Left Arm', 'Left Hand', 'Upper Right Arm', 'Lower Right Arm', 'Right Hand') CogPartNamesSimple = ('Upper Torso',) SellbotLegFactorySpecMainEntrance = 'Front Entrance' SellbotLegFactorySpecLobby = 'Lobby' SellbotLegFactorySpecLobbyHallway = 'Lobby Hallway' SellbotLegFactorySpecGearRoom = 'Gear Room' SellbotLegFactorySpecBoilerRoom = 'Boiler Room' SellbotLegFactorySpecEastCatwalk = 'East Catwalk' SellbotLegFactorySpecPaintMixer = 'Paint Mixer' SellbotLegFactorySpecPaintMixerStorageRoom = 'Paint Mixer Storage Room' SellbotLegFactorySpecWestSiloCatwalk = 'West Silo Catwalk' SellbotLegFactorySpecPipeRoom = 'Pipe Room' SellbotLegFactorySpecDuctRoom = 'Duct Room' SellbotLegFactorySpecSideEntrance = 'Side Entrance' SellbotLegFactorySpecStomperAlley = 'Stomper Alley' SellbotLegFactorySpecLavaRoomFoyer = 'Lava Room Foyer' SellbotLegFactorySpecLavaRoom = 'Lava Room' SellbotLegFactorySpecLavaStorageRoom = 'Lava Storage Room' SellbotLegFactorySpecWestCatwalk = 'West Catwalk' SellbotLegFactorySpecOilRoom = 'Oil Room' SellbotLegFactorySpecLookout = 'Lookout' SellbotLegFactorySpecWarehouse = 'Warehouse' SellbotLegFactorySpecOilRoomHallway = 'Oil Room Hallway' SellbotLegFactorySpecEastSiloControlRoom = 'East Silo Control Room' SellbotLegFactorySpecWestSiloControlRoom = 'West Silo Control Room' SellbotLegFactorySpecCenterSiloControlRoom = 'Center Silo Control Room' SellbotLegFactorySpecEastSilo = 'East Silo' SellbotLegFactorySpecWestSilo = 'West Silo' SellbotLegFactorySpecCenterSilo = 'Center Silo' SellbotLegFactorySpecEastSiloCatwalk = 'East Silo Catwalk' SellbotLegFactorySpecWestElevatorShaft = 'West Elevator Shaft' SellbotLegFactorySpecEastElevatorShaft = 'East Elevator Shaft' FishBingoBingo = 'BINGO!' FishBingoVictory = 'VICTORY!!' FishBingoJackpot = 'JACKPOT!' FishBingoGameOver = 'GAME OVER' FishBingoIntermission = 'Intermission\nEnds In:' FishBingoNextGame = 'Next Game\nStarts In:' FishBingoTypeNormal = 'Classic' FishBingoTypeCorners = 'Four Corners' FishBingoTypeDiagonal = 'Diagonals' FishBingoTypeThreeway = 'Three Way' FishBingoTypeBlockout = 'BLOCKOUT!' FishBingoStart = "It's time for Fish Bingo! Go to any available pier to play!" FishBingoOngoing = 'Welcome! Fish Bingo is currently in progress.' FishBingoEnd = 'Hope you had fun playing Fish Bingo.' FishBingoHelpMain = 'Welcome to Toontown Fish Bingo! Everyone at the pond works together to fill the card before time runs out.' FishBingoHelpFlash = 'When you catch a fish, click on one of the flashing squares to mark the card.' FishBingoHelpNormal = 'This is a Classic Bingo card. Mark any row down, across or diagonally to win.' FishBingoHelpDiagonals = 'Mark both of the diagonals to win.' FishBingoHelpCorners = 'An easy Corners card. Mark all four corners to win.' FishBingoHelpThreeway = "Three-way. Mark both diagonals and the middle row to win. This one isn't easy!" FishBingoHelpBingo = 'Bingo!' FishBingoHelpBlockout = 'Blockout!. Mark the entire card to win. You are competing against all the other ponds for a huge jackpot!' FishBingoOfferToSellFish = 'Your fish bucket is full. Would you like to sell your fish?' FishBingoJackpotWin = 'Win %s Jellybeans!' ResistanceToonupMenu = 'Toon-up' ResistanceToonupItem = '%s Toon-up' ResistanceToonupItemMax = 'Max' ResistanceToonupChat = 'Toons of the World, Toon-up!' ResistanceRestockMenu = 'Gag-up' ResistanceRestockItem = 'Gag-up %s' ResistanceRestockItemAll = 'All' ResistanceRestockChat = 'Toons of the World, Gag-up!' ResistanceMoneyMenu = 'Jellybeans' ResistanceMoneyItem = '%s Jellybeans' ResistanceMoneyChat = 'Toons of the World, Spend Wisely!' ResistanceEmote1 = NPCToonNames[9228] + ': Welcome to the Resistance!' ResistanceEmote2 = NPCToonNames[9228] + ': Use your new emote to identify yourself to other members.' ResistanceEmote3 = NPCToonNames[9228] + ': Good luck!' KartUIExit = 'Leave Kart' KartShop_Cancel = lCancel KartShop_BuyKart = 'Buy Kart' KartShop_BuyAccessories = 'Buy Accessories' KartShop_BuyAccessory = 'Buy Accessory' KartShop_Cost = 'Cost: %d Tickets' KartShop_ConfirmBuy = 'Buy the %s for %d Tickets?' KartShop_NoAvailableAcc = 'No available accessories of this type' KartShop_FullTrunk = 'Your trunk is full.' KartShop_ConfirmReturnKart = 'Are you sure you want to return your current Kart?' KartShop_ConfirmBoughtTitle = 'Congratulations!' KartShop_NotEnoughTickets = 'Not Enough Tickets!' KartView_Rotate = 'Rotate' KartView_Right = 'Right' KartView_Left = 'Left' StartingBlock_NotEnoughTickets = "You don't have enough tickets! Try a practice race instead." StartingBlock_NoBoard = 'Boarding has ended for this race. Please wait for the next race to begin.' StartingBlock_NoKart = 'You need a kart first! Try asking one of the clerks in the Kart Shop.' StartingBlock_Occupied = 'This block is currently occupied! Please try another spot.' StartingBlock_TrackClosed = 'Sorry, this track is closed for remodeling.' StartingBlock_EnterPractice = 'Would you like to enter a practice race?' StartingBlock_EnterNonPractice = 'Would you like to enter a %s race for %s tickets?' StartingBlock_EnterShowPad = 'Would you like to park your car here?' StartingBlock_KickSoloRacer = 'Toon Battle and Grand Prix races require two or more racers.' StartingBlock_Loading = 'Goofy Speedway' LeaderBoard_Time = 'Time' LeaderBoard_Name = 'Racer Name' LeaderBoard_Daily = 'Daily Scores' LeaderBoard_Weekly = 'Weekly Scores' LeaderBoard_AllTime = 'All Time Best Scores' RecordPeriodStrings = [LeaderBoard_Daily, LeaderBoard_Weekly, LeaderBoard_AllTime] KartRace_RaceNames = ['Practice', 'Toon Battle', 'Grand Prix'] from toontown.racing import RaceGlobals KartRace_Go = 'Go!' KartRace_Reverse = ' Rev' KartRace_TrackNames = {RaceGlobals.RT_Speedway_1: 'Screwball Stadium', RaceGlobals.RT_Speedway_1_rev: 'Screwball Stadium' + KartRace_Reverse, RaceGlobals.RT_Rural_1: 'Rustic Raceway', RaceGlobals.RT_Rural_1_rev: 'Rustic Raceway' + KartRace_Reverse, RaceGlobals.RT_Urban_1: 'City Circuit', RaceGlobals.RT_Urban_1_rev: 'City Circuit' + KartRace_Reverse, RaceGlobals.RT_Speedway_2: 'Corkscrew Coliseum', RaceGlobals.RT_Speedway_2_rev: 'Corkscrew Coliseum' + KartRace_Reverse, RaceGlobals.RT_Rural_2: 'Airborne Acres', RaceGlobals.RT_Rural_2_rev: 'Airborne Acres' + KartRace_Reverse, RaceGlobals.RT_Urban_2: 'Blizzard Boulevard', RaceGlobals.RT_Urban_2_rev: 'Blizzard Boulevard' + KartRace_Reverse} KartRace_Unraced = 'N/A' KartDNA_KartNames = {0: 'Cruiser', 1: 'Roadster', 2: 'Toon Utility Vehicle'} KartDNA_AccNames = {1000: 'Air Cleaner', 1001: 'Four Barrel', 1002: 'Flying Eagle', 1003: 'Steer Horns', 1004: 'Straight Six', 1005: 'Small Scoop', 1006: 'Single Overhead', 1007: 'Medium Scoop', 1008: 'Single Barrel', 1009: 'Flugle Horn', 1010: 'Striped Scoop', 2000: 'Space Wing', 2001: 'Patched Spare', 2002: 'Roll Cage', 2003: 'Single Fin', 2004: 'Double-decker Wing', 2005: 'Single Wing', 2006: 'Standard Spare', 2007: 'Single Fin', 2008: 'sp9', 2009: 'sp10', 3000: 'Dueling Horns', 3001: "Freddie's Fenders", 3002: 'Cobalt Running Boards', 3003: 'Cobra Sidepipes', 3004: 'Straight Sidepipes', 3005: 'Scalloped Fenders', 3006: 'Carbon Running Boards', 3007: 'Wood Running Boards', 3008: 'fw9', 3009: 'fw10', 4000: 'Curly Tailpipes', 4001: 'Splash Fenders', 4002: 'Dual Exhaust', 4003: 'Plain Dual Fins', 4004: 'Plain Mudflaps', 4005: 'Quad Exhaust', 4006: 'Dual Flares', 4007: 'Mega Exhaust', 4008: 'Striped Dual Fins', 4009: 'Bubble Duals Fins', 4010: 'Striped Mudflaps', 4011: 'Mickey Mudflaps', 4012: 'Scalloped Mudflaps', 5000: 'Turbo', 5001: 'Moon', 5002: 'Patched', 5003: 'Three Spoke', 5004: 'Paint Lid', 5005: 'Heart', 5006: 'Mickey', 5007: 'Five Bolt', 5008: 'Daisy', 5009: 'Basketball', 5010: 'Hypno', 5011: 'Tribal', 5012: 'Gemstone', 5013: 'Five Spoke', 5014: 'Knockoff', 6000: 'Number Five', 6001: 'Splatter', 6002: 'Checkerboard', 6003: 'Flames', 6004: 'Hearts', 6005: 'Bubbles', 6006: 'Tiger', 6007: 'Flowers', 6008: 'Lightning', 6009: 'Angel', 7000: 'Chartreuse', 7001: 'Peach', 7002: 'Bright Red', 7003: 'Red', 7004: 'Maroon', 7005: 'Sienna', 7006: 'Brown', 7007: 'Tan', 7008: 'Coral', 7009: 'Orange', 7010: 'Yellow', 7011: 'Cream', 7012: 'Citrine', 7013: 'Lime', 7014: 'Sea Green', 7015: 'Green', 7016: 'Light Blue', 7017: 'Aqua', 7018: 'Blue', 7019: 'Periwinkle', 7020: 'Royal Blue', 7021: 'Slate Blue', 7022: 'Purple', 7023: 'Lavender', 7024: 'Pink', 7025: 'Plum', 7026: 'Black'} RaceHoodSpeedway = 'Speedway' RaceHoodRural = 'Rural' RaceHoodUrban = 'Urban' RaceTypeCircuit = 'Tournament' RaceQualified = 'qualified' RaceSwept = 'swept' RaceWon = 'won' Race = 'race' Races = 'races' Total = 'total' GrandTouring = 'Grand Touring' def getTrackGenreString(genreId): genreStrings = ['Speedway', 'Country', 'City'] return genreStrings[genreId].lower() def getTunnelSignName(trackId, padId): if trackId == 2 and padId == 0: return 'tunne1l_citysign' elif trackId == 1 and padId == 0: return 'tunnel_countrysign1' else: genreId = RaceGlobals.getTrackGenre(trackId) return 'tunnel%s_%ssign' % (padId + 1, RaceGlobals.getTrackGenreString(genreId)) KartTrophyDescriptions = [str(RaceGlobals.QualifiedRaces[0]) + ' ' + RaceHoodSpeedway + ' ' + Race + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[1]) + ' ' + RaceHoodSpeedway + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[2]) + ' ' + RaceHoodSpeedway + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[0]) + ' ' + RaceHoodRural + ' ' + Race + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[1]) + ' ' + RaceHoodRural + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[2]) + ' ' + RaceHoodRural + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[0]) + ' ' + RaceHoodUrban + ' ' + Race + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[1]) + ' ' + RaceHoodUrban + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.QualifiedRaces[2]) + ' ' + RaceHoodUrban + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.TotalQualifiedRaces) + ' ' + Total + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.WonRaces[0]) + ' ' + RaceHoodSpeedway + ' ' + Race + ' ' + RaceWon, str(RaceGlobals.WonRaces[1]) + ' ' + RaceHoodSpeedway + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonRaces[2]) + ' ' + RaceHoodSpeedway + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonRaces[0]) + ' ' + RaceHoodRural + ' ' + Race + ' ' + RaceWon, str(RaceGlobals.WonRaces[1]) + ' ' + RaceHoodRural + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonRaces[2]) + ' ' + RaceHoodRural + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonRaces[0]) + ' ' + RaceHoodUrban + ' ' + Race + ' ' + RaceWon, str(RaceGlobals.WonRaces[1]) + ' ' + RaceHoodUrban + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonRaces[2]) + ' ' + RaceHoodUrban + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.TotalWonRaces) + ' ' + Total + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonCircuitRaces[0]) + ' ' + RaceTypeCircuit + ' ' + Race + ' ' + RaceQualified, str(RaceGlobals.WonCircuitRaces[1]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.WonCircuitRaces[2]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceQualified, str(RaceGlobals.WonCircuitRaces[0]) + ' ' + RaceTypeCircuit + ' ' + Race + ' ' + RaceWon, str(RaceGlobals.WonCircuitRaces[1]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.WonCircuitRaces[2]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceWon, str(RaceGlobals.SweptCircuitRaces[0]) + ' ' + RaceTypeCircuit + ' ' + Race + ' ' + RaceSwept, str(RaceGlobals.SweptCircuitRaces[1]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceSwept, str(RaceGlobals.SweptCircuitRaces[2]) + ' ' + RaceTypeCircuit + ' ' + Races + ' ' + RaceSwept, GrandTouring, str(RaceGlobals.TrophiesPerCup) + ' Kart Racing trophies won! Laff point boost!', str(RaceGlobals.TrophiesPerCup * 2) + ' Kart Racing trophies won! Laff point boost!', str(RaceGlobals.TrophiesPerCup * 3) + ' Kart Racing trophies won! Laff point boost!'] KartRace_TitleInfo = 'Get Ready to Race' KartRace_SSInfo = 'Welcome to Screwball Stadium!\nPut the pedal to the metal and hang on tight!\n' KartRace_CoCoInfo = 'Welcome to Corkscrew Coliseum!\nUse the banked turns to keep your speed up!\n' KartRace_RRInfo = 'Welcome to Rustic Raceway!\nPlease be kind to the fauna and stay on the track!\n' KartRace_AAInfo = 'Welcome to Airborne Acres!\nHold onto your hats! It looks bumpy up ahead...\n' KartRace_CCInfo = 'Welcome to City Circuit!\nWatch out for pedestrians as you speed through downtown!\n' KartRace_BBInfo = 'Welcome to Blizzard Boulevard!\nWatch your speed. There might be ice out there.\n' KartRace_GeneralInfo = 'Use Control to throw gags you pick up on the track, and the arrow keys to control your kart.' KartRace_TrackInfo = {RaceGlobals.RT_Speedway_1: KartRace_SSInfo + KartRace_GeneralInfo, RaceGlobals.RT_Speedway_1_rev: KartRace_SSInfo + KartRace_GeneralInfo, RaceGlobals.RT_Speedway_2: KartRace_CoCoInfo + KartRace_GeneralInfo, RaceGlobals.RT_Speedway_2_rev: KartRace_CoCoInfo + KartRace_GeneralInfo, RaceGlobals.RT_Rural_1: KartRace_RRInfo + KartRace_GeneralInfo, RaceGlobals.RT_Rural_1_rev: KartRace_RRInfo + KartRace_GeneralInfo, RaceGlobals.RT_Rural_2: KartRace_AAInfo + KartRace_GeneralInfo, RaceGlobals.RT_Rural_2_rev: KartRace_AAInfo + KartRace_GeneralInfo, RaceGlobals.RT_Urban_1: KartRace_CCInfo + KartRace_GeneralInfo, RaceGlobals.RT_Urban_1_rev: KartRace_CCInfo + KartRace_GeneralInfo, RaceGlobals.RT_Urban_2: KartRace_BBInfo + KartRace_GeneralInfo, RaceGlobals.RT_Urban_2_rev: KartRace_BBInfo + KartRace_GeneralInfo} KartRecordStrings = {RaceGlobals.Daily: 'daily', RaceGlobals.Weekly: 'weekly', RaceGlobals.AllTime: 'all time'} KartRace_FirstSuffix = 'st' KartRace_SecondSuffix = ' nd' KartRace_ThirdSuffix = ' rd' KartRace_FourthSuffix = ' th' KartRace_WrongWay = 'Wrong\nWay!' KartRace_LapText = 'Lap %s' KartRace_FinalLapText = 'Final Lap!' KartRace_Exit = 'Exit Race' KartRace_NextRace = 'Next Race' KartRace_Leave = 'Leave Race' KartRace_Qualified = 'Qualified!' KartRace_Record = 'Record!' KartRace_RecordString = 'You have set a new %s record for %s! Your bonus is %s tickets.' KartRace_Tickets = 'Tickets' KartRace_Exclamations = '!' KartRace_Deposit = 'Deposit' KartRace_Winnings = 'Winnings' KartRace_Bonus = 'Bonus' KartRace_RaceTotal = 'Race Total' KartRace_CircuitTotal = 'Circuit Total' KartRace_Trophies = 'Trophies' KartRace_Zero = '0' KartRace_Colon = ':' KartRace_TicketPhrase = '%s ' + KartRace_Tickets KartRace_DepositPhrase = KartRace_Deposit + KartRace_Colon + '\n' KartRace_QualifyPhrase = 'Qualify:\n' KartRace_RaceTimeout = 'You timed out of that race. Your tickets have been refunded. Keep trying!' KartRace_RaceTimeoutNoRefund = 'You timed out of that race. Your tickets have not been refunded because the Grand Prix had already started. Keep trying!' KartRace_RacerTooSlow = 'You took too long to finish the race. Your tickets have not been refunded. Keep trying!' KartRace_PhotoFinish = 'Photo Finish!' KartRace_CircuitPoints = 'Circuit Points' CircuitRaceStart = 'The Toontown Grand Prix at Goofy Speedway is about to begin! To win, collect the most points in three consecutive races!' CircuitRaceOngoing = 'Welcome! The Toontown Grand Prix is currently in progress.' CircuitRaceEnd = "That's all for today's Toontown Grand Prix at Goofy Speedway. See you next week!" TrickOrTreatMsg = 'You have already\nfound this treat!' WinterCarolingMsg = 'You have already been caroling here!' LawbotBossTempIntro0 = "Hmmm what's on the docket today?" LawbotBossTempIntro1 = 'Aha, we have a Toon on trial!' LawbotBossTempIntro2 = "The prosecution's case is strong." LawbotBossTempIntro3 = 'And here are the public defenders.' LawbotBossTempIntro4 = "Wait a minute... You're Toons!" LawbotBossTempJury1 = 'Jury selection will now commence.' LawbotBossHowToGetEvidence = 'Touch the witness stand to get evidence.' LawbotBossTrialChat1 = 'Court is now in session' LawbotBossHowToThrowPies = 'Press the Delete key to throw the evidence\n at the lawyers or into the scale!' LawbotBossNeedMoreEvidence = 'You need to get more evidence!' LawbotBossDefenseWins1 = 'Impossible! The defense won?' LawbotBossDefenseWins2 = 'No. I declare a mistrial! A new one will be scheduled.' LawbotBossDefenseWins3 = "Hrrmpphh. I'll be in my chambers." LawbotBossProsecutionWins = 'I find in favor of the plaintiff' LawbotBossReward = 'I award a promotion and the ability to summon Cogs' LawbotBossLeaveCannon = 'Leave cannon' LawbotBossPassExam = 'Bah, so you passed the bar exam.' LawbotBossTaunts = ['%s, I find you in contempt of court!', 'Objection sustained!', 'Strike that from the record.', 'Your appeal has been rejected. I sentence you to sadness!', 'Order in the court!'] LawbotBossAreaAttackTaunt = "You're all in contempt of court!" WitnessToonName = 'Bumpy Bumblebehr' WitnessToonPrepareBattleTwo = "Oh no! They're putting only Cogs on the jury!\x07Quick, use the cannons and shoot some Toon jurors into the jury chairs.\x07We need %d to get a balanced scale." WitnessToonNoJuror = 'Oh oh, no Toon jurors. This will be a tough trial.' WitnessToonOneJuror = 'Cool! There is 1 Toon in the jury!' WitnessToonSomeJurors = 'Cool! There are %d Toons in the jury!' WitnessToonAllJurors = 'Awesome! All the jurors are Toons!' WitnessToonPrepareBattleThree = 'Hurry, touch the witness stand to get evidence.\x07Press the Delete key to throw the evidence at the lawyers, or at the defense pan.' WitnessToonCongratulations = "You did it! Thank you for a spectacular defense!\x07Here, take these papers the Chief Justice left behind.\x07With it you'll be able to summon Cogs from your Cog Gallery page." WitnessToonLastPromotion = "\x07Wow, you've reached level %s on your Cog Suit!\x07Cogs don't get promoted higher than that.\x07You can't upgrade your Cog Suit anymore, but you can certainly keep working for the Resistance!" WitnessToonHPBoost = "\x07You've done a lot of work for the Resistance.\x07The Toon Council has decided to give you another Laff point. Congratulations!" WitnessToonMaxed = '\x07I see that you have a level %s Cog Suit. Very impressive!\x07On behalf of the Toon Council, thank you for coming back to defend more Toons!' WitnessToonBonus = 'Wonderful! All the lawyers are stunned. Your evidence weight is %s times heavier for %s seconds' WitnessToonJuryWeightBonusSingular = {6: 'This is a tough case. You seated %d Toon juror, so your evidence has a bonus weight of %d.', 7: 'This is a very tough case. You seated %d Toon juror, so your evidence has a bonus weight of %d.', 8: 'This is the toughest case. You seated %d Toon juror, so your evidence has a bonus weight of %d.'} WitnessToonJuryWeightBonusPlural = {6: 'This is a tough case. You seated %d Toon jurors, so your evidence has a bonus weight of %d.', 7: 'This is a very tough case. You seated %d Toon jurors, so your evidence has a bonus weight of %d.', 8: 'This is the toughest case. You seated %d Toon jurors, so your evidence has a bonus weight of %d.'} IssueSummons = 'Summon' SummonDlgTitle = 'Issue a Cog Summons' SummonDlgButton1 = 'Summon a Cog' SummonDlgButton2 = 'Summon a Cog Building' SummonDlgButton3 = 'Summon a Cog Invasion' SummonDlgSingleConf = 'Would you like to issue a summons to a %s?' SummonDlgBuildingConf = 'Would you like to summon a %s to a nearby Toon building?' SummonDlgInvasionConf = 'Would you like to summon a %s invasion?' SummonDlgNumLeft = 'You have %s left.' SummonDlgDelivering = 'Delivering Summons...' SummonDlgSingleSuccess = 'You have successfully summoned the Cog.' SummonDlgSingleBadLoc = "Sorry, Cogs aren't allowed here. Try somewhere else." SummonDlgBldgSuccess = 'You have successfully summoned the Cogs. %s has agreed to let them temporarily take over %s!' SummonDlgBldgSuccess2 = 'You have successfully summoned the Cogs. A Shopkeeper has agreed to let them temporarily take over their building!' SummonDlgBldgBadLoc = 'Sorry, there are no Toon buildings nearby for the Cogs to take over.' SummonDlgInvasionSuccess = "You have successfully summoned the Cogs. It's an invasion!" SummonDlgInvasionBusy = 'A %s cannot be found now. Try again when the Cog invasion is over.' SummonDlgInvasionFail = 'Sorry, the Cog invasion has failed.' SummonDlgShopkeeper = 'The Shopkeeper ' PolarPlaceEffect1 = NPCToonNames[3306] + ': Welcome to Polar Place!' PolarPlaceEffect2 = NPCToonNames[3306] + ': Try this on for size.' PolarPlaceEffect3 = NPCToonNames[3306] + ': Your new look will only work in ' + lTheBrrrgh + '.' GreenToonEffectMsg = NPCToonNames[5312] + ': You look Toontastic in green!' LaserGameMine = 'Skull Finder!' LaserGameRoll = 'Matching' LaserGameAvoid = 'Avoid the Skulls' LaserGameDrag = 'Drag three of a color in a row' LaserGameDefault = 'Unknown Game' PinballHiScore = 'High Score: %s\n' PinballHiScoreAbbrev = '...' PinballYourBestScore = 'Your Best Score:\n' PinballScore = 'Score: %d x %d = ' PinballScoreHolder = '%s\n' GagTreeFeather = 'Feather Gag Tree' GagTreeJugglingBalls = 'Juggling Balls Gag Tree' StatuaryFountain = 'Fountain' StatuaryDonald = 'Donald Statue' StatuaryMinnie = 'Minnie Statue' StatuaryMickey1 = 'Mickey Statue' StatuaryMickey2 = 'Mickey Fountain' StatuaryToon = 'Toon Statue' StatuaryToonWave = 'Toon Wave Statue' StatuaryToonVictory = 'Toon Victory Statue' StatuaryToonCrossedArms = 'Toon Authority Statue' StatuaryToonThinking = 'Toon Embrace Statue' StatuaryMeltingSnowman = 'Melting Snowman' StatuaryMeltingSnowDoodle = 'Melting SnowDoodle' StatuaryGardenAccelerator = 'Insta-Grow Fertilizer' AnimatedStatuaryFlappyCog = 'Flappy Cog' FlowerColorStrings = ['Red', 'Orange', 'Violet', 'Blue', 'Pink', 'Yellow', 'White', 'Green'] FlowerSpeciesNames = {49: 'Daisy', 50: 'Tulip', 51: 'Carnation', 52: 'Lily', 53: 'Daffodil', 54: 'Pansy', 55: 'Petunia', 56: 'Rose'} FlowerFunnyNames = {49: ('School Daisy', 'Lazy Daisy', 'Midsummer Daisy', 'Freshasa Daisy', 'Whoopsie Daisy', 'Upsy Daisy', 'Crazy Daisy', 'Hazy Dazy'), 50: ('Onelip', 'Twolip', 'Threelip'), 51: ('What-in Carnation', 'Instant Carnation', 'Hybrid Carnation', 'Side Carnation', 'Model Carnation'), 52: ('Lily-of-the-Alley', 'Lily Pad', 'Tiger Lily', 'Livered Lily', 'Chili Lily', 'Silly Lily', 'Indubitab Lily', 'Dilly Lilly'), 53: ('Laff-o-dil', 'Daffy Dill', 'Giraff-o-dil', 'Time and a half-o-dil'), 54: ('Dandy Pansy', 'Chim Pansy', 'Potsen Pansy', 'Marzi Pansy', 'Smarty Pansy'), 55: ('Car Petunia', 'Platoonia'), 56: ("Summer's Last Rose", 'Corn Rose', 'Tinted Rose', 'Stinking Rose', 'Istilla Rose')} FlowerVarietyNameFormat = '%s %s' FlowerUnknown = '????' FloweringNewEntry = 'New Entry' ShovelNameDict = {0: 'Tin', 1: 'Bronze', 2: 'Silver', 3: 'Gold'} WateringCanNameDict = {0: 'Small', 1: 'Medium', 2: 'Large', 3: 'Huge'} GardeningPlant = 'Plant' GardeningWater = 'Water' GardeningRemove = 'Remove' GardeningPick = 'Pick' GardeningFull = 'Full' GardeningSkill = 'Skill' GardeningWaterSkill = 'Water Skill' GardeningShovelSkill = 'Shovel Skill' GardeningNoSkill = 'No Skill Up' GardeningPlantFlower = 'Plant\nFlower' GardeningPlantTree = 'Plant\nTree' GardeningPlantItem = 'Plant\nItem' PlantingGuiOk = 'Plant' PlantingGuiCancel = 'Cancel' PlantingGuiReset = 'Reset' GardeningChooseBeans = 'Choose the Jellybeans you want to plant.' GardeningChooseBeansItem = 'Choose the Jellybeans / item you want to plant.' GardeningChooseToonStatue = 'Choose the toon you want to create a statue of.' GardenShovelLevelUp = "Congratulations you've earned a %(shovel)s! You've mastered the %(oldbeans)d bean flower! To progress you should pick %(newbeans)d bean flowers." GardenShovelSkillLevelUp = "Congratulations! You've mastered the %(oldbeans)d bean flower! To progress you should pick %(newbeans)d bean flowers." GardenShovelSkillMaxed = "Amazing! You've maxed out your shovel skill!" GardenWateringCanLevelUp = "Congratulations you've earned a new watering can!" GardenMiniGameWon = "Congratulations you've watered the plant!" ShovelTin = 'Tin Shovel' ShovelSteel = 'Bronze Shovel' ShovelSilver = 'Silver Shovel' ShovelGold = 'Gold Shovel' WateringCanSmall = 'Small Watering Can' WateringCanMedium = 'Medium Watering Can' WateringCanLarge = 'Large Watering Can' WateringCanHuge = 'Huge Watering Can' BeanColorWords = ('red', 'green', 'orange', 'violet', 'blue', 'pink', 'yellow', 'cyan', 'silver') PlantItWith = ' Plant with %s.' MakeSureWatered = ' Make sure all your plants are watered first.' UseFromSpecialsTab = ' Use from the specials tab of the garden page.' UseSpecial = 'Use Special' UseSpecialBadLocation = 'You can only use that in your garden.' UseSpecialSuccess = 'Success! Your watered plants just grew.' ConfirmWiltedFlower = '%(plant)s is wilted. Are you sure you want to remove it? It will not go into your flower basket, nor will you get an increase in skill.' ConfirmUnbloomingFlower = '%(plant)s is not blooming. Are you sure you want to remove it? It will not go into your flower basket, nor will you get an increase in skill.' ConfirmNoSkillupFlower = 'Are you sure you want to pick the %(plant)s? It will go into your flower basket, but you will NOT get an increase in skill.' ConfirmSkillupFlower = 'Are you sure you want to pick the %(plant)s? It will go into your flower basket. You will also get an increase in skill.' ConfirmMaxedSkillFlower = "Are you sure you want to pick the %(plant)s? It will go into your flower basket. You will NOT get an increase in skill since you've maximized it already." ConfirmBasketFull = 'Your flower basket is full. Sell some flowers first.' ConfirmRemoveTree = 'Are you sure you want to remove the %(tree)s?' ConfirmWontBeAbleToHarvest = " If you remove this tree, you won't be able to harvest gags from the higher level trees." ConfirmRemoveStatuary = 'Are you sure you want to permanently delete the %(item)s?' ResultPlantedSomething = 'Congratulations! You just planted a %s.' ResultPlantedSomethingAn = 'Congratulations! You just planted an %s.' ResultPlantedNothing = "That didn't work. Please try a different combination of Jellybeans." GardenGagTree = ' Gag Tree' GardenUberGag = 'Uber Gag' def getRecipeBeanText(beanTuple): retval = '' if not beanTuple: return retval allTheSame = True for index in range(len(beanTuple)): if index + 1 < len(beanTuple): if not beanTuple[index] == beanTuple[index + 1]: allTheSame = False break if allTheSame: if len(beanTuple) > 1: retval = '%d %s Jellybeans' % (len(beanTuple), BeanColorWords[beanTuple[0]]) else: retval = 'a %s jellybean' % BeanColorWords[beanTuple[0]] else: retval += 'a' maxBeans = len(beanTuple) for index in range(maxBeans): if index == maxBeans - 1: retval += ' and %s jellybean' % BeanColorWords[beanTuple[index]] elif index == 0: retval += ' %s' % BeanColorWords[beanTuple[index]] else: retval += ', %s' % BeanColorWords[beanTuple[index]] return retval GardenTextMagicBeans = 'Magic Beans' GardenTextMagicBeansB = 'Some Other Beans' GardenSpecialDiscription = 'This text should explain how to use a certain garden special' GardenSpecialDiscriptionB = 'This text should explain how to use a certain garden special, in yo face foo!' GardenTrophyAwarded = 'Wow! You collected %s of %s flowers. That deserves a trophy and a Laff boost!' GardenTrophyNameDict = {0: 'Wheelbarrow', 1: 'Shovels', 2: 'Flower', 3: 'Watering Can', 4: 'Shark', 5: 'Swordfish', 6: 'Killer Whale'} SkillTooLow = 'Skill\nToo Low' NoGarden = 'No\nGarden' def isVowelStart(str): retval = False if str and len(str) > 0: vowels = ['A', 'E', 'I', 'O', 'U'] firstLetter = str.upper()[0:1] if firstLetter in vowels: retval = True return retval def getResultPlantedSomethingSentence(flowerName): if isVowelStart(flowerName): retval = ResultPlantedSomethingAn % flowerName else: retval = ResultPlantedSomething % flowerName return retval TravelGameTitle = 'Trolley Tracks' TravelGameInstructions = 'Click up or down to set your number of votes. Click the vote button to cast it. Reach your secret goal to get bonus beans. Earn more votes by doing well in the other games.' TravelGameRemainingVotes = 'Remaining Votes:' TravelGameUse = 'Use' TravelGameVotesWithPeriod = 'votes.' TravelGameVotesToGo = 'votes to go' TravelGameVoteToGo = 'vote to go' TravelGameUp = 'UP.' TravelGameDown = 'DOWN.' TravelGameVoteWithExclamation = 'Vote!' TravelGameWaitingChoices = 'Waiting for other players to vote...' TravelGameDirections = ['UP', 'DOWN'] TravelGameTotals = 'Totals ' TravelGameReasonVotes = 'The trolley is moving %(dir)s, winning by %(numVotes)d votes.' TravelGameReasonVotesPlural = 'The trolley is moving %(dir)s, winning by %(numVotes)d votes.' TravelGameReasonVotesSingular = 'The trolley is moving %(dir)s, winning by %(numVotes)d vote.' TravelGameReasonPlace = '%(name)s breaks the tie. The trolley is moving %(dir)s.' TravelGameReasonRandom = 'The trolley is randomly moving %(dir)s.' TravelGameOneToonVote = '%(name)s used %(numVotes)s votes to go %(dir)s\n' TravelGameBonusBeans = '%(numBeans)d Beans' TravelGamePlaying = 'Up next, the %(game)s trolley game.' TravelGameGotBonus = '%(name)s got a bonus of %(numBeans)s Jellybeans!' TravelGameNoOneGotBonus = 'No one reached their secret goal. Everyone gets 1 jellybean.' TravelGameConvertingVotesToBeans = 'Converting some votes to Jellybeans...' TravelGameGoingBackToShop = "Only 1 player left. Going to Goofy's Gag Shop." PairingGameTitle = 'Toon Memory Game' PairingGameInstructions = 'Press Delete to open a card. Match 2 cards to score a point. Make a match with the bonus glow and earn an extra point. Earn more points by keeping the flips low.' PairingGameInstructionsMulti = 'Press Delete to open a card. Press Control to signal another player to open a card. Match 2 cards to score a point. Make a match with the bonus glow and earn an extra point. Earn more points by keeping the flips low.' PairingGamePerfect = 'PERFECT!!' PairingGameFlips = 'Flips:' PairingGamePoints = 'Points:' TrolleyHolidayStart = 'Trolley Tracks is about to begin! Board any trolley with 2 or more toons to play.' TrolleyHolidayOngoing = 'Welcome! Trolley Tracks is currently in progress.' TrolleyHolidayEnd = "That's all for today's Trolley Tracks. See you next week!" TrolleyWeekendStart = 'Trolley Tracks Weekend is about to begin! Board any trolley with 2 or more toons to play.' TrolleyWeekendEnd = "That's all for Trolley Tracks Weekend." VineGameTitle = 'Jungle Vines' VineGameInstructions = 'Get to the rightmost vine in time. Press Up or Down to climb the vine. Press Left or Right to change facing and jump. The lower you are on the vine, the faster you jump off. Collect the bananas if you can, but avoid the bats and spiders.' ValentinesDayStart = "Happy ValenToon's Day!" ValentinesDayEnd = "That's all for ValenToon's Day!" GolfCourseNames = {0: 'Walk In The Par', 1: 'Hole Some Fun', 2: 'The Hole Kit And Caboodle'} GolfHoleNames = {0: 'Whole In Won', 1: 'No Putts About It', 2: 'Down The Hatch', 3: 'Seeing Green', 4: 'Hot Links', 5: 'Peanut Putter', 6: 'Swing-A-Long', 7: 'Afternoon Tee', 8: 'Hole In Fun', 9: 'Rock And Roll In', 10: 'Bogey Nights', 11: 'Tea Off Time', 12: 'Holey Mackerel!', 13: 'One Little Birdie', 14: 'At The Drive In', 15: 'Swing Time', 16: 'Hole On The Range', 17: 'Second Wind', 18: 'Whole In Won-2', 19: 'No Putts About It-2', 20: 'Down The Hatch-2', 21: 'Seeing Green-2', 22: 'Hot Links-2', 23: 'Peanut Putter-2', 24: 'Swing-A-Long-2', 25: 'Afternoon Tee-2', 26: 'Hole In Fun-2', 27: 'Rock And Roll In-2', 28: 'Bogey Nights-2', 29: 'Tea Off Time-2', 30: 'Holey Mackerel!-2', 31: 'One Little Birdie-2', 32: 'At The Drive In-2', 33: 'Swing Time-2', 34: 'Hole On The Range-2', 35: 'Second Wind-2'} GolfHoleInOne = 'Hole In One' GolfCondor = 'Condor' GolfAlbatross = 'Albatross' GolfEagle = 'Eagle' GolfBirdie = 'Birdie' GolfPar = 'Par' GolfBogey = 'Bogey' GolfDoubleBogey = 'Double Bogey' GolfTripleBogey = 'Triple Bogey' GolfShotDesc = {-4: GolfCondor, -3: GolfAlbatross, -2: GolfEagle, -1: GolfBirdie, 0: GolfPar, 1: GolfBogey, 2: GolfDoubleBogey, 3: GolfTripleBogey} from toontown.golf import GolfGlobals CoursesCompleted = 'Courses Completed' CoursesUnderPar = 'Courses Under Par' HoleInOneShots = 'Hole In One Shots' EagleOrBetterShots = 'Eagle Or Better Shots' BirdieOrBetterShots = 'Birdie Or Better Shots' ParOrBetterShots = 'Par Or Better Shots' MultiPlayerCoursesCompleted = 'Multiplayer Courses Completed' TwoPlayerWins = 'Two Player Wins' ThreePlayerWins = 'Three Player Wins' FourPlayerWins = 'Four Player Wins' CourseZeroWins = GolfCourseNames[0] + ' Wins' CourseOneWins = GolfCourseNames[1] + ' Wins' CourseTwoWins = GolfCourseNames[2] + ' Wins' GolfHistoryDescriptions = [CoursesCompleted, CoursesUnderPar, HoleInOneShots, EagleOrBetterShots, BirdieOrBetterShots, ParOrBetterShots, MultiPlayerCoursesCompleted, CourseZeroWins, CourseOneWins, CourseTwoWins] GolfTrophyDescriptions = [str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesCompleted][0]) + ' ' + CoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesCompleted][1]) + ' ' + CoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesCompleted][2]) + ' ' + CoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesUnderPar][0]) + ' ' + CoursesUnderPar, str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesUnderPar][1]) + ' ' + CoursesUnderPar, str(GolfGlobals.TrophyRequirements[GolfGlobals.CoursesUnderPar][2]) + ' ' + CoursesUnderPar, str(GolfGlobals.TrophyRequirements[GolfGlobals.HoleInOneShots][0]) + ' ' + HoleInOneShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.HoleInOneShots][1]) + ' ' + HoleInOneShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.HoleInOneShots][2]) + ' ' + HoleInOneShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.EagleOrBetterShots][0]) + ' ' + EagleOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.EagleOrBetterShots][1]) + ' ' + EagleOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.EagleOrBetterShots][2]) + ' ' + EagleOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.BirdieOrBetterShots][0]) + ' ' + BirdieOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.BirdieOrBetterShots][1]) + ' ' + BirdieOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.BirdieOrBetterShots][2]) + ' ' + BirdieOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.ParOrBetterShots][0]) + ' ' + ParOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.ParOrBetterShots][1]) + ' ' + ParOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.ParOrBetterShots][2]) + ' ' + ParOrBetterShots, str(GolfGlobals.TrophyRequirements[GolfGlobals.MultiPlayerCoursesCompleted][0]) + ' ' + MultiPlayerCoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.MultiPlayerCoursesCompleted][1]) + ' ' + MultiPlayerCoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.MultiPlayerCoursesCompleted][2]) + ' ' + MultiPlayerCoursesCompleted, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseZeroWins][0]) + ' ' + CourseZeroWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseZeroWins][1]) + ' ' + CourseZeroWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseZeroWins][2]) + ' ' + CourseZeroWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseOneWins][0]) + ' ' + CourseOneWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseOneWins][1]) + ' ' + CourseOneWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseOneWins][2]) + ' ' + CourseOneWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseTwoWins][0]) + ' ' + CourseTwoWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseTwoWins][1]) + ' ' + CourseTwoWins, str(GolfGlobals.TrophyRequirements[GolfGlobals.CourseTwoWins][2]) + ' ' + CourseTwoWins] GolfCupDescriptions = [str(GolfGlobals.TrophiesPerCup) + ' Trophies won', str(GolfGlobals.TrophiesPerCup * 2) + ' Trophies won', str(GolfGlobals.TrophiesPerCup * 3) + ' Trophies won'] GolfAvReceivesHoleBest = '%(name)s scored a new hole best at %(hole)s!' GolfAvReceivesCourseBest = '%(name)s scored a new course best at %(course)s!' GolfAvReceivesCup = '%(name)s receives the %(cup)s cup!! Laff point boost!' GolfAvReceivesTrophy = '%(name)s receives the %(award)s trophy!!' GolfRanking = 'Ranking: \n' GolfPowerBarText = '%(power)s%%' GolfChooseTeeInstructions = 'Press Left or Right to change tee spot.\nPress Control to select.' GolfWarningMustSwing = 'Warning: You must press Control on your next swing.' GolfAimInstructions = 'Press Left or Right to aim.\nPress and hold Control to swing.' GolferExited = '%s has left the golf course.' GolfPowerReminder = 'Hold Down Control Longer to\nHit the Ball Further' GolfPar = 'Par' GolfHole = 'Hole' GolfTotal = 'Total' GolfExitCourse = 'Exit Course' GolfUnknownPlayer = '???' GolfPageTitle = 'Golf' GolfPageTitleCustomize = 'Golf Customizer' GolfPageTitleRecords = 'Personal Best Records' GolfPageTitleTrophy = 'Golfing Trophies' GolfPageCustomizeTab = 'Customize' GolfPageRecordsTab = 'Records' GolfPageTrophyTab = 'Trophy' GolfPageTickets = 'Tickets : ' GolfPageConfirmDelete = 'Delete Accessory?' GolfTrophyTextDisplay = 'Trophy %(number)s : %(desc)s' GolfCupTextDisplay = 'Cup %(number)s : %(desc)s' GolfCurrentHistory = 'Current %(historyDesc)s : %(num)s' GolfTieBreakWinner = '%(name)s wins the random tie breaker!' GolfSeconds = ' - %(time).2f seconds' GolfTimeTieBreakWinner = '%(name)s wins the total aiming time tie breaker!!!' RoamingTrialerWeekendStart = 'Tour Toontown is starting! Free players may now enter any neighborhood!' RoamingTrialerWeekendOngoing = 'Welcome to Tour Toontown! Free players may now enter any neighborhood!' RoamingTrialerWeekendEnd = "That's all for Tour Toontown." MoreXpHolidayStart = 'Good news! Exclusive Test Toon double gag experience time has started.' MoreXpHolidayOngoing = 'Welcome! Exclusive Test Toon double gag experience time is currently ongoing.' MoreXpHolidayEnd = 'Exclusive Test Toon double gag experience time has ended. Thanks for helping us Test things!' JellybeanDayHolidayStart = "It's Jellybean Day! Get Double Jellybean rewards at Parties!" JellybeanDayHolidayEnd = "That's all for Jellybean Day. See you next year." PartyRewardDoubledJellybean = 'Double Jellybeans!' GrandPrixWeekendHolidayStart = "It's Grand Prix Weekend at Goofy Speedway! Free and paid players collect the most points in three consecutive races." GrandPrixWeekendHolidayEnd = "That's all for Grand Prix Weekend. See you next year." KartRace_DoubleTickets = 'Double Tickets' SellbotNerfHolidayStart = 'Operation: Storm Sellbot is happening now! Battle the VP today!' SellbotNerfHolidayEnd = 'Operation: Storm Sellbot has ended. Great work, Toons!' JellybeanTrolleyHolidayStart = 'Double Bean Days for Trolley Games have begun!' JellybeanTrolleyHolidayEnd = 'Double Bean Days for Trolley Games have ended!' JellybeanFishingHolidayStart = 'Double Bean Days for Fishing have begun!' JellybeanFishingHolidayEnd = 'Double Bean Days for Fishing have ended!' JellybeanPartiesHolidayStart = "It's Jellybean Week! Get Double Jellybean rewards!" JellybeanPartiesHolidayEnd = "That's all for Jellybean Week. See you next year." JellybeanMonthHolidayStart = 'Celebrate Toontown with double beans, Cattlelog items and silly surprises!' BankUpgradeHolidayStart = 'Something Toontastic happened to your Jellybean Bank!' HalloweenPropsHolidayStart = "It's Halloween in Toontown!" HalloweenPropsHolidayEnd = 'Halloween has ended. Boo!' SpookyPropsHolidayStart = 'Silly Meter spins Toontown into spooky mode!' BlackCatHolidayStart = 'Create a Black Cat - Today only!' BlackCatHolidayEnd = 'Black Cat day has ended!' SpookyBlackCatHolidayStart = 'Friday 13th means a Black Cat blast!' TopToonsMarathonStart = "The Top Toons New Year's Day Marathon has begun!" TopToonsMarathonEnd = "The Top Toons New Year's Day Marathon has ended." WinterDecorationsStart = "It's Winter Holiday time in Toontown!" WinterDecorationsEnd = 'Winter Holiday is over - Happy New Year!' WackyWinterDecorationsStart = 'Brrr! Silly Meter goes from silly to chilly!' WinterCarolingStart = 'Caroling has come to Toontown. Sing for your Snowman Head - see the Blog for details!' ExpandedClosetsStart = 'Attention Toons: For a limited time, Members can purchase the new 50 item Closet from the Cattlelog for the low price of 50 Jellybeans!' KartingTicketsHolidayStart = 'Get double tickets from Practice races at Goofy Speedway today!' IdesOfMarchStart = 'Toons go GREEN!' LogoutForced = 'You have done something wrong\n and are being logged out automatically,\n additionally your account may be frozen.\n Try going on a walk outside, it is fun.' CountryClubToonEnterElevator = '%s \nhas jumped in the golf kart.' CountryClubBossConfrontedMsg = '%s is battling the Club President!' CountryClubFloorNum2Name = ['First Hole', 'Second Hole', 'Third Hole', 'Fourth Hole', 'Fifth Hole', 'Sixth Hole', 'Seventh Hole', 'Eighth Hole', 'Ninth Hole'] ElevatorBlockedRoom = 'All challenges must be defeated first.' MolesLeft = 'Moles Left: %d' MolesInstruction = 'Mole Stomp!\nJump on the red moles!' MolesFinished = 'Mole Stomp successful!' MolesPityWin = 'Stomp Failed! But the moles left.' MolesRestarted = 'Stomp Failed! Restarting...' BustACogInstruction = 'Remove the cog ball!' BustACogExit = 'Exit for Now' BustACogHowto = 'How to Play' BustACogFailure = 'Out of Time!' BustACogSuccess = 'Success!' GolfGreenGameScoreString = 'Puzzles Left: %s' GolfGreenGamePlayerScore = 'Solved %s' GolfGreenGameBonusGag = 'You won %s!' GolfGreenGameGotHelp = '%s solved a Puzzle!' GolfGreenGameDirections = 'Shoot balls using the the mouse\n\n\nMatching three of a color causes the balls to fall\n\n\nRemove all Cog balls from the board' enterHedgeMaze = 'Race through the Hedge Maze\n for a laff bonus!' toonFinishedHedgeMaze = '%s \n finished in %s place!' hedgeMazePlaces = ['first', 'second', 'third', 'Fourth'] mazeLabel = 'Maze Race!' BoardingPartyReadme = 'Boarding Group?' BoardingGroupHide = 'Hide' BoardingGroupShow = 'Show Boarding Group' BoardingPartyInform = 'Create an elevator Boarding Group by clicking on another Toon and Inviting them.\nIn this area Boarding Groups cannot have more than %s Toons.' BoardingPartyTitle = 'Boarding Group' QuitBoardingPartyLeader = 'Disband' QuitBoardingPartyNonLeader = 'Leave' QuitBoardingPartyConfirm = 'Are you sure you want to quit this Boarding Group?' BoardcodeMissing = 'Something went wrong; try again later.' BoardcodeMinLaffLeader = 'Your group cannot board because you have less than %s laff points.' BoardcodeMinLaffNonLeaderSingular = 'Your group cannot board because %s has less than %s laff points.' BoardcodeMinLaffNonLeaderPlural = 'Your group cannot board because %s have less than %s laff points.' BoardcodePromotionLeader = 'Your group cannot board because you do not have enough promotion merits.' BoardcodePromotionNonLeaderSingular = 'Your group cannot board because %s does not have enough promotion merits.' BoardcodePromotionNonLeaderPlural = 'Your group cannot board because %s do not have enough promotion merits.' BoardcodeSpace = 'Your group cannot board because there is not enough space.' BoardcodeBattleLeader = 'Your group cannot board because you are in battle.' BoardcodeBattleNonLeaderSingular = 'Your group cannot board because %s is in battle.' BoardcodeBattleNonLeaderPlural = 'Your group cannot board because %s are in battle.' BoardingInviteMinLaffInviter = 'You need %s Laff Points before being a member of this Boarding Group.' BoardingInviteMinLaffInvitee = '%s needs %s Laff Points before being a member of this Boarding Group.' BoardingInvitePromotionInviter = 'You need to earn a promotion before being a member of this Boarding Group.' BoardingInvitePromotionInvitee = '%s needs to earn a promotion before being a member of this Boarding Group.' BoardingInviteNotPaidInvitee = '%s needs to be a paid Member to be a part of your Boarding Group.' BoardingInviteeInDiffGroup = '%s is already in a different Boarding Group.' BoardingInviteeInKickOutList = '%s had been removed by your leader. Only the leader can re-invite removed members.' BoardingInviteePendingIvite = '%s has a pending invite; try again later.' BoardingInviteeInElevator = '%s is currently busy; try again later.' BoardingInviteGroupFull = 'Your Boarding Group is already full.' BoardingAlreadyInGroup = 'You cannot accept this invitation because you are part of another Boarding Group.' BoardingGroupAlreadyFull = 'You cannot accept this invitation because the group is already full.' BoardingKickOutConfirm = 'Are you sure you want to remove %s?' BoardingPendingInvite = 'You need to deal with the\n pending invitation first.' BoardingCannotLeaveZone = 'You cannot leave this area because you are part of a Boarding Group.' BoardingInviteeMessage = '%s would like you to join their Boarding Group.' BoardingInvitingMessage = 'Inviting %s to your Boarding Group.' BoardingInvitationRejected = '%s has rejected to join your Boarding Group.' BoardingMessageKickedOut = 'You have been removed from the Boarding Group.' BoardingMessageInvited = '%s has invited %s to the Boarding Group.' BoardingMessageLeftGroup = '%s has left the Boarding Group.' BoardingMessageGroupDissolved = 'Your Boarding Group was disbanded by the group leader.' BoardingMessageGroupDisbandedGeneric = 'Your Boarding Group was disbanded.' BoardingMessageInvitationFailed = '%s tried to invite you to their Boarding Group.' BoardingMessageGroupFull = '%s tried to accept your invitation but your group was full.' BoardingGo = 'GO' BoardingCancelGo = 'Click Again to\nCancel Go' And = 'and' BoardingGoingTo = 'Going To:' BoardingTimeWarning = 'Boarding the elevator in ' BoardingMore = 'more' BoardingGoShow = 'Going to\n%s in ' BoardingGoPreShow = 'Confirming...' BossbotBossName = 'C.E.O.' BossbotRTWelcome = 'You toons will need different disguises.' BossbotRTRemoveSuit = 'First take off your cog suits...' BossbotRTFightWaiter = 'and then fight these waiters.' BossbotRTWearWaiter = "Good Job! Now put on the waiters' clothes." BossbotBossPreTwo1 = "What's taking so long? " BossbotBossPreTwo2 = 'Get cracking and serve my banquet!' BossbotRTServeFood1 = 'Hehe, serve the food I place on these conveyor belts.' BossbotRTServeFood2 = 'If you serve a cog three times in a row it will explode.' BossbotResistanceToonName = "Good ol' Gil Giggles" BossbotPhase3Speech1 = "What's happening here?!" BossbotPhase3Speech2 = 'These waiters are toons!' BossbotPhase3Speech3 = 'Get them!!!' BossbotPhase4Speech1 = 'Hrrmmpph. When I need a job done right...' BossbotPhase4Speech2 = "I'll do it myself." BossbotRTPhase4Speech1 = 'Good Job! Now squirt the C.E.O. with the water on the tables...' BossbotRTPhase4Speech2 = 'or use golf balls to slow him down.' BossbotPitcherLeave = 'Leave Bottle' BossbotPitcherLeaving = 'Leaving Bottle' BossbotPitcherAdvice = 'Use the left and right keys to rotate.\nHold down Ctrl increase power.\nRelease Ctrl to fire.' BossbotGolfSpotLeave = 'Leave Golf Ball' BossbotGolfSpotLeaving = 'Leaving Golf Ball' BossbotGolfSpotAdvice = 'Use the left and right keys to rotate.\nCtrl to fire.' BossbotRewardSpeech1 = "No! The Chairman won't like this." BossbotRewardSpeech2 = 'Arrrggghhh!!!!' BossbotRTCongratulations = "You did it! You've demoted the C.E.O.!\x07Here, take these pink slips the C.E.O. left behind.\x07With it you'll be able to fire Cogs in a battle." BossbotRTLastPromotion = "\x07Wow, you've reached level %s on your Cog Suit!\x07Cogs don't get promoted higher than that.\x07You can't upgrade your Cog Suit anymore, but you can certainly keep working for the Resistance!" BossbotRTHPBoost = "\x07You've done a lot of work for the Resistance.\x07The Toon Council has decided to give you another Laff point. Congratulations!" BossbotRTMaxed = '\x07I see that you have a level %s Cog Suit. Very impressive!\x07On behalf of the Toon Council, thank you for coming back to defend more Toons!' GolfAreaAttackTaunt = 'Fore!' OvertimeAttackTaunts = ["It's time to reorganize.", "Now let's downsize."] ElevatorBossBotBoss = 'C.E.O Battle' ElevatorBossBotCourse0 = 'The Front Three' ElevatorBossBotCourse1 = 'The Middle Six' ElevatorBossBotCourse2 = 'The Back Nine' ElevatorCashBotBoss = 'C.F.O Battle' ElevatorCashBotMint0 = 'Coin Mint' ElevatorCashBotMint1 = 'Dollar Mint' ElevatorCashBotMint2 = 'Bullion Mint' ElevatorSellBotBoss = 'Senior V.P Battle' ElevatorSellBotFactory0 = 'Front Entrance' ElevatorSellBotFactory1 = 'Side Entrance' ElevatorLawBotBoss = 'Chief Justice Battle' ElevatorLawBotCourse0 = 'Office A' ElevatorLawBotCourse1 = 'Office B' ElevatorLawBotCourse2 = 'Office C' ElevatorLawBotCourse3 = 'Office D' DaysToGo = 'Wait\n%s Days' IceGameTitle = 'Ice Slide' IceGameInstructions = 'Get as close to the center by the end of the second round. Use arrow keys to change direction and force. Press Ctrl to launch your toon. Hit barrels for extra points and avoid the TNT!' IceGameInstructionsNoTnt = 'Get as close to the center by the end of the second round. Use arrow keys to change direction and force. Press Ctrl to launch your toon. Hit barrels for extra points.' IceGameWaitingForPlayersToFinishMove = 'Waiting for other players...' IceGameWaitingForAISync = 'Waiting for other players...' IceGameInfo = 'Match %(curMatch)d/%(numMatch)d, Round %(curRound)d/%(numRound)d' IceGameControlKeyWarning = 'Remember to press the Ctrl key!' PicnicTableJoinButton = 'Join' PicnicTableObserveButton = 'Observe' PicnicTableCancelButton = 'Cancel' PicnicTableTutorial = 'How To Play' PicnicTableMenuTutorial = 'What game do you want to learn?' PicnicTableMenuSelect = 'What game do you want to play?' ChineseCheckersGetUpButton = 'Get Up' ChineseCheckersStartButton = 'Start Game' ChineseCheckersQuitButton = 'Quit Game' ChineseCheckersIts = "It's " ChineseCheckersYourTurn = 'Your Turn' ChineseCheckersGreenTurn = "Green's Turn" ChineseCheckersYellowTurn = "Yellow's Turn" ChineseCheckersPurpleTurn = "Purple's Turn" ChineseCheckersBlueTurn = "Blue's Turn" ChineseCheckersPinkTurn = "Pink's Turn" ChineseCheckersRedTurn = "Red's Turn" ChineseCheckersColorG = 'You are Green' ChineseCheckersColorY = 'You are Yellow' ChineseCheckersColorP = 'You are Purple' ChineseCheckersColorB = 'You are Blue' ChineseCheckersColorPink = 'You are Pink' ChineseCheckersColorR = 'You are Red' ChineseCheckersColorO = 'You are Observing' ChineseCheckersYouWon = 'You just won a game of Chinese Checkers!' ChineseCheckers = 'Chinese Checkers.' ChineseCheckersGameOf = ' has just won a game of ' ChineseTutorialTitle1 = 'Objective' ChineseTutorialTitle2 = 'How to Play' ChineseTutorialPrev = 'Previous Page' ChineseTutorialNext = 'Next Page' ChineseTutorialDone = 'Done' ChinesePage1 = 'The goal of Chinese Checkers is to be the first player to move all of your marbles from the bottom triangle across the board and into the triangle at the top. The first player to do so wins!' ChinesePage2 = 'Players take turns moving any marble of their own color. A marble can move into an adjacent hole or it can hop over other marbles. Hops must go over a marble and end in an empty hole. It is possible to chain hops together for longer moves!' CheckersPage1 = 'The goal of Checkers is to leave the opponent without any possible moves. To do this you can either capture all of his peices or block them in such that he has no available moves.' CheckersPage2 = 'Players take turns moving any peice of their own color. A peice can move one square diagonal and forward. A peice can only move into a square that is not occupied by another peice. Kings follow the same rules but are allowed to move backwards.' CheckersPage3 = 'To capture an opponents peice your peice must jump over it diagonally into the vacant square beyond it. If you have any jump moves during a turn, you must do one of them. You can chain jump moves together as long as it is with the same peice.' CheckersPage4 = 'A peice becomes a king when it reaches the last row on the board. A peice that has just become a king cannot continue jumping until the next turn. Additionally, kings are allowed to move all directions and are allowed to change directions while jumping.' CheckersGetUpButton = 'Get Up' CheckersStartButton = 'Start Game' CheckersQuitButton = 'Quit Game' CheckersIts = "It's " CheckersYourTurn = 'Your Turn' CheckersWhiteTurn = "White's Turn" CheckersBlackTurn = "Black's Turn" CheckersColorWhite = 'You are White' CheckersColorBlack = 'You are Black' CheckersObserver = 'You are Observing' RegularCheckers = 'Checkers.' RegularCheckersGameOf = ' has just won a game of ' RegularCheckersYouWon = 'You just won a game of Checkers!' MailNotifyNewItems = "You've got mail!" MailNewMailButton = 'Mail' MailSimpleMail = 'Note' MailFromTag = 'Note From: %s' AwardNotifyNewItems = 'You have a new award in your mailbox!' AwardNotifyOldItems = 'There are still awards waiting in your mailbox for you to pick up!' InviteInvitation = 'the invitation' InviteAcceptInvalidError = 'The invitation is no longer valid.' InviteAcceptPartyInvalid = 'That party has been cancelled.' InviteAcceptAllOk = 'The host has been informed of your reply.' InviteRejectAllOk = 'The host has been informed that you declined the invitation.' Months = {1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH', 4: 'APRIL', 5: 'MAY', 6: 'JUNE', 7: 'JULY', 8: 'AUGUST', 9: 'SEPTEMBER', 10: 'OCTOBER', 11: 'NOVEMBER', 12: 'DECEMBER'} DayNames = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') DayNamesAbbrev = ('MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN') HolidayNamesInCalendar = {1: ('Summer Fireworks', 'Celebrate Summer with a fireworks show every hour in each playground!'), 2: ('New Year Fireworks', 'Happy New Year! Enjoy a fireworks show every hour in each playground!'), 3: ('Bloodsucker Invasion', 'Help defend Toontown from the Bloodsucker invasion!'), 4: ('Winter Holiday', 'Celebrate the Winter Holiday with Toontastic decorations, party and Cattlelog items, and more!'), 5: ('Skelecog Invasion', 'Stop the Skelecogs from invading Toontown!'), 6: ('Mr. Hollywood Invasion', 'Stop the Mr. Hollywood Cogs from invading Toontown!'), 7: ('Fish Bingo', 'Fish Bingo Wednesday! Everyone at the pond works together to complete the card before time runs out.'), 8: ('Toon Species Election', 'Vote on the new Toon species! Will it be Goat? Will it be Pig?'), 9: ('Black Cat Day', 'Happy Halloween! Create a Toontastic Black Cat Toon - Today Only!'), 13: ('Trick or Treat', 'Happy Halloween! Trick or treat throughout Toontown to get a nifty Halloween pumpkin head reward!'), 14: ('Grand Prix', 'Grand Prix Monday at Goofy Speedway! To win, collect the most points in three consecutive races!'), 16: ('Grand Prix Weekend', 'Free and Paid players compete in circuit races at Goofy Speedway!'), 17: ('Trolley Tracks', 'Trolley Tracks Thursday! Board any Trolley with two or more Toons to play.'), 19: ('Silly Saturdays', 'Saturdays are silly with Fish Bingo and Grand Prix throughout the day!'), 24: ('Ides of March', 'Beware the Ides of March! Stop the Backstabber Cogs from invading Toontown!'), 26: ('Halloween Decor', 'Celebrate Halloween as spooky trees and streetlights transform Toontown!'), 28: ('Winter Invasion', 'The sellbots are on the loose spreading their cold sales tactics!'), 29: ("April Toons' Week", "Celebrate April Toons' Week - a holiday built by Toons for Toons!"), 33: ('Sellbot Surprise 1', 'Sellbot Surprise! Stop the Cold Caller Cogs from invading Toontown!'), 34: ('Sellbot Surprise 2', 'Sellbot Surprise! Stop the Name Dropper Cogs from invading Toontown!'), 35: ('Sellbot Surprise 3', 'Sellbot Surprise! Stop the Gladhander Cogs from invading Toontown!'), 36: ('Sellbot Surprise 4', 'Sellbot Surprise! Stop the Mover & Shaker Cogs from invading Toontown!'), 37: ('A Cashbot Conundrum 1', 'A Cashbot Conundrum. Stop the Short Change Cogs from invading Toontown!'), 38: ('A Cashbot Conundrum 2', 'A Cashbot Conundrum. Stop the Penny Pincher Cogs from invading Toontown!'), 39: ('A Cashbot Conundrum 3', 'A Cashbot Conundrum. Stop the Bean Counter Cogs from invading Toontown!'), 40: ('A Cashbot Conundrum 4', 'A Cashbot Conundrum. Stop the Number Cruncher Cogs from invading Toontown!'), 41: ('The Lawbot Gambit 1', 'The Lawbot Gambit. Stop the Bottomfeeder Cogs from invading Toontown!'), 42: ('The Lawbot Gambit 2', 'The Lawbot Gambit. Stop the Double Talker Cogs from invading Toontown!'), 43: ('The Lawbot Gambit 3', 'The Lawbot Gambit. Stop the Ambulance Chaser Cogs from invading Toontown!'), 44: ('The Lawbot Gambit 4', 'The Lawbot Gambit. Stop the Backstabber Cogs from invading Toontown!'), 45: ('The Trouble With Bossbots 1', 'The Trouble with Bossbots. Stop the Flunky Cogs from invading Toontown!'), 46: ('The Trouble With Bossbots 2', 'The Trouble with Bossbots. Stop the Pencil Pusher Cogs from invading Toontown!'), 47: ('The Trouble With Bossbots 3', 'The Trouble with Bossbots. Stop the Micromanager Cogs from invading Toontown!'), 48: ('The Trouble With Bossbots 4', 'The Trouble with Bossbots. Stop the Downsizer Cogs from invading Toontown!'), 49: ('Jellybean Day', 'Celebrate Jellybean Day with double Jellybean rewards at parties!'), 53: ('Cold Caller Invasion', 'Stop the Cold Caller Cogs from invading Toontown!'), 54: ('Bean Counter Invasion', 'Stop the Bean Counter Cogs from invading Toontown!'), 55: ('Double Talker Invasion', 'Stop the Double Talker Cogs from invading Toontown!'), 56: ('Downsizer Invasion', 'Stop the Downsizer Cogs from invading Toontown!'), 57: ('Caroling', 'Sing for your Snowman Head! See the Blog for details!'), 59: ("ValenToon's Day", "Celebrate ValenToon's Day from Feb 09 to Feb 16!"), 72: ('Yes Men Invasion', 'Stop the Yes Men Cogs from invading Toontown!'), 73: ('Tightwad Invasion', 'Stop the Tightwad Cogs from invading Toontown!'), 74: ('Telemarketers Invasion', 'Stop the Telemarketer Cogs from invading Toontown!'), 75: ('Head Hunter Invasion', 'Stop the Head Hunter Cogs from invading Toontown!'), 76: ('Spin Doctor Invasion', 'Stop the Spin Doctor Cogs from invading Toontown!'), 77: ('Moneybags Invasion', 'Stop the Moneybags from invading Toontown!'), 78: ('Two-faces Invasion', 'Stop the Two-faces from invading Toontown!'), 79: ('Mingler Invasion', 'Stop the Mingler Cogs from invading Toontown!'), 80: ('Loan Shark Invasion', 'Stop the Loanshark Cogs from invading Toontown!'), 81: ('Corporate Raider Invasion', 'Stop the Corporate Raider Cogs from invading Toontown!'), 82: ('Robber Baron Invasion', 'Stop the Robber Baron Cogs from invading Toontown!'), 83: ('Legal Eagle Invasion', 'Stop the Legal Eagle Cogs from invading Toontown!'), 84: ('Big Wig Invasion', 'Stop the Big Wig Cogs from invading Toontown!'), 85: ('Big Cheese Invasion', 'Stop the Big Cheese from invading Toontown!'), 86: ('Down Sizer Invasion', 'Stop the Down Sizer Cogs from invading Toontown!'), 87: ('Mover And Shaker Invasion', 'Stop the Mover and Shaker Cogs from invading Toontown!'), 88: ('Double Talker Invasion', 'Stop the Double Talkers Cogs from invading Toontown!'), 89: ('Penny Pincher Invasion', 'Stop the Penny Pinchers Cogs from invading Toontown!'), 90: ('Name Dropper Invasion', 'Stop the Name Dropper Cogs from invading Toontown!'), 91: ('Ambulance Chaser Invasion', 'Stop the Ambulance Chaser Cogs from invading Toontown!'), 92: ('Micro Manager Invasion', 'Stop the Micro Manager Cogs from invading Toontown!'), 93: ('Number Cruncher Invasion', 'Stop the Number Cruncher Cogs from invading Toontown!'), 95: ('Victory Parties', 'Celebrate our historic triumph against the Cogs!'), 96: ('Operation: Storm Sellbot', "Sellbot HQ is open to everyone. Let's go fight the VP!"), 97: ('Double Bean Days - Trolley Games', ''), 98: ('Double Bean Days - Fishing', ''), 99: ('Jellybean Week', 'Celebrate Jellybean Week with double Jellybean rewards!'), 101: ("Top Toons New Year's Day Marathon", "Chances to win every hour! See the What's New Blog for details!"), 105: ('Toons go GREEN!', 'Toons make a green scene at Green Bean Jeans on Oak Street in Daisy Gardens!')} UnknownHoliday = 'Unknown Holiday %d' HolidayFormat = '%b %d ' TimeZone = 'US/Pacific' HourFormat = '12' CogdoMemoGuiTitle = 'Memos:' CogdoMemoNames = 'Barrel-Destruction Memos' CogdoStomperName = 'Stomp-O-Matic' CogdoBarrelRoomTitle = 'Stomper Room' CogdoBarrelIntroMovieDialogue = 'Good work! You\'ve halted the %s and are now able to collect some of the stolen Laff Barrels, but make sure to hurry before the Cogs come!' % CogdoStomperName BoardroomGameTitle = 'Boardroom Hijinks' BoardroomGameInstructions = 'The COGS are having a meeting to decide what to do with stolen gags. Slide on through and grab as many gag-destruction memos as you can!' CogdoCraneGameTitle = 'Vend-A-Stomper' CogdoCraneGameInstructions = 'The COGS are using a coin-operated machine to destroy Laff Barrels. Use the cranes to pick up and throw money bags, in order to prevent barrel destruction!' CogdoMazeGameTitle = 'Mover & Shaker\nField Office' CogdoMazeGameInstructions = 'The big Mover & Shaker Cogs have the code to open the door. Defeat them with your water balloons in order to get it!' CogdoMazeIntroMovieDialogue = (("This is the Toon Resistance! The Movers & Shakers\nhave our Jokes, and they've locked the exit!",), ('Grab water balloons at coolers, and throw them at Cogs!\nSmall Cogs drop Jokes, BIG COGS open the exit.',), ('The more Jokes you rescue, the bigger your Toon-Up\nat the end. Good luck!',)) CogdoMazeGameDoorOpens = 'THE EXIT IS OPEN FOR 60 SECONDS!\nGET THERE FAST FOR A BIGGER TOON-UP' CogdoMazeGameLocalToonFoundExit = "The exit will open when\nyou've busted all four BIG COGS!" CogdoMazeGameWaitingForToons = 'Please wait...' CogdoMazeGameTimeOut = 'Oh no, time ran out! You lost your jokes.' CogdoMazeGameTimeAlert = 'Hurry up! 60 seconds to go!' CogdoMazeGameBossGuiTitle = 'BIG COGS:' CogdoMazeFindHint = 'Find a Water Cooler' CogdoMazeThrowHint = "Press 'Ctrl' to throw your water balloon" CogdoMazeSquashHint = 'Falling objects pop your balloon' CogdoMazeBossHint = 'Big Cogs take TWO hits to defeat' CogdoMazeMinionHint = 'Smaller Cogs drop jokes' CogdoFlyingGameTitle = 'Legal Eagle\nField Office' CogdoFlyingGameInstructions = "Fly through the Legal Eagles' lair. Watch out for obstacles and Cogs along the way, and don't forget to refuel your helicopter!" CogdoFlyingIntroMovieDialogue = (("You won't ruffle our feathers, Toon! We're destroying barrels of your Laff, and you cannot stop us!", "A Toon! We're crushing barrels of your Laff in our %s, and there's nothing you can do about it!" % CogdoStomperName, "You can't egg us on, Toon! We're powering our offices with your Laff, and you're powerless to stop us!"), ('This is the Toon Resistance! A little bird told me you can use propellers to fly around, grab Barrel Destruction Memos, and keep Laff from being destroyed! Good luck!', 'Attention! Wing it with a propeller and collect Barrel Destruction Memos to keep our Laff from being stomped! Toon Resistance out!', 'Toon Resistance here! Cause a flap by finding propellers, flying to the Barrel Destruction Memos, and keeping our Laff from being smashed! Have fun!'), ("Squawk! I'm a Silver Sprocket Award winner, I don't need this!", 'Do your best! You will find us to be quite talon-ted!', "We'll teach you to obey the pecking order, Toon!")) CogdoFlyingGameWaiting = 'Please wait%s' CogdoFlyingGameFuelLabel = 'Fuel' CogdoFlyingGameLegalEagleTargeting = 'A Legal Eagle has noticed you!' CogdoFlyingGameLegalEagleAttacking = 'Incoming Eagle!' CogdoFlyingGameInvasionTargeting = 'A %s has noticed you!' CogdoFlyingGameInvasionAttacking = 'Incoming %s!' CogdoFlyingGamePickUpAPropeller = 'You need a propeller to fly!' CogdoFlyingGamePressCtrlToFly = "Press 'Ctrl' to fly up!" CogdoFlyingGameYouAreInvincible = 'Red Tape protects you!' CogdoFlyingGameTimeIsRunningOut = 'Time is running out!' CogdoFlyingGameMinimapIntro = 'This meter shows your progress!\nX marks the finish line.' CogdoFlyingGameMemoIntro = 'Memos prevent Laff Barrels in\nthe Stomper Room from being destroyed!' CogdoFlyingGameOutOfTime = 'Oh No! You ran out of time!' CogdoFlyingGameYouMadeIt = 'You made it on time!' CogdoFlyingGameYouMadeIt = 'Good work, you made it on time!' CogdoFlyingGameTakingMemos = 'The Legal Eagles took all your memos!' CogdoFlyingGameTakingMemosInvasion = 'The %s took all your memos!' CogdoElevatorRewardLaff = 'Great job!\nYou get a Toon-Up from the jokes you saved!' CogdoExecutiveSuiteTitle = 'Executive Suite' CogdoExecutiveSuiteIntroMessage = "Oh no, they've got the shop keeper!\nDefeat the Cogs and free the captive." CogdoExecutiveSuiteToonThankYou = 'Thanks for the rescue!\nIf you need help in a fight, use this SOS card to call my friend %s.' CogdoLawbotExecutiveSuiteToonThankYou = "Thanks for the rescue!\nIt seems the Cogs didn't leave behind the key to the Sprocket Award case.\x07Instead, use these summons I found laying around. You can summon Cogs with them!" CogdoExecutiveSuiteToonBye = 'Bye!' SillySurgeTerms = {1: 'Amusing Ascent!', 2: 'Silly Surge!', 3: 'Ridiculous Rise!', 4: 'Giggle Growth!', 5: 'Funny Fueling!', 6: 'Batty Boost!', 7: 'Crazy Climb!', 8: 'Jolly Jump!', 9: 'Loony Lift!', 10: 'Hilarity Hike!', 11: 'Insanity Increase!', 12: 'Cracked-Uptick!'} InteractivePropTrackBonusTerms = {0: 'Super Toon-Up!', 1: '', 2: '', 3: '', 4: 'Super Throw!', 5: 'Super Squirt!', 6: '', 7: ''} PlayingCardUnknown = 'Card Name is unknown' RemapPrompt = 'Choose the keys you wish to remap.' RemapPopup = 'Press the key you wish to remap this control to.' Controls = ['Move Up:', 'Move Left:', 'Move Down:', 'Move Right:', 'Jump:', 'Action Key:', 'Options Hotkey:', 'Chatbox Hotkey:', 'Screenshot Key:']
silly-wacky-3-town-toon/SOURCE-COD
toontown/toonbase/TTLocalizerEnglish.py
Python
apache-2.0
503,899
[ "Amber", "BLAST", "Brian", "CRYSTAL", "MOE", "Octopus", "SIESTA", "VisIt" ]
8a3bd3f4501598e66984ed646cfe02cd7e0e536975c4df8fb8c2ba3310e9aa31
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import sys import unittest import subprocess from TestHarnessTestCase import TestHarnessTestCase class TestHarnessTester(TestHarnessTestCase): @unittest.skipIf(sys.platform == 'linux' and sys.version_info[0] == 3 and sys.version_info[1] < 7, "Python 3.6 print doesn't handle \xb1 on linux") def testCSVValidationTester(self): """ Test for correct operation of CSV validation tester """ with self.assertRaises(subprocess.CalledProcessError) as cm: self.runTests('-i', 'csv_validation_tester', '--no-color').decode('utf-8') e = cm.exception output = e.output.decode('utf-8') self.assertRegexpMatches(output, r'test_harness\.csv_validation_tester_01.*?OK') self.assertRegexpMatches(output, r'test_harness\.csv_validation_tester_02.*?FAILED \(DIFF\)') @unittest.skipIf(sys.platform == 'linux' and sys.version_info[0] == 3 and sys.version_info[1] < 7, "Python 3.6 print doesn't handle \xb1 on linux") def testCSVValidationTesterVerbose(self): """ Test for correct operation of CSV validation tester in verbose mode """ with self.assertRaises(subprocess.CalledProcessError) as cm: self.runTests('-i', 'csv_validation_tester', '--verbose', '--no-color').decode('utf-8') e = cm.exception output = e.output.decode('utf-8') self.assertRegexpMatches(output, 'csv_validation_tester_01.csv | 0.00 \xb1 0.01 | 0.01 \xb1 0.01') self.assertRegexpMatches(output, 'csv_validation_tester_02.csv | 0.00 \xb1 0.01 | 0.01 \xb1 0.00')
harterj/moose
python/TestHarness/tests/test_CSVValidationTester.py
Python
lgpl-2.1
1,959
[ "MOOSE" ]
e305422e440a75296daeb7675e136e9728f23d0deeae8fa1a1caa3561234e9b3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # LAMMPS documentation build configuration file, created by # sphinx-quickstart on Sat Sep 6 14:20:08 2014. # # This file is execfile()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. import sys import os # 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(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # 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.mathjax', 'sphinxcontrib.images', ] images_config = { 'default_image_width' : '25%', 'default_group' : 'default' } # 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 = 'Manual' # General information about the project. project = 'LAMMPS' copyright = '2013 Sandia Corporation' def get_lammps_version(): import os script_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(script_dir, '../../../src/version.h'), 'r') as f: line = f.readline() start_pos = line.find('"')+1 end_pos = line.find('"', start_pos) return line[start_pos:end_pos] # 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. version = get_lammps_version() # The full version, including alpha/beta/rc tags. release = '' # 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'] # 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 = True # 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 = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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 = 'lammps_theme' # 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 = {} # 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 = "LAMMPS documentation" # 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 = None # 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 = None # 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 = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # 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 = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # 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 # If false, no index is generated. #html_use_index = 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 = False # 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'LAMMPSdoc' html_add_permalinks = '' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('Manual', 'LAMMPS.tex', 'LAMMPS Documentation', 'Steve Plimpton', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # 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 # If true, show URL addresses after external links. #latex_show_urls = False # 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 = [ ('Manual', 'liggghts', 'LAMMPS Documentation', ['Steve Plimpton'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('Manual', 'LAMMPS', 'LAMMPS Documentation', 'LAMMPS', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for ePUB output ---------------------------------------------- epub_title = 'LAMMPS Documentation - ' + get_lammps_version() epub_cover = ('lammps-logo.png', '') epub_description = """ This is the Manual for the LAMMPS software package. LAMMPS stands for Large-scale Atomic/Molecular Massively Parallel Simulator and is a classical molecular dynamics simulation code designed to run efficiently on parallel computers. It was developed at Sandia National Laboratories, a US Department of Energy facility, with funding from the DOE. It is an open-source code, distributed freely under the terms of the GNU Public License (GPL). The primary author of the code is Steve Plimpton, who can be emailed at sjplimp@sandia.gov. The LAMMPS WWW Site at lammps.sandia.gov has more information about the code and its uses. """ epub_author = 'The LAMMPS Developers' # configure spelling extension if present import importlib.util spelling_spec = importlib.util.find_spec("sphinxcontrib.spelling") if spelling_spec: extensions.append('sphinxcontrib.spelling') spelling_lang='en_US' spelling_word_list_filename='false_positives.txt'
ovilab/atomify-lammps
libs/lammps/doc/utils/sphinx-config/conf.py
Python
gpl-3.0
9,820
[ "LAMMPS" ]
a873b1d1e77772918f6dd33c3135e2fddf550682ff7fbb4b8af529874fd6bc69