def preparePP(self, j, m, n): """Intermediate function used to setup the calculation of spherical harmonics.""" # c2 is the sqrt[(j+m)! * (j-m)!] * j! of equation 3.55 c2 = N.sqrt((factorial(j + m) * factorial(j - m))) * factorial(j) c3 = j + m pp = [] aa = [] for p in range(0, j + 1, 1): if (p <= c3) and (p >= m): # p1 is the j+m-p of equation 3.55 p1 = c3 - p # p2 is the j-p of equation 3.55 p2 = j - p p3 = p - m # a1 is the first part of equation 3.55 before the x a1 = ((-1)**p) * c2 / (factorial(p1) * factorial(p2) * factorial(p) * factorial(p3)) pp.append((p1, p2, p3, p)) aa.append(a1) return N.array(pp, typecode=N.Float), N.array(aa, typecode=N.Float)
def nonbondedList(self, universe, subset1, subset2, global_data): try: from MMTK_forcefield import NonbondedList, NonbondedListTerm except ImportError: return None, None nbl = None update = None if 'nonbondedlist' in global_data.get('initialized'): nbl, update, cutoff = global_data.get('nonbondedlist') if nbl is None: excluded_pairs, one_four_pairs, atom_subset = \ self.excludedPairs(subset1, subset2, global_data) excluded_pairs = N.array(excluded_pairs) one_four_pairs = N.array(one_four_pairs) if atom_subset is not None: atom_subset = N.array(atom_subset) else: atom_subset = N.array([], N.Int) nbl = NonbondedList(excluded_pairs, one_four_pairs, atom_subset, universe._spec, self.cutoff) update = NonbondedListTerm(nbl) update.info = 0 global_data.set('nonbondedlist', (nbl, update, self.cutoff)) global_data.add('initialized', 'nonbondedlist') else: if cutoff is not None and \ (self.cutoff is None or self.cutoff > cutoff): nbl.setCutoff(self.cutoff) return nbl, update
def __init__(self, master, width, height, background='white', **attr): """ @param master: the parent widget @param width: the initial width of the canvas @type width: C{int} @param height: the initial height of the canvas @type height: C{int} @param background: the background color @type background: C{str} @param attr: widget attributes """ apply(Tkinter.Frame.__init__, (self, master), attr) self.canvas = Tkinter.Canvas(self, width=width, height=height, background=background) self.canvas.pack(fill=Tkinter.BOTH, expand=Tkinter.YES) border_w = self.canvas.winfo_reqwidth() - \ int(self.canvas.cget('width')) border_h = self.canvas.winfo_reqheight() - \ int(self.canvas.cget('height')) self.border = (border_w, border_h) self.canvas.bind('<Configure>', self.reconfigure) self.canvas.bind('<1>', self.clickhandler1) self.canvas.bind('<ButtonRelease-1>', self.releasehandler1) self.canvas.bind('<2>', self.clickhandler2) self.canvas.bind('<ButtonRelease-2>', self.releasehandler2) self.canvas.bind('<3>', self.clickhandler3) self.canvas.bind('<ButtonRelease-3>', self.releasehandler3) self._setsize() self.scale = None self.translate = N.array([0., 0.]) self.last_draw = None self.axis = N.array([0., 0., 1.]) self.plane = N.array([[1., 0.], [0., 1.], [0., 0.]])
def setup(self, time, inspector, names): time = time[::self.step] sum = 0. range = 0. for n in names: data = Numeric.array(inspector.readScalarVariable(n, 0, None, self.step)) sum = sum + data upper = Numeric.maximum.reduce(data) lower = Numeric.minimum.reduce(data) lower, upper = plotRange(lower, upper) range = max(range, upper-lower) upper = Numeric.maximum.reduce(sum) lower = Numeric.minimum.reduce(sum) lower, upper = plotRange(lower, upper) range = 0.5*max(range, upper-lower) for n in names: data = Numeric.array(inspector.readScalarVariable(n, 0, None, self.step)) data = Numeric.transpose(Numeric.array([time, data])) mean = Numeric.add.reduce(data[:, 1])/len(data) self.plotBox(n, data, (mean-range, mean+range)) if len(names) > 1: data = Numeric.transpose(Numeric.array([time, sum])) mean = Numeric.add.reduce(data[:, 1])/len(data) self.plotBox('Sum', data, (mean-range, mean+range))
def draw(self, event=None): xnum = self.xnum.get() ynum = self.ynum.get() znum = self.znum.get() self.mode_projector.calculateProjections([xnum, ynum, znum]) x = self.mode_projector[xnum] data = Numeric.zeros((len(x), 3), Numeric.Float) data[:, 0] = x[:, 1] data[:, 1] = self.mode_projector[ynum][:, 1] data[:, 2] = self.mode_projector[znum][:, 1] minv = Numeric.minimum.reduce(data) maxv = Numeric.maximum.reduce(data) scale = maxv - minv reference = minv - 0.05 * scale xaxis = PolyLine3D( [reference, reference + scale * Numeric.array([0.2, 0., 0.])], color='red') yaxis = PolyLine3D( [reference, reference + scale * Numeric.array([0., 0.2, 0.])], color='yellow') zaxis = PolyLine3D( [reference, reference + scale * Numeric.array([0., 0., 0.2])], color='green') graphics = [PolyLine3D(data, color='blue'), xaxis, yaxis, zaxis] self.plot.clear() self.plot.draw(VisualizationGraphics(graphics))
def _setsize(self): self.width = string.atoi(self.canvas.cget('width')) self.height = string.atoi(self.canvas.cget('height')) self.plotbox_size = 0.97*N.array([self.width, -self.height]) xo = 0.5*(self.width-self.plotbox_size[0]) yo = self.height-0.5*(self.height+self.plotbox_size[1]) self.plotbox_origin = N.array([xo, yo])
def rigidRegionsFinite(comp, df, cutoff, subset=None): world = comp.universe natoms = world.numberOfCartesianCoordinates() if subset is None: subset = world pc = MMTK.PartitionedAtomCollection(1.2, world) regions = filter(lambda p: len(p) > 2, map(lambda p: p[2], pc.partitions())) data = [] rigid_regions = [] for region in regions: in_domain = 1 df_mean = N.add.reduce(map(lambda a, f=df: f[a], region)) / len(region) if df_mean < cutoff: r = MMTK.Collection(region) tr, rms = r.findTransformation(comp) v = tr.translation().displacement() axis, angle = tr.rotation().axisAndAngle() data.append(list(v) + list(angle * axis)) rigid_regions.append(r) data = N.array(data) arr = N.array(len(rigid_regions) * [None]) for i in range(len(arr)): arr[i] = rigid_regions[i] return data, arr
def setup(self, time, inspector, names): time = time[::self.step] sum = 0. range = 0. for n in names: data = Numeric.array( inspector.readScalarVariable(n, 0, None, self.step)) sum = sum + data upper = Numeric.maximum.reduce(data) lower = Numeric.minimum.reduce(data) lower, upper = plotRange(lower, upper) range = max(range, upper - lower) upper = Numeric.maximum.reduce(sum) lower = Numeric.minimum.reduce(sum) lower, upper = plotRange(lower, upper) range = 0.5 * max(range, upper - lower) for n in names: data = Numeric.array( inspector.readScalarVariable(n, 0, None, self.step)) data = Numeric.transpose(Numeric.array([time, data])) mean = Numeric.add.reduce(data[:, 1]) / len(data) self.plotBox(n, data, (mean - range, mean + range)) if len(names) > 1: data = Numeric.transpose(Numeric.array([time, sum])) mean = Numeric.add.reduce(data[:, 1]) / len(data) self.plotBox('Sum', data, (mean - range, mean + range))
def _setsize(self): width = self.width() height = self.height() self.plotbox_size = 0.97*N.array([width, -height]) xo = 0.5*(width-self.plotbox_size[0]) yo = height-0.5*(height+self.plotbox_size[1]) self.plotbox_origin = N.array([xo, yo])
def _mouseRelease(self, event): if self.mouse_state == 1: self.canvas.delete(self.rubberband) self.rubberband = None p1 = Numeric.array([self.startx, self.starty]) p2 = Numeric.array([self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)]) if Numeric.minimum.reduce(Numeric.fabs(p1-p2)) > 5: scale, shift = self.transformation p1 = (p1-shift)/scale p2 = (p2-shift)/scale graphics, xaxis, yaxis = self.last_draw if xaxis is not None: xaxis = (p1[0], p2[0]) if yaxis is not None: yaxis = (p2[1], p1[1]) self.clear() self.draw(graphics, xaxis, yaxis) elif self.mouse_state == 2: scale, shift = self.transformation x1 = (self.startx-shift[0])/scale[0] x2 = (self.canvas.canvasx(event.x)-shift[0])/scale[0] if x1 < x2: self.selected_range = (x1, x2) else: self.selected_range = (x2, x1) if self.selectfn is not None: self.selectfn(self.selected_range) else: self.canvas.delete(self.rectangle) self.rectangle = None self.selected_range = None if self.selectfn is not None: self.selectfn(self.selected_range) self.mouse_state = 0
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data) pe = params['electrostatic'] assert pe['algorithm'] == 'dpmta' pn = params['nonbonded'] excluded_pairs = N.array(pn['excluded_pairs']) one_four_pairs = N.array(pn['one_four_pairs']) if atom_subset is None: atom_subset = N.array([], N.Int) else: atom_subset = N.array(pn['atom_subset']) nbinfo = [excluded_pairs, one_four_pairs, atom_subset] if universe.is_periodic: try: shape = universe.basisVectors() except AttributeError: raise ValueError("Multipole method implemented only " + "for orthorhombic universes.") shape = N.array(shape, N.Float) else: shape = N.zeros((), N.Float) from MMTK_forcefield import EsMPTerm ev = EsMPTerm(universe._spec, shape, nbinfo, pe['charge'], pe['one_four_factor'], pe['spatial_decomposition_levels'], pe['multipole_expansion_terms'], pe['use_fft'], pe['fft_blocking_factor'], pe['macroscopic_expansion_terms'], pe['multipole_acceptance']) return [ev]
def _setsize(self): self.width = string.atoi(self.canvas.cget('width')) self.height = string.atoi(self.canvas.cget('height')) self.plotbox_size = 0.97*Numeric.array([self.width, -self.height]) xo = 0.5*(self.width-self.plotbox_size[0]) yo = self.height-0.5*(self.height+self.plotbox_size[1]) self.plotbox_origin = Numeric.array([xo, yo])
def normalizingTransformation(self, repr=None): """Returns a linear transformation that shifts the center of mass of the object to the coordinate origin and makes its principal axes of inertia parallel to the three coordinate axes. A specific representation can be chosen by setting |repr| to Ir : x y z <--> b c a IIr : x y z <--> c a b IIIr : x y z <--> a b c Il : x y z <--> c b a IIl : x y z <--> a c b IIIl : x y z <--> b a c """ from Scientific.LA import determinant cm, inertia = self.centerAndMomentOfInertia() ev, diag = inertia.diagonalization() if determinant(diag.array) < 0: diag.array[0] = -diag.array[0] if repr != None: seq = Numeric.argsort(ev) if repr == 'Ir': seq = Numeric.array([seq[1], seq[2], seq[0]]) elif repr == 'IIr': seq = Numeric.array([seq[2], seq[0], seq[1]]) elif repr == 'Il': seq = Numeric.seq[2::-1] elif repr == 'IIl': seq[1:3] = Numeric.array([seq[2], seq[1]]) elif repr == 'IIIl': seq[0:2] = Numeric.array([seq[1], seq[0]]) elif repr != 'IIIr': print 'unknown representation' diag.array = Numeric.take(diag.array, seq) return Transformation.Rotation(diag)*Transformation.Translation(-cm)
def draw(self, event=None): xnum = self.xnum.get() ynum = self.ynum.get() znum = self.znum.get() self.mode_projector.calculateProjections([xnum, ynum, znum]) x = self.mode_projector[xnum] data = Numeric.zeros((len(x), 3), Numeric.Float) data[:, 0] = x[:, 1] data[:, 1] = self.mode_projector[ynum][:, 1] data[:, 2] = self.mode_projector[znum][:, 1] minv = Numeric.minimum.reduce(data) maxv = Numeric.maximum.reduce(data) scale = maxv-minv reference = minv-0.05*scale xaxis = PolyLine3D([reference, reference+scale*Numeric.array([0.2, 0., 0.])], color='red') yaxis = PolyLine3D([reference, reference+scale*Numeric.array([0., 0.2, 0.])], color='yellow') zaxis = PolyLine3D([reference, reference+scale*Numeric.array([0., 0., 0.2])], color='green') graphics = [PolyLine3D(data, color = 'blue'), xaxis, yaxis, zaxis] self.plot.clear() self.plot.draw(VisualizationGraphics(graphics))
def targetFunctionAndAmplitudeDerivatives(self): self.updateInternalState() beta = N.array([self.beta(sq) for sq in self.ssq]) eps_beta_inv = 1./(self.epsilon*beta + (2-self.centric)*self.exp_sigmas_sq) alpha = N.array([self.alpha(sq) for sq in self.ssq]) alpha_a = alpha*self.model_amplitudes arg1 = -(self.exp_amplitudes**2+alpha_a**2)*eps_beta_inv arg2 = alpha_a*self.exp_amplitudes*eps_beta_inv darg1 = -2.*alpha_a*alpha*eps_beta_inv darg2 = alpha*self.exp_amplitudes*eps_beta_inv llk = 0. dllk = 0.*self.ssq for ri in range(self.nreflections): if self.working_set[ri]: if self.centric[ri]: llk -= 0.5*arg1[ri]+logcosh(arg2[ri]) \ + 0.5*N.log(2*eps_beta_inv[ri]/N.pi) # cosh(x)' = sinh(x) # log(cosh(x))' = tanh(x) dllk[ri] = -(0.5*darg1[ri]+N.tanh(arg2[ri])*darg2[ri]) else: llk -= arg1[ri]+logI0(2.*arg2[ri]) \ + N.log(2.*self.exp_amplitudes[ri]*eps_beta_inv[ri]) # I0(x)' = I1(x) # log(I0(x))' = I1(x)/I0(x) dllk[ri] = -(darg1[ri]+2.*I1divI0(2*arg2[ri])*darg2[ri]) return llk/self.nwreflections, dllk/self.nwreflections
def pairsWithinCutoff(self, cutoff): """ :param cutoff: a cutoff for pair distances :returns: a list containing all pairs of objects in the collection whose center-of-mass distance is less than the cutoff :rtype: list """ pairs = [] positions = {} for index, objects in self.partition.items(): pos = map(lambda o: o.position(), objects) positions[index] = pos for o1, o2 in Utility.pairs(zip(objects, pos)): if (o2[1] - o1[1]).length() <= cutoff: pairs.append((o1[0], o2[0])) partition_cutoff = int(N.floor((cutoff / self.partition_size)**2)) ones = N.array([1, 1, 1]) zeros = N.array([0, 0, 0]) keys = self.partition.keys() for i in range(len(keys)): p1 = keys[i] for j in range(i + 1, len(keys)): p2 = keys[j] d = N.maximum(abs(N.array(p2) - N.array(p1)) - ones, zeros) if N.add.reduce(d * d) <= partition_cutoff: for o1, pos1 in zip(self.partition[p1], positions[p1]): for o2, pos2 in zip(self.partition[p2], positions[p2]): if (pos2 - pos1).length() <= cutoff: pairs.append((o1, o2)) return pairs
def evaluatorTerms(self, universe, subset1, subset2, global_data): if subset1 is not None: for s1, s2 in [(subset1, subset2), (subset2, subset1)]: set = {} for a in s1.atomList(): set[a.index] = None for a in s2.atomList(): try: del set[a.index] except KeyError: pass set = {} for a in subset1.atomList(): set[a.index] = None for a in subset2.atomList(): set[a.index] = None atom_subset = set.keys() atom_subset.sort() atom_subset = Numeric.array(atom_subset) else: atom_subset = Numeric.array([], Numeric.Int) nothing = Numeric.zeros((0,2), Numeric.Int) nbl = NonbondedList(nothing, nothing, atom_subset, universe._spec, self.cutoff) update = NonbondedListTerm(nbl) cutoff = self.cutoff if cutoff is None: cutoff = 0. ev = CalphaTerm(universe._spec, nbl, cutoff, self.scale_factor, self.version) return [update, ev]
def setUp(self): self.points = N.array([[-2.341500, 3.696800], [-1.109200, 3.111700], [-1.566900, 1.835100], [-2.658500, 0.664900], [-4.031700, 2.845700], [-3.081000, 2.101100], [2.588000, 1.781900], [3.292300, 3.058500], [4.031700, 1.622300], [3.081000, -0.611700], [0.264100, 0.398900], [1.320400, 2.207400], [0.193700, 3.643600], [1.954200, -0.505300], [1.637300, 1.409600], [-0.123200, -1.516000], [-1.355600, -3.058500], [0.017600, -4.016000], [1.003500, -3.590400], [0.017600, -2.420200], [-1.531700, -0.930900], [-1.144400, 0.505300], [0.616200, -1.516000], [1.707700, -2.207400], [2.095100, 3.430900]]) self.results = [(-50., N.array([ 2, 2, 2, 2, 2, 2, 6, 6, 6, 6, 2, 6, 2, 6, 6, 19, 19, 19, 19, 19, 19, 2, 19, 19, 6 ])), (-10., N.array([ 1, 1, 1, 5, 5, 5, 6, 6, 6, 13, 21, 6, 1, 13, 6, 19, 19, 19, 19, 19, 21, 21, 19, 19, 6 ])), (-5., N.array([ 1, 1, 1, 5, 5, 5, 6, 6, 6, 13, 21, 6, 1, 13, 6, 22, 17, 17, 17, 22, 21, 21, 22, 22, 6 ]))]
def __init__(self, master, width, height, background='white', **attr): """ @param master: the parent widget @param width: the initial width of the canvas @type width: C{int} @param height: the initial height of the canvas @type height: C{int} @param background: the background color @type background: C{str} @param attr: widget attributes """ apply(Tkinter.Frame.__init__, (self, master), attr) self.canvas = Tkinter.Canvas(self, width=width, height=height, background=background) self.canvas.pack(fill=Tkinter.BOTH, expand=Tkinter.YES) border_w = self.canvas.winfo_reqwidth() - \ string.atoi(self.canvas.cget('width')) border_h = self.canvas.winfo_reqheight() - \ string.atoi(self.canvas.cget('height')) self.border = (border_w, border_h) self.canvas.bind('<Configure>', self.reconfigure) self.canvas.bind('<1>', self.clickhandler1) self.canvas.bind('<ButtonRelease-1>', self.releasehandler1) self.canvas.bind('<2>', self.clickhandler2) self.canvas.bind('<ButtonRelease-2>', self.releasehandler2) self.canvas.bind('<3>', self.clickhandler3) self.canvas.bind('<ButtonRelease-3>', self.releasehandler3) self._setsize() self.scale = None self.translate = Numeric.array([0., 0.]) self.last_draw = None self.axis = Numeric.array([0.,0.,1.]) self.plane = Numeric.array([[1.,0.], [0.,1.], [0.,0.]])
def mouseMoveEvent(self, event): x = event.x() y = event.y() if self.mouse_state == 0: scale, shift = self.transformation p = (N.array([self.startx, self.starty]) - shift) / scale bb1, bb2 = self.bbox if self.selectfn is not None and p[1] < bb1[1]: self.painter.setPen(QPen(Qt.NoPen)) self.painter.setBrush(QBrush(Qt.blue, Qt.Dense5Pattern)) self.rectangle = (self.startx, 0, x - self.startx, self.height()) self.painter.drawRect(*self.rectangle) self.mouse_state = 2 elif self.zoom: self.painter.setPen(QPen(Qt.white, 1, Qt.DotLine)) self.painter.setBrush(QBrush(Qt.NoBrush)) self.rectangle = (self.startx, self.starty, x - self.startx, y - self.starty) self.painter.drawRect(*self.rectangle) self.mouse_state = 1 elif self.mouse_state == 1 or self.mouse_state == 2: self.painter.drawRect(*self.rectangle) if self.mouse_state == 1: self.rectangle = (self.startx, self.starty, x - self.startx, y - self.starty) elif self.mouse_state == 2: self.rectangle = (self.startx, 0, x - self.startx, self.height()) self.painter.drawRect(*self.rectangle) elif self.mouse_state == 3: scale, shift = self.transformation point = N.array([x, y]) point = (point - shift) / scale self.value_label.setText(" x = %f\n y = %f" % tuple(point))
def normalizingTransformation(self, repr=None): """Returns a linear transformation that shifts the center of mass of the object to the coordinate origin and makes its principal axes of inertia parallel to the three coordinate axes. A specific representation can be chosen by setting |repr| to Ir : x y z <--> b c a IIr : x y z <--> c a b IIIr : x y z <--> a b c Il : x y z <--> c b a IIl : x y z <--> a c b IIIl : x y z <--> b a c """ from Scientific.LA import determinant cm, inertia = self.centerAndMomentOfInertia() ev, diag = inertia.diagonalization() if determinant(diag.array) < 0: diag.array[0] = -diag.array[0] if repr != None: seq = Numeric.argsort(ev) if repr == 'Ir': seq = Numeric.array([seq[1], seq[2], seq[0]]) elif repr == 'IIr': seq = Numeric.array([seq[2], seq[0], seq[1]]) elif repr == 'Il': seq = Numeric.seq[2::-1] elif repr == 'IIl': seq[1:3] = Numeric.array([seq[2], seq[1]]) elif repr == 'IIIl': seq[0:2] = Numeric.array([seq[1], seq[0]]) elif repr != 'IIIr': print 'unknown representation' diag.array = Numeric.take(diag.array, seq) return Transformation.Rotation(diag) * Transformation.Translation(-cm)
def forceConstantTest(universe, atoms = None, delta = 0.0001): """ Test force constants by comparing to the numerical derivatives of the gradients. :param universe: the universe on which the test is performed :type universe: :class:`~MMTK.Universe.Universe` :param atoms: the atoms of the universe for which the gradient is tested (default: all atoms) :type atoms: list :param delta: the step size used in calculating the numerical derivatives :type delta: float """ e0, grad0, fc = universe.energyGradientsAndForceConstants() if atoms is None: atoms = universe.atomList() for a1, a2 in itertools.chain(itertools.izip(atoms, atoms), Utility.pairs(atoms)): print a1, a2 print fc[a1, a2] num_fc = [] for v in [ex, ey, ez]: x = a1.position() a1.setPosition(x+delta*v) e_plus, grad_plus = universe.energyAndGradients() a1.setPosition(x-delta*v) e_minus, grad_minus = universe.energyAndGradients() a1.setPosition(x) num_fc.append(0.5*(grad_plus[a2]-grad_minus[a2])/delta) print N.array(map(lambda a: a.array, num_fc))
def pairsWithinCutoff(self, cutoff): """ :param cutoff: a cutoff for pair distances :returns: a list containing all pairs of objects in the collection whose center-of-mass distance is less than the cutoff :rtype: list """ pairs = [] positions = {} for index, objects in self.partition.items(): pos = map(lambda o: o.position(), objects) positions[index] = pos for o1, o2 in Utility.pairs(zip(objects, pos)): if (o2[1]-o1[1]).length() <= cutoff: pairs.append((o1[0], o2[0])) partition_cutoff = int(N.floor((cutoff/self.partition_size)**2)) ones = N.array([1,1,1]) zeros = N.array([0,0,0]) keys = self.partition.keys() for i in range(len(keys)): p1 = keys[i] for j in range(i+1, len(keys)): p2 = keys[j] d = N.maximum(abs(N.array(p2)-N.array(p1)) - ones, zeros) if N.add.reduce(d*d) <= partition_cutoff: for o1, pos1 in zip(self.partition[p1], positions[p1]): for o2, pos2 in zip(self.partition[p2], positions[p2]): if (pos2-pos1).length() <= cutoff: pairs.append((o1, o2)) return pairs
def forceConstantTest(universe, atoms=None, delta=0.0001): """ Test force constants by comparing to the numerical derivatives of the gradients. :param universe: the universe on which the test is performed :type universe: :class:`~MMTK.Universe.Universe` :param atoms: the atoms of the universe for which the gradient is tested (default: all atoms) :type atoms: list :param delta: the step size used in calculating the numerical derivatives :type delta: float """ e0, grad0, fc = universe.energyGradientsAndForceConstants() if atoms is None: atoms = universe.atomList() for a1, a2 in itertools.chain(itertools.izip(atoms, atoms), Utility.pairs(atoms)): print a1, a2 print fc[a1, a2] num_fc = [] for v in [ex, ey, ez]: x = a1.position() a1.setPosition(x + delta * v) e_plus, grad_plus = universe.energyAndGradients() a1.setPosition(x - delta * v) e_minus, grad_minus = universe.energyAndGradients() a1.setPosition(x) num_fc.append(0.5 * (grad_plus[a2] - grad_minus[a2]) / delta) print N.array(map(lambda a: a.array, num_fc))
def mouseMoveEvent(self, event): x = event.x() y = event.y() if self.mouse_state == 0: scale, shift = self.transformation p = (N.array([self.startx, self.starty])-shift)/scale bb1, bb2 = self.bbox if self.selectfn is not None and p[1] < bb1[1]: self.painter.setPen(QPen(Qt.NoPen)) self.painter.setBrush(QBrush(Qt.blue, Qt.Dense5Pattern)) self.rectangle = (self.startx, 0, x-self.startx, self.height()) self.painter.drawRect(*self.rectangle) self.mouse_state = 2 elif self.zoom: self.painter.setPen(QPen(Qt.white, 1, Qt.DotLine)) self.painter.setBrush(QBrush(Qt.NoBrush)) self.rectangle = (self.startx, self.starty, x-self.startx, y-self.starty) self.painter.drawRect(*self.rectangle) self.mouse_state = 1 elif self.mouse_state == 1 or self.mouse_state == 2: self.painter.drawRect(*self.rectangle) if self.mouse_state == 1: self.rectangle = (self.startx, self.starty, x-self.startx, y-self.starty) elif self.mouse_state == 2: self.rectangle = (self.startx, 0, x-self.startx, self.height()) self.painter.drawRect(*self.rectangle) elif self.mouse_state == 3: scale, shift = self.transformation point = N.array([x, y]) point = (point-shift)/scale self.value_label.setText(" x = %f\n y = %f" % tuple(point))
def _mouseRelease(self, event): if self.mouse_state == 1: self.canvas.delete(self.rubberband) self.rubberband = None p1 = N.array([self.startx, self.starty]) p2 = N.array([self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)]) if N.minimum.reduce(N.fabs(p1-p2)) > 5: scale, shift = self.transformation p1 = (p1-shift)/scale p2 = (p2-shift)/scale graphics, xaxis, yaxis = self.last_draw if xaxis is not None: xaxis = (p1[0], p2[0]) if yaxis is not None: yaxis = (p2[1], p1[1]) self.clear() self.draw(graphics, xaxis, yaxis) elif self.mouse_state == 2: scale, shift = self.transformation x1 = (self.startx-shift[0])/scale[0] x2 = (self.canvas.canvasx(event.x)-shift[0])/scale[0] if x1 < x2: self.selected_range = (x1, x2) else: self.selected_range = (x2, x1) if self.selectfn is not None: self.selectfn(self.selected_range) else: self.canvas.delete(self.rectangle) self.rectangle = None self.selected_range = None if self.selectfn is not None: self.selectfn(self.selected_range) self.mouse_state = 0
def getBasis(self): """ Construct a basis for the subspace by orthonormalization of the input vectors using Singular Value Decomposition. The basis consists of a sequence of :class:~MMTK.ParticleProperties.ParticleVector objects that are orthonormal in configuration space. :returns: the basis """ if self._basis is None: basis = N.array([v.array for v in self.vectors], N.Float) shape = basis.shape nvectors = shape[0] natoms = shape[1] basis.shape = (nvectors, 3*natoms) sv = N.zeros((min(nvectors, 3*natoms),), N.Float) min_n_m = min(3*natoms, nvectors) vt = N.zeros((nvectors, min_n_m), N.Float) work = N.zeros((1,), N.Float) iwork = N.zeros((8*min_n_m,), int_type) u, sv, _ = svd(basis) u, sv = N.array(u), N.array(sv) svmax = N.maximum.reduce(sv) nvectors = N.add.reduce(N.greater(sv, 1.e-10*svmax)) u = u[:nvectors] u.shape = (nvectors, natoms, 3) self._basis = ParticleVectorSet(self.universe, u) return self._basis
def findAlphaBeta(self): if self.res_shells is None: return p = self.model_amplitudes*self.exp_amplitudes/self.epsilon t = None alpha = [] beta = [] for rsc, rsa in self.res_shells: a = b = c = d = 0. tw = len(rsc) + 2.*len(rsa) for ri in rsc: a += self.model_amplitudes[ri]**2/self.epsilon[ri] b += self.exp_amplitudes[ri]**2/self.epsilon[ri] c += p[ri] d += p[ri]*p[ri] for ri in rsa: a += 2.*self.model_amplitudes[ri]**2/self.epsilon[ri] b += 2.*self.exp_amplitudes[ri]**2/self.epsilon[ri] c += 2.*p[ri] d += 2.*p[ri]*p[ri] a /= tw b /= tw c /= tw d /= tw if d < a*b: t = 0. else: def g(t): return N.sqrt(1.+4.*a*b*t*t)-2.*t*_l(t, p, rsc, rsa)-1. if t is None: t = 1. while g(t) > 0.: t = t/2. t1 = t while g(t) < 0.: t = 2.*t t2 = t g1 = g(t1) g2 = g(t2) while t2-t1 > 1.e-3*t1: t = t1-g1*(t2-t1)/(g2-g1) gt = g(t) if gt == 0.: break elif gt < 0: t1 = t g1 = gt else: t2 = t g2 = gt s = N.sqrt(1.+4.*a*b*t*t) v = N.sqrt((s-1)/(2*a)) u = N.sqrt((s+1)/(2*b)) alpha.append(v/u) beta.append(1./(u*u)) self.alpha = InterpolatingFunction((self.ssq_av_shell,), N.array([alpha[0]]+alpha+[alpha[-1]])) self.beta = InterpolatingFunction((self.ssq_av_shell,), N.array([beta[0]]+beta+[beta[-1]]))
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data)['harmonic_angle_term'] assert len(params) == 1 indices = N.array([params[0][:3]]) parameters = N.array([params[0][3:]]) return [HarmonicAngleTerm(universe._spec, indices, parameters, self.name)]
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data)['harmonic_distance_term'] assert len(params) == 1 indices = Numeric.array([params[0][:2]]) parameters = Numeric.array([params[0][2:]]) return [HarmonicDistanceTerm(universe._spec, indices, parameters, self.name)]
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data)['cosine_dihedral_term'] assert len(params) == 1 indices = N.array([params[0][:4]]) parameters = N.array([params[0][4:]]) return [CosineDihedralTerm(universe._spec, indices, parameters, self.name)]
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data)['cosine_dihedral_term'] assert len(params) == 1 indices = Numeric.array([params[:4]]) parameters = Numeric.array([params[4:]]) return [ CosineDihedralTerm(universe._spec, indices, parameters, self.name) ]
def evaluatorTerms(self, universe, subset1, subset2, global_data): params = self.evaluatorParameters(universe, subset1, subset2, global_data)['harmonic_angle_term'] assert len(params) == 1 indices = Numeric.array([params[0][:3]]) parameters = Numeric.array([params[0][3:]]) return [ HarmonicAngleTerm(universe._spec, indices, parameters, self.name) ]
def __init__(self, pressure, relaxation_time=1.5): """ :param pressure: the pressure set by the barostat :type pressure: float :param relaxation_time: the relaxation time of the barostat coordinate :type relaxation_time: float """ self.parameters = N.array([pressure, relaxation_time]) self.coordinates = N.array([0.])
def __init__(self, temperature, relaxation_time=0.2): """ :param temperature: the temperature set by the thermostat :type temperature: float :param relaxation_time: the relaxation time of the thermostat coordinate :type relaxation_time: float """ self.parameters = N.array([temperature, relaxation_time]) self.coordinates = N.array([0., 0.])
def __getstate__(self): reflections = [(r.h, r.k, r.l, r.index) for r in self.minimal_reflection_list] absences = [(r.h, r.k, r.l) for r in self.systematic_absences] return (tuple(self.cell.basisVectors()), self.space_group.number, self.s_min, self.s_max, self.compact, self.completeness_range, N.array(reflections), N.array(absences))
def __init__(self, pressure, relaxation_time = 1.5): """ :param pressure: the pressure set by the barostat :type pressure: float :param relaxation_time: the relaxation time of the barostat coordinate :type relaxation_time: float """ self.parameters = N.array([pressure, relaxation_time]) self.coordinates = N.array([0.])
def __init__(self, temperature, relaxation_time = 0.2): """ :param temperature: the temperature set by the thermostat :type temperature: float :param relaxation_time: the relaxation time of the thermostat coordinate :type relaxation_time: float """ self.parameters = N.array([temperature, relaxation_time]) self.coordinates = N.array([0., 0.])
def _setupEIndices(self): indices = [] for i in range(self.nitems): ii = [] ik = [] for k, index in self.index[i].items(): ii.append(index) ik.append(k) indices.append((N.array(ii), N.array(ik))) self.e_indices = indices
def __init__(self, elements, nocheck = None): """ @param elements: 2D array or nested list specifying the nine tensor components [[xx, xy, xz], [yx, yy, yz], [zx, zy, zz]] @type elements: C{Numeric.array} or C{list} """ self.array = N.array(elements) if nocheck is None: if not N.logical_and.reduce(N.equal(N.array(self.array.shape), 3)): raise ValueError('Tensor must have length 3 along any axis') self.rank = len(self.array.shape)
def __init__(self, elements, nocheck=None): """ @param elements: 2D array or nested list specifying the nine tensor components [[xx, xy, xz], [yx, yy, yz], [zx, zy, zz]] @type elements: C{Numeric.array} or C{list} """ self.array = N.array(elements) if nocheck is None: if not N.logical_and.reduce(N.equal(N.array(self.array.shape), 3)): raise ValueError('Tensor must have length 3 along any axis') self.rank = len(self.array.shape)
def memoryFunction(self, nsteps): mz = self.memoryFunctionZ() mem = mz.divide(nsteps - 1)[0].coeff[:] mem.reverse() if len(mem) == nsteps + 1: mem = mem[1:] if isComplex(self.coeff[0]): mem = N.array([complex(m.real, m.imag) for m in mem]) else: mem = N.array([float(m) for m in mem]) mem[0] = 2. * realPart(mem[0]) time = self.delta_t * N.arange(nsteps) return InterpolatingFunction((time, ), mem)
def draw(self, graphics, xaxis = None, yaxis = None): """ Draw something on the canvas @param graphics: the graphics object (L{PolyLine}, L{PolyMarker}, or L{PlotGraphics}) to be drawn @param xaxis: C{None} (no x-axis), C{"automatic"} (automatic scaling), or a pair (x1, x2) defining the range of the x-axis @param yaxis: C{None} (no y-axis), C{"automatic"} (automatic scaling), or a pair (y1, y2) defining the range of the y-axis """ self.last_draw = (graphics, xaxis, yaxis) p1, p2 = graphics.boundingBox() xaxis = self._axisInterval(xaxis, p1[0], p2[0]) yaxis = self._axisInterval(yaxis, p1[1], p2[1]) text_width = [0., 0.] text_height = [0., 0.] if xaxis is not None: p1[0] = xaxis[0] p2[0] = xaxis[1] xticks = self._ticks(xaxis[0], xaxis[1]) bb = self._textBoundingBox(xticks[0][1]) text_height[1] = bb[3]-bb[1] text_width[0] = 0.5*(bb[2]-bb[0]) bb = self._textBoundingBox(xticks[-1][1]) text_width[1] = 0.5*(bb[2]-bb[0]) else: xticks = None if yaxis is not None: p1[1] = yaxis[0] p2[1] = yaxis[1] yticks = self._ticks(yaxis[0], yaxis[1]) for y in yticks: bb = self._textBoundingBox(y[1]) w = bb[2]-bb[0] text_width[0] = max(text_width[0], w) h = 0.5*(bb[3]-bb[1]) text_height[0] = h text_height[1] = max(text_height[1], h) else: yticks = None text1 = Numeric.array([text_width[0], -text_height[1]]) text2 = Numeric.array([text_width[1], -text_height[0]]) scale = (self.plotbox_size-text1-text2) / (p2-p1) shift = -p1*scale + self.plotbox_origin + text1 self.transformation = (scale, shift) self.bbox = (p1, p2) self._drawAxes(self.canvas, xaxis, yaxis, p1, p2, scale, shift, xticks, yticks) graphics.scaleAndShift(scale, shift) graphics.draw(self.canvas, (scale*p1+shift, scale*p2+shift))
def draw(self, graphics, xaxis = None, yaxis = None): """ Draw something on the canvas @param graphics: the graphics object (L{PolyLine}, L{PolyMarker}, or L{PlotGraphics}) to be drawn @param xaxis: C{None} (no x-axis), C{"automatic"} (automatic scaling), or a pair (x1, x2) defining the range of the x-axis @param yaxis: C{None} (no y-axis), C{"automatic"} (automatic scaling), or a pair (y1, y2) defining the range of the y-axis """ self.last_draw = (graphics, xaxis, yaxis) p1, p2 = graphics.boundingBox() xaxis = self._axisInterval(xaxis, p1[0], p2[0]) yaxis = self._axisInterval(yaxis, p1[1], p2[1]) text_width = [0., 0.] text_height = [0., 0.] if xaxis is not None: p1[0] = xaxis[0] p2[0] = xaxis[1] xticks = self._ticks(xaxis[0], xaxis[1]) bb = self._textBoundingBox(xticks[0][1]) text_height[1] = bb[3]-bb[1] text_width[0] = 0.5*(bb[2]-bb[0]) bb = self._textBoundingBox(xticks[-1][1]) text_width[1] = 0.5*(bb[2]-bb[0]) else: xticks = None if yaxis is not None: p1[1] = yaxis[0] p2[1] = yaxis[1] yticks = self._ticks(yaxis[0], yaxis[1]) for y in yticks: bb = self._textBoundingBox(y[1]) w = bb[2]-bb[0] text_width[0] = max(text_width[0], w) h = 0.5*(bb[3]-bb[1]) text_height[0] = h text_height[1] = max(text_height[1], h) else: yticks = None text1 = N.array([text_width[0], -text_height[1]]) text2 = N.array([text_width[1], -text_height[0]]) scale = (self.plotbox_size-text1-text2) / (p2-p1) shift = -p1*scale + self.plotbox_origin + text1 self.transformation = (scale, shift) self.bbox = (p1, p2) self._drawAxes(self.canvas, xaxis, yaxis, p1, p2, scale, shift, xticks, yticks) graphics.scaleAndShift(scale, shift) graphics.draw(self.canvas, (scale*p1+shift, scale*p2+shift))
def _addData(self, data, weights): data = N.array(data, N.Float) weights = N.array(weights, N.Float) mask = N.logical_and(N.less_equal(data, self.max), N.greater_equal(data, self.min)) data = N.repeat(data, mask) weights = N.repeat(weights, mask) data = N.floor((data - self.min)/self.bin_width).astype(N.Int) nbins = self.array.shape[0] histo = N.add.reduce(weights*N.equal(N.arange(nbins)[:,N.NewAxis], data), -1) histo[-1] = histo[-1] + N.add.reduce(N.repeat(weights, N.equal(nbins, data))) self.array[:, 1] = self.array[:, 1] + histo
def test_symmetric_tensors(self): t = N.array([[1., -0.5, 0.3], [-0.5, 2.5, -1.1], [0.3, -1.1, 2.]]) tc = N.array([1., 2.5, 2., -1.1, 0.3, -0.5]) error = largestAbsoluteElement(SymmetricTensor(t).array - tc) self.assert_(error == 0.) for i in range(50): t = SymmetricTensor(randomArray((6, ))) tf = t.array2d tc = SymmetricTensor(tf) error = largestAbsoluteElement(tf - tc.array2d) self.assert_(error == 0.) for i in range(10): t = randomArray((3, 3)) self.assertRaises(ValueError, SymmetricTensor, t)
def paintEvent(self, event): p = QPainter() p.begin(self) p.fillRect(self.rect(), QBrush(self.background_color)) graphics, xaxis, yaxis = self.current_plot p1, p2 = graphics.boundingBox() xaxis = self._axisInterval(xaxis, p1[0], p2[0]) yaxis = self._axisInterval(yaxis, p1[1], p2[1]) text_width = [0., 0.] text_height = [0., 0.] if xaxis is not None: p1[0] = xaxis[0] p2[0] = xaxis[1] xticks = self._ticks(xaxis[0], xaxis[1]) w, h = self._textBoundingBox(p, xticks[0][1]) text_height[1] = h+2 text_width[0] = 0.5*w w, h = self._textBoundingBox(p, xticks[-1][1]) text_width[1] = 0.5*w else: xticks = None if yaxis is not None: p1[1] = yaxis[0] p2[1] = yaxis[1] yticks = self._ticks(yaxis[0], yaxis[1]) for y in yticks: w, h = self._textBoundingBox(p, y[1]) text_width[0] = max(text_width[0], w+2) h = 0.5*h text_height[0] = h text_height[1] = max(text_height[1], h) else: yticks = None text1 = N.array([text_width[0], -text_height[1]]) text2 = N.array([text_width[1], -text_height[0]]) scale = (self.plotbox_size-text1-text2) / (p2-p1) shift = -p1*scale + self.plotbox_origin + text1 self.transformation = (scale, shift) self.bbox = (p1, p2) if self.selected_range is not None: x1 = scale[0]*self.selected_range[0]+shift[0] x2 = scale[0]*self.selected_range[1]+shift[0] p.setPen(QPen(Qt.NoPen)) p.setBrush(QBrush(Qt.gray, Qt.Dense5Pattern)) p.drawRect(x1, 0, x2-x1, self.height()) self._drawAxes(p, xaxis, yaxis, p1, p2, scale, shift, xticks, yticks) graphics.scaleAndShift(scale, shift) graphics.draw(p, (scale*p1+shift, scale*p2+shift)) p.end()
def _writeData(self, item, data, part_first, part_last): try: if len(data) == 0: return except TypeError: pass item = self._indices(item, part_first, part_last) if item is not None: try: self.file.file.variables[self.name][item] = N.array(data) except: print self.file.file.variables[self.name].shape print item print N.array(data).shape raise
def _send(obj, destinations): requests = [] if type(obj) is N.arraytype: send_data = obj try: type_code = send_data.typecode() # Numeric, numarray except AttributeError: type_code = send_data.dtype.char # NumPy tag = _type_tags.get(type_code, 2) if _debug_flag: print world.rank, "sending array (type %s, shape %s) to %s" \ % (type_code, str(obj.shape), str(destinations)) sys.stdout.flush() if tag == 2: send_data = cPickle.dumps(send_data, 1) else: shape = N.array(obj.shape) for pid in destinations: requests.append(world.nonblockingSend(shape, pid, tag)) tag = 1 else: if _debug_flag: print world.rank, "sending non-array object to", destinations sys.stdout.flush() send_data = cPickle.dumps(obj, 1) tag = 2 if _debug_flag: print world.rank, "sending data (%d) to" % tag, destinations sys.stdout.flush() for pid in destinations: requests.append(world.nonblockingSend(send_data, pid, tag)) return requests
def mouseReleaseEvent(self, event): button = event.button() self.setCursor(Qt.arrowCursor) if button == Qt.LeftButton: try: dx = event.x() - self.click1x dy = event.y() - self.click1y except AttributeError: return if dx != 0 or dy != 0: normal = Vector(self.axis) move = Vector(-dx*self.plane[:,0]+dy*self.plane[:,1]) axis = normal.cross(move) / \ N.minimum.reduce(N.fabs(self.plotbox_size)) rot = Rotation(axis.normal(), axis.length()) self.axis = rot(normal).array self.plane[:,0] = rot(Vector(self.plane[:,0])).array self.plane[:,1] = rot(Vector(self.plane[:,1])).array elif button == Qt.MidButton: try: dx = event.x() - self.click2x dy = event.y() - self.click2y except AttributeError: return if dx != 0 or dy != 0: self.translate = self.translate + N.array([dx, dy]) else: try: dy = event.y() - self.click3y except AttributeError: return if dy != 0: ratio = -dy/self.plotbox_size[1] self.scale = self.scale * (1.+ratio) self.update()
def _mouseMotion(self, event): if self.mouse_state == 0: scale, shift = self.transformation p = (Numeric.array([self.startx, self.starty])-shift)/scale bb1, bb2 = self.bbox if self.selectfn is not None and p[1] < bb1[1]: self.mouse_state = 2 self.canvas.delete(self.rectangle) self.rectangle = \ self.canvas.create_rectangle(self.startx, self.starty, self.startx, self.starty, fill='yellow', outline='', stipple='gray50', width=0) self.canvas.lower(self.rectangle) elif self.zoom: self.mouse_state = 1 if self.mouse_state == 1: x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) if (self.startx != event.x) and (self.starty != event.y) : self.canvas.delete(self.rubberband) self.rubberband = self.canvas.create_rectangle(self.startx, self.starty, x, y) self.update_idletasks() elif self.mouse_state == 2: self.canvas.coords(self.rectangle, self.startx, 1., self.canvas.canvasx(event.x), self.height) self.update_idletasks()
def __getitem__(self, item): try: series = self.cache[item] except KeyError: self.calculateProjections([item]) series = self.cache[item] return Numeric.transpose(Numeric.array([self.time, series]))
def test_nonbondedList(self): self.universe.configuration() atoms = self.universe.atomList() atom_indices = N.array([a.index for a in self.universe.atomList()]) empty = N.zeros((0, 2), N.Int) for cutoff in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]: nblist = NonbondedList(empty, empty, atom_indices, self.universe._spec, cutoff) nblist.update(self.universe.configuration().array) distances = nblist.pairDistances() pairs1 = nblist.pairIndices() pairs1 = [sorted_tuple(pairs1[i]) for i in range(len(pairs1)) if distances[i] < cutoff] pairs1.sort(lambda a, b: cmp(a[0], b[0]) or cmp(a[1], b[1])) pairs2 = [] for i in range(len(atoms)): for j in range(i+1, len(atoms)): d = self.universe.distance(atoms[i], atoms[j]) if d < cutoff: pairs2.append(sorted_tuple((atoms[i].index, atoms[j].index))) pairs2.sort(lambda a, b: cmp(a[0], b[0]) or cmp(a[1], b[1])) self.assertEqual(pairs1, pairs2)
def __init__(self, master, trajectory): Tkwindow.__init__(self, master) self.filename = None if type(trajectory) == type(''): if string.find(trajectory, ':') >= 0 and tmanager is not None: self.filename = trajectory self.inspector = tmanager.trajectoryInspector(trajectory) self.inspector.reopen() else: self.filename = trajectory self.inspector = TrajectoryInspector(trajectory) else: self.inspector = TrajectoryInspector(trajectory) if self.filename is not None: self.title(self.filename) self.description = self.inspector.description() self.universe = None self.categories = categorizeVariables(self.inspector.variableNames()) step_number = Numeric.array(self.inspector.readScalarVariable('step')) jumps = Numeric.less(step_number[1:]-step_number[:-1], 0) self.restarts = Numeric.repeat(Numeric.arange(len(jumps)), jumps)+1 self.restarts = list(self.restarts) try: self.time = \ Numeric.array(self.inspector.readScalarVariable('time')) jumps = Numeric.repeat(Numeric.arange(len(self.time)-1), Numeric.less(self.time[1:], self.time[:-1]))+1 if len(jumps) > 0: for jump in jumps[::-1]: dt = self.time[jump-1] + self.time[jump+1] \ - 2*self.time[jump] try: # Numeric typecode = self.time.typecode() except AttributeError: # numpy typecode = self.time.dtype.char self.time[jump:] = (self.time[jump:] + dt).astype(typecode) except KeyError: self.time = 1.*Numeric.arange(self.inspector.numberOfSteps()) self.plotlist = [] self.selection = None self._createMenu() self._createMainBox() self.open()