def interpreteInputParameters(self): """Parse the input parameters for the analysis. """ # Parses the parameters that are common to different analysis. Analysis.interpreteInputParameters(self) # The 'temperature' input parameter. It must be a float or a value convertible to a float > 0. # Must be a float or convertible to a float. try: self.temperature = float(self.parameters['temperature']) # The value can not be converted to a float. except ValueError: raise Error('Error when parsing "temperature" parameter: must be a float or a value convertible to a float.') else: # Must > 0. if self.temperature <= 0.0: raise Error('Error when parsing "temperature" parameter: must be > 0.') self.buildTimeInfo() self.subset = self.selectAtoms(self.subsetDefinition) self.nSelectedAtoms = len(self.subset) self.mask = N.zeros(self.universe.numberOfAtoms(), typecode = N.Int0) for aIndex in self.subset: self.mask[aIndex] = 1
def testAnalysis(option, opt_str, value, parser): """ """ if len(parser.rargs) == 0: raise Error('No arguments for %s option.' % option) if 'ALL' in parser.rargs: selectedTests = availableTests else: selectedTests = parser.rargs for n in selectedTests: try: t = eval(n.strip().upper() + 'Tests()') except NameError: LogMessage('error', '%s test is not a valid analysis benchmark name.' % n, ['console']) else: try: t.run() except: raise Error('An error occured when running %s test.' % n) else: LogMessage('info', t.summary, ['console']) sys.exit(0)
def Generate_QShells(qShells): genQShells = [] if isinstance(qShells, (list, tuple)): genQShells = qShells elif isinstance(qShells, str): for qInter in [v.strip() for v in qShells.split(";")]: qMin, qMax, dQ = [float(v) for v in qInter.split(":")] temp = N.arange(qMin, qMax + 0.001 * dQ, dQ).tolist() if temp[-1] > qMax: del temp[-1] genQShells.extend(temp) else: raise Error("%s: invalid format for qshells." % genQShells) genQShells = [v for v in sorted(set(genQShells)) if v > 0.0] if len(genQShells) == 0: raise Error("%s triggered emptry qshells generation." % genQShells) return genQShells
def interpreteInputParameters(self): """Parse the input parameters for the analysis. """ # Parses the parameters that are common to different analysis. Analysis.interpreteInputParameters(self) self.buildTimeInfo() if (self.referenceFrame < 0) or (self.referenceFrame > len( self.trajectory)): self.referenceFrame = 0 LogMessage( 'warning', 'The reference frame must be an integer in [1,%s].\n\ It will be set to 1 for the running analysis.' % len(self.trajectory), ['console']) # The 'wignerindexes' input parameter. It must be string of the form j,m,n where j, m and n are the Wigner # indexes. if isinstance(self.parameters['wignerindexes'], str): # Must be a string of three comma-separated integers. try: j, m, n = [ int(v) for v in self.parameters['wignerindexes'].split(',') ] except: raise Error( 'Error when parsing "wignerindexes" parameter: must be a string of the form "j,m,n".' ) else: if j < 0: raise Error( 'Error when parsing "wignerindexes" parameter: j must be >= 0.' ) if m > j: raise Error( 'Error when parsing "wignerindexes" parameter: m must be <= j.' ) if abs(n) > m: raise Error( 'Error when parsing "wignerindexes" parameter: n must be <= n.' ) self.wignerIndexes = (j, m, n) self.group = self.selectGroups(self.groupDefinition) self.nGroups = len(self.group) if self.architecture != 'monoprocessor': # The attribute trajectory is removed because it can not be pickled by Pyro. delattr(self, 'trajectory')
def validate(self): # An intput file must have been set. self.inputFile = self.inputFileBrowser.getValue() if not self.inputFile: raise Error('Please enter an ASCII input file.') self.outputFile = self.outputFileBrowser.getValue() # An output file must have been set. if not self.outputFile: raise Error('Please enter a NetCDF output file.') return True
def validate(self): if not self.trajectory: raise Error('No MMTK trajectory file loaded for animation.') if self.trajectory != self.fileBrowser.getValue(): raise Error( 'Mismatch between the loaded trajectory and the displayed MMTK trajectory file name.\ You should validate that file by pressing Return on its corresponding entry.') self.viewableAtoms = self.trajectory.universe.atomsWithDefinedPositions( ) if not self.firstStepEntry.getValue(): self.first = 0 LogMessage( 'warning', 'First frame undefined. Frame 1 will be taken by default.', ['gui']) else: self.first = self.firstStepEntry.getValue() - 1 if self.first < 0: raise Error('First frame not within [1,%d].' % len(self.trajectory)) if not self.lastStepEntry.getValue(): self.last = 1 LogMessage( 'warning', 'Last frame undefined. Frame 1 will be taken by default.', ['gui']) else: self.last = self.lastStepEntry.getValue() if self.last > len(self.trajectory): raise Error('Last frame not within [1,%d].' % len(self.trajectory)) if not self.skipStepEntry.getValue(): self.skip = 1 LogMessage('warning', 'Frame skip undefined. 1 will be taken by default.', ['gui']) else: self.skip = self.skipStepEntry.getValue() if (self.skip < 1) or (self.skip >= len(self.trajectory)): raise Error('Last frame not within [1,%d[.' % len(self.trajectory)) return True
def initialize(self): """Initializes the analysis (e.g. parses and checks input parameters, set some variables ...). """ # The input parameters are parsed. self.interpreteInputParameters() if self.universe.basisVectors() is None: raise Error( 'The universe must be periodic for this kind of calculation.') self.S2 = {} self.sequence = {} self.hnLookup = {} self.nChemicalObjects = len(self.universe.objectList()) chemicalObjects = self.universe.objectList() for comp in range(self.nChemicalObjects): obj = chemicalObjects[comp] objName = self.chemicalObjectNames[comp] if self.chemicalObjectInfo[objName]['objectclass'] in [ 'PeptideChain', 'Protein' ]: self.sequence[objName] = [] self.hnLookup[objName] = [] comp = 1 for r in obj.residues()[1:]: if r.symbol.lower() != 'pro': self.sequence[objName].append(r.sequence_number) self.hnLookup[objName].append(comp) comp += 1 self.S2[objName] = N.zeros( (len(self.sequence[objName]), self.nFrames), typecode=N.Float) # Case where no protein or peptide chain was found in the universe. if not self.sequence: raise Error( 'The universe must contains at least one peptide chain to perform the analysis.' ) self.scaleHydrogenPos = N.zeros((3, ), typecode=N.Float) self.scaleOxygenPos = N.zeros((3, ), typecode=N.Float)
def __init__(self, master, frameLabel='', tagName='', contents=[]): """The constructor. @param master: the parent widget of the combo widget. @param frameLabel: the label for the Tkinter LabelFrame widget. @type frameLabel: string or Tkinter.StringVar object. @param tagLabel: the tag used for to document the widget. If set to '', the widget will not be documented. @type tagLabel: string. @param contents: a 3 elements list (integer) specifying respectively the first, the last and the resolution values for the Tkinter Scale widget. @type contents: list """ # The comboframe is set up. ComboFrame.__init__(self, master, frameLabel, tagName) # At least one option must be provided. if len(contents) == 0: raise Error('No values given to set up this combowidget.') self.from_, self.to, self.resolution = contents self.scale = Scale(self, from_=self.from_, to=self.to, resolution=self.resolution, length=200, orient=HORIZONTAL) self.scale.grid(row=0, column=0, sticky=E, padx=3)
def randomVector(directions=None): """Returns a normalized random vector on an axis, a plane or in space. @param directions: if not None, a list of 2 Scientific.Vector that will define the plane on which the vector should be generated. @type directions: list of 2 Scientific.Vector or None @return: a normalized random vector on a plane defined by |directions| or in space (|directions| = None). @rtype: Scientific.Geometry.Vector object """ # 3D case. if directions is None: return randomDirection() # 1D case. if len(directions) == 1: return directions[0] # 2D case. elif len(directions) == 2: # The first vector of the plane. v1, v2 = directions # v1 /\ v2. axis = (v1.cross(v2)) if axis.length() == 0.0: raise Error( 'Your basis vectors are colinear. Can not build a plane out of them.' ) return randomDirection2D(axis)
def convolution(inputSeries1, inputSeries2): """Returns the numerical convolution between two signals. @param inputSeries1: the first signal @type inputSeries1: NumPy array @param inputSeries2: the second signal. @type inputSeries2: NumPy array @return: the result of the convolution. @rtype: NumPy array @note: if |inputSeries1| is a multidimensional array the convolution calculation is performed on the first dimension. @note: the convolution is computed using the convolve function of NumPy package. """ # The signals must not be empty. if (len(inputSeries1) == 0) | (len(inputSeries2) == 0): raise Error('One or both inputSeries are empty.') # The convolution between inputSeries1 and inputSeries2. # A 1D Numeric array of dimension len(inputSeries1)*len(inputSeries2)-1 return N.convolve(inputSeries1, inputSeries2)
def openTrajectory(self, event=None): """ Ths method is called when the user clicks on the 'Browse' button of the trajectory visualization dialog. It opens a file browser. After the file selection some of the dialog widgets are updated with the informations coming from the loaded trajectory. """ # Case where the user enters a file name directly in the entry widget without using the browser. if event is not None: if event.widget == self.fileBrowser.entry: filename = self.fileBrowser.getValue() else: return else: # The name of the NetCDF file to load. filename = askopenfilename(parent = self,\ filetypes = [('NetCDF file','*.nc')],\ initialdir = PREFERENCES['trajfile_path']) # The file must exist. if filename: try: # The trajectory is loaded. self.trajectory = Trajectory(None, filename, 'r') except IOError: raise Error('Can not read the trajectory.') else: # The control variables are updated with the informations about the loaded trajectory. self.fileBrowser.setValue(filename) self.selectedStepEntry.setValue('1') return 'break'
def correlation(inputSeries1, inputSeries2=None): """Returns the numerical correlation between two signals. @param inputSeries1: the first signal. @type inputSeries1: NumPy array @param inputSeries2: if not None, the second signal otherwise the correlation will be an autocorrelation. @type inputSeries2: NumPy array or None @return: the result of the numerical correlation. @rtype: NumPy array @note: if |inputSeries1| is a multidimensional array the correlation calculation is performed on the first dimension. @note: The correlation is computed using the FCA algorithm. """ # The signal must not be empty. if len(inputSeries1) <= 0: raise Error('One or both time series are empty.') # The length of inputSeries1 is stored in inputSeries1Length inputSeries1Length = len(inputSeries1) # extendedLength = 2*len(inputSeries1) extendedLength = 2 * inputSeries1Length # The FCA algorithm: # 1) computation of the FFT of inputSeries1 zero-padded until extendedLength # The computation is done along the 0-axis FFTSeries1 = fft(inputSeries1, extendedLength, 0) if inputSeries2 is None: # Autocorrelation case FFTSeries2 = FFTSeries1 else: # 2) computation of the FFT of inputSeries2 zero-padded until extendedLength # The computation is done along the 0-axis FFTSeries2 = fft(inputSeries2, extendedLength, 0) # 3) Product between FFT(inputSeries1)* and FFT(inputSeries2) FFTSeries1 = N.conjugate(FFTSeries1) * FFTSeries2 # 4) inverse FFT of the product # The computation is done along the 0-axis FFTSeries1 = inverse_fft(FFTSeries1, len(FFTSeries1), 0) # This refers to (1/(N-m))*Sab in the published algorithm. # This is the correlation function defined for positive indexes only. if len(FFTSeries1.shape) == 1: corr = FFTSeries1.real[:inputSeries1Length] / ( inputSeries1Length - N.arange(inputSeries1Length)) else: corr = N.add.reduce(FFTSeries1.real[:inputSeries1Length], 1) / ( inputSeries1Length - N.arange(inputSeries1Length)) return corr
def apply(self): try: if os.path.exists(PREFERENCES['vmd_path']): definePDBViewer('vmd', PREFERENCES['vmd_path']) else: raise except: raise Error( 'Error when defining VMD molecular viewer from %s path.' % PREFERENCES['vmd_path']) try: # This MMTK function calls VMD to visualize the trajectory. viewTrajectory(trajectory = self.trajectory, first = self.first, last = self.last, skip = self.skip,\ subset = self.viewableAtoms) except: raise Error('Error when animating the trajectory.')
def getValue(self): """Returns the value of the control variable linked to the Tkinter Entry widget if it is an integer otherwise throws an error. """ try: return int(self.variable.get()) except ValueError: raise Error('%s is not an integer' % self.variable.get())
def getValue(self): """Returns the value of the control variable linked to the Tkinter Entry widget if it is a string otherwise throws an error. """ try: if self.variable.get(): return str(self.variable.get()) else: return None except: raise Error('%s is not a string' % self.variable.get())
def validate(self): # This is the list of the test sets selected by the |checkSimulationsDialog| dialog. self.selectedTestSets = [ self.testListLb.lb.get(int(testSet)) for testSet in self.testListLb.lb.curselection() ] if not self.selectedTestSets: raise Error('No Test selected.') return True
def interpreteInputParameters(self): """Parse the input parameters for the analysis. """ # Parses the parameters that are common to different analysis. Analysis.interpreteInputParameters(self) # Parses the analysis specific parameters. # The 'filter' input parameter. Must be a string of the form 'fmin:fmax' where fmin and fmax are respectively # the min and max frequencies of the filter. if isinstance(self.parameters['filter'],str): try: # Sets the |self.freqMin| and |self.freqMax| attributes to respectively the min and max frequencies. self.freqMin, self.freqMax = [float(v) for v in self.parameters['filter'].split(':')] except: raise Error('Error when parsing "filter" parameter: must be a string of the form fmin:fmax.') # The min frequency must be >= 0. if self.freqMin < 0.0: raise Error('Error when parsing "filter" parameter: the min frequency must be >= 0.') # The max frequency must be > min frequency. if self.freqMin >= self.freqMax: raise Error('Error when parsing "filter" parameter: the max frequency must be > min frequency.') # Otherwise raises an error. else: raise Error('Error when parsing "filter" parameter: must be a string.') self.buildTimeInfo() self.subset = self.selectAtoms(self.subsetDefinition) self.nSelectedAtoms = len(self.subset) if self.architecture != 'monoprocessor': # The attribute trajectory is removed because it can not be pickled by Pyro. delattr(self, 'trajectory')
def validate(self): if not self.trajectory: raise Error('No MMTK trajectory file loaded for extraction.') if self.trajectory.filename != self.fileBrowser.getValue(): raise Error( 'Mismatch between the loaded trajectory and the displayed MMTK trajectory file name.\ You should validate that file by pressing Return on its corresponding entry.') # A frame selection must have been set. if not self.selectedStepEntry.getValue(): self.selectedFrames = '1' LogMessage( 'warning', 'No frame selected. Frame 1 will be extracted by default.', ['gui']) else: self.selectedFrames = self.selectedStepEntry.getValue().strip() try: self.selectedFrames = eval(self.selectedFrames) # The entry can be an integer. if isinstance(self.selectedFrames, int): self.selectedFrames = [self.selectedFrames] # The entry can be a list or a tuple. elif isinstance(self.selectedFrames, (list, tuple)): pass except: try: temp = [] self.selectedFrames = [ temp.extend(range(int(v[0]), int(v[1]) + 1, int(v[2]))) for v in re.findall('(\d+):(\d+):(\d+)', self.selectedFrames) ] self.selectedFrames = temp except: raise Error('Wrong format for frame selection.') # Check that every selected step is valid. for s in self.selectedFrames: if not isinstance(s, int): raise Error('Wrong entry for frame selection.') if (s <= 0) or (s > len(self.trajectory)): raise Error( 'Some selected frame number are not within [1,%d].' % len(self.trajectory)) # A PDB output file name must have been set. self.pdbFile = self.pdbFileBrowser.getValue() if not self.pdbFile: raise Error('Please enter a PDB output file.') return True
def runAnalysis(self): """Runs the analysis directly from the GUI. """ self.parameters['estimate'] = 'no' if not self.parameters.has_key('pyroserver'): self.actualAnalysis = eval( '%s_serial(parameters = self.parameters, statusBar = self.statusBar)' % self.db_internalname) else: if self.parameters['pyroserver'].lower() == 'monoprocessor': self.actualAnalysis = eval( '%s_serial(parameters = self.parameters, statusBar = self.statusBar)' % self.db_internalname) elif self.parameters['pyroserver'][:14].lower( ) == 'multiprocessor': self.actualAnalysis = eval( '%s_parallel(parameters = self.parameters, statusBar = self.statusBar)' % self.db_internalname) elif self.parameters['pyroserver'][:7].lower() == 'cluster': self.actualAnalysis = eval( '%s_parallel(parameters = self.parameters, statusBar = self.statusBar)' % self.db_internalname) else: raise Error('The pyro server was not set properly') t = self.actualAnalysis.runAnalysis() self.parent.info.insert(contents='\n\n\nPERFORMED ANALYSIS:\n\n') self.parent.info.insert(contents=self.actualAnalysis.information) message = 'Analysis run successfully in \n %(days)s days %(hours)s hours %(minutes)s minutes %(seconds)s seconds.\n\n' % t if self.actualAnalysis.toPlot is None: # The information dialog with the predicted analysis time. LogMessage('info', message, ['gui']) else: # Try to import the matplotlib module. try: from nMOLDYN.GUI.PlotNetCDFVariableDialog import PlotNetCDFVariableDialog except: return else: message += 'Do you want to plot the results right now ?' q = askyesno(title='Question', message=message) if q: PlotNetCDFVariableDialog(self, **self.actualAnalysis.toPlot)
def __init__(self, master, frameLabel='', tagName='', contents=[], default=0): """The constructor. @param master: the parent widget of the combo widget. @param frameLabel: the label for the Tkinter LabelFrame widget. @type frameLabel: string or Tkinter.StringVar object. @param tagLabel: the tag used for to document the widget. If set to '', the widget will not be documented. @type tagLabel: string. @param contents: a tuple (string) specifying the names of for the entries to insert in the Tkinter Spinbox widget. @type contents: tuple @param default: an integer specifying which entry of the Tkinter Spinbox widget will be displayed by default. @type default: integer """ # The comboframe is set up. ComboFrame.__init__(self, master, frameLabel, tagName) # At least one option must be provided. if len(contents) == 0: raise Error('No option given to set up this combowidget.') self.type = type(contents[0]) for v in contents: if type(v) != self.type: self.type = str # The frame that will host the option menu widget is set up. spinboxFrame = Frame(self) spinboxFrame.grid(row=0, column=1, sticky=E, padx=3) self.contents = contents self.default = default self.spinbox = Spinbox(spinboxFrame, values=self.contents, wrap=True, width=4, bg='white') self.spinbox.grid(sticky=E) self.setValue(self.contents[self.default])
def parseInterval(interval): """This function convert a string of the form xmin:xmax:dx to an array @param interval: a string of the form 'mini:maxi:delta' to convert. @type interval: string @return: a list of the form [xmin, xmin + dx, xmin + 2*dx ...] @rtype: list """ if not isinstance(interval, str): raise Error( 'Error when parsing %s parameter: wrong format for the string.' % pName) # The string must be three semi colon-separated floats. try: xMin, xMax, dX = [float(v) for v in interval.split(':')] except: raise Error( 'Error when parsing % string: must be of the form "xmin:xmax:dx".' % interval) else: # The number of bins corresponding to the given interval. nBins = int((xMax - xMin) / dX) # The actual value of xMax is recomputed. xMax = xMin + nBins * dX values = linspace(xMin, xMax, nBins + 1, True) values.sort() return values
def internalRun(self): """Performs the analysis in parallel mode. """ from Scientific.DistributedComputing.MasterSlave import initializeMasterProcess, TaskRaisedException, GlobalStateValue pyroServer = setUpPyroServer() if self.taskName is None: # This should be enough to create a unique task name. self.taskName = '%s_%s_%s' % (self.db_shortname, getpass.getuser(), '_'.join(asctime().split())) if self.architecture == 'multiprocessor': tasks = initializeMasterProcess(self.taskName) elif self.architecture == 'cluster': tasks = initializeMasterProcess(self.taskName, slave_module='nMOLDYN.Analysis.Slave') else: raise Error('Illegal parallel mode %s' % self.architecture) # The instance of the running analysis is made global for all the process. tasks.setGlobalState(analysis=self) # The master registers the tasks to be done by the slave. for fIndex in self.frameIndexes: task_id = tasks.requestTask("analysisPerElement", GlobalStateValue(1, 'analysis'), fIndex, self.trajectoryFilename) # The slaves are started but the calculation is not started actually. # In case of a cluster run, wait for calls to the task_manager. startSlaves(self.taskName, self.architecture, self.numberOfProcs) # The analysis actual starting time. self.chrono = default_timer() for fIndex in self.frameIndexes: try: task_id, tag, (frameIndex, x) = tasks.retrieveResult("analysisPerElement") self.combine(frameIndex,x) self.updateJobProgress(self.nFrames) except TaskRaisedException, e: LogMessage('error', e.traceback, ['console']) raise except:
def apply(self): try: if os.path.exists(PREFERENCES['vmd_path']): definePDBViewer('vmd', PREFERENCES['vmd_path']) else: raise except: raise Error('Error when defining the PDB viewer from %s path.' % PREFERENCES['vmd_path']) try: local = {} skeleton = eval(self.description, vars(Skeleton), local) universe = skeleton.make({}, self.avgStruct) universe.setCellParameters(self.cell) avg = Configuration(universe, self.avgStruct) pseudoTraj = [avg] for comp in range(self.nFrames): vibr = copy.copy(avg) for selMode in self.selectedMode: dx = copy.copy(self.dx[selMode]) dx.shape = (universe.numberOfAtoms(), 3) d = ParticleVector(universe, dx) vibr += self.amplitude*Num.sin(2.0*Num.pi*float(comp)/self.nFrames)*d pseudoTraj.append(vibr) viewSequenceVMD(universe, pseudoTraj, periodic = 1) except: raise Error('Error when animating the selected mode(s).')
def validate(self): # An input file must have been set. self.inputFile = self.inputFileBrowser.getValue() if not self.inputFile: raise Error('Please enter a NetCDF input file.') # The float precision entry is checked and stored. self.floatPrecision = self.floatPrecisionEntry.getValue() if self.floatPrecision <= 0: raise Error('The float precision must > 0.') # The double precision entry is checked and stored. self.doublePrecision = self.doublePrecisionEntry.getValue() if self.doublePrecision <= 0: raise Error('The Double precision must > 0.') # An output file must have been set. self.outputFile = self.outputFileBrowser.getValue() if not self.outputFile: raise Error('Please enter an ASCII output file.') # The extension '.cdl' is appended to the output file name if necessary. if self.outputFile[-4:] != '.cdl': self.outputFile += '.cdl' # The selected variables are stored. self.selectedVariables = [] for k, v in self.variables.items(): if v.get(): self.selectedVariables.append(k) if not self.selectedVariables: raise Error('No NetCDF variables selected for conversion.') return True
def internalRun(self): """Performs the analysis in parallel mode. """ from Scientific.DistributedComputing.MasterSlave import initializeMasterProcess, TaskRaisedException, GlobalStateValue # The Pyro server is setup. pyroServer = setUpPyroServer() # If no task name was assigned to the job, build one. if self.taskName is None: self.taskName = '%s_%s_%s' % (self.db_shortname, getpass.getuser(), '_'.join(asctime().split())) if self.architecture == 'multiprocessor': tasks = initializeMasterProcess(self.taskName) elif self.architecture == 'cluster': tasks = initializeMasterProcess(self.taskName, slave_module='nMOLDYN.Analysis.Slave') else: raise Error('Illegal parallel mode %s' % self.architecture) tasks.setGlobalState(analysis=self) for aIndex in self.subset: task_id = tasks.requestTask("analysisPerElement", GlobalStateValue(1, 'analysis'), aIndex, self.trajectoryFilename) startSlaves(self.taskName, self.architecture, self.numberOfProcs) # The analysis actual starting time. self.chrono = default_timer() for aIndex in self.subset: try: task_id, tag, (atomIndex, x) = tasks.retrieveResult("analysisPerElement") self.combine(atomIndex, x) self.updateJobProgress(self.nSelectedAtoms) except TaskRaisedException, e: LogMessage('error', e.traceback, ['console']) raise except:
def _planar_qvectors(self): hkl_dir = self._generate_hkls() self.hkl_dir = [] factor = pgcd(hkl_dir[0]) self.hkl_dir.append(Vector(hkl_dir[0]) / factor) factor = pgcd(hkl_dir[1]) self.hkl_dir.append(Vector(hkl_dir[1]) / factor) self.qDirections = [] self.qDirections.append(self.transRecBasis * self.hkl_dir[0]) self.qDirections.append(self.transRecBasis * self.hkl_dir[1]) if self.qDirections[0].cross(self.qDirections[1]).length() <= 0: raise Error( "The q plan must be defined by two non-colinear q-directions.") for q in self.qShells: qMin = max(q - 0.5 * self.qShellWidth, 0.0) qMax = q + 0.5 * self.qShellWidth indMax = [int(qMax / v.length()) + 2 for v in self.qDirections] grid = N.transpose(numpy.mgrid[-indMax[0]:indMax[0], -indMax[1]:indMax[1]]) indRange = (-grid).reshape(grid.size / 2, 2).tolist() + grid.reshape( grid.size / 2, 2).tolist() shuffle(indRange) qVects, hkls = self._explicit_qvectors(qMin, qMax, indRange) if qVects: self.qRadii.append(q) self.qVectors.append(qVects) self.hkls.append(hkls)
def invFFT(inputSeries): """Returns the inverse FFT of a signal. @param inputSeries: the signal. @type inputSeries: NumPy array @return: the inverse FFT transformed signal. @rtype: NumPy array @note: the inverse FFT is computed using the inverse_fft function of Scientific.FFT package. """ # The signal must not be empty. if len(inputSeries) == 0: raise Error('The inputSeries is empty.') # The inverse FFT of inputSeries return inverse_fft(inputSeries, len(inputSeries), 0)
def insert(self, contents=[]): """Inserts a list of items (string) in the Tkinter Listbox widget. @param contents: a list (string) specifying the items to insert in the Tkinter Listbox widget. @type contents: list """ # Some checkings. if not isinstance(contents, (list, tuple, dict)): raise Error( 'The object of type %s cannot be inserted into a listbox.' % contents.__class__.__name__) self.cleanup() # Loop over list to insert in the listbox. for c in contents: self.lb.insert(END, c)
def _axial_qvectors(self): hkl_dir = self._generate_hkls() factor = pgcd(hkl_dir[0]) self.hkl_dir = [Vector(hkl_dir[0]) / factor] self.qDirections = [self.transRecBasis * self.hkl_dir[0]] qLength = self.qDirections[0].length() if qLength <= 0.0: raise Error( "The %s node gave a null direction in the reciprocal space." % self.qDirection) for q in self.qShells: qMin = max(q - 0.5 * self.qShellWidth, 0.0) if qLength > qMin: continue qMax = q + 0.5 * self.qShellWidth indMin = int(qMin / qLength) indMax = int(qMax / qLength) + 1 indRange = range(-indMax, -indMin + 1) + range(indMin, indMax + 1) shuffle(indRange) indRange = [[v] for v in indRange] qVects, hkls = self._explicit_qvectors(qMin, qMax, indRange) if qVects: self.qRadii.append(q) self.qVectors.append(qVects) self.hkls.append(hkls)
def __init__(self, master, frameLabel='', tagName='', contents=[], default=0): """The constructor. @param master: the parent widget of the combo widget. @param frameLabel: the label for the Tkinter LabelFrame widget. @type frameLabel: string or Tkinter.StringVar object. @param tagLabel: the tag used for to document the widget. If set to '', the widget will not be documented. @type tagLabel: string. @param contents: a list (string) specifying the names of for the entries each Tkinter OptionMenu widget. @type contents: list @param default: an integer specifying which entry of the Tkinter optionMenu widget will be displayed by default. @type default: integer """ # The comboframe is set up. ComboFrame.__init__(self, master, frameLabel, tagName) # At least one option must be provided. if len(contents) == 0: raise Error('No option given to set up this combowidget.') # The frame that will host the option menu widget is set up. optionFrame = Frame(self) optionFrame.grid(row=0, column=1, sticky=E, padx=3) self.contents = contents self.optionVar = StringVar() self.optionVar.set(self.contents[default]) self.option = OptionMenu(optionFrame, self.optionVar, *contents) self.option.grid(sticky=E)