rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
fields=(Sequence('id', 'int', 'pydouser_id_seq'),
fields=(Sequence('id', 'pydouser_id_seq'),
def getUsers(self): return self.joinTable('id', 'pydouser_pydogroup', 'group_id', 'user_id', PyDOUser, 'id')
fields=(Sequence('id', 'int', 'article_id_seq'), ('title', 'text'), ('body', 'text'), ('creator', 'int'), ('created', 'timestamp'))
fields=(Sequence('id', 'article_id_seq'), 'title', 'body', 'creator', 'created')
def getArticles(self): return Article.getSome(creator=self.id, order='created DESC')
if v != errno.ECONNRESET:
assert v.args if v.args[0] != errno.ECONNRESET:
def _processRequest(sock, addr, protocolImpl):
path=normpath(path) return normpath('%s%s' % (root, path))
path=_normpath(path) return _normpath('%s%s' % (root, path))
def _fixPath(root, path): ## some insurance that we don't escape a given root if not path: return root if not path.startswith('/'): path='/%s' % path path=normpath(path) return normpath('%s%s' % (root, path))
if p in ('format', 'qmark'):
if p in ('format', 'qmark', 'numeric'):
def fget(self): p=self.paramstyle if p in ('format', 'qmark'): return self._values elif p in ('pyformat', 'numeric', 'named'): return self._named_values
elif p in ('pyformat', 'numeric', 'named'):
elif p in ('pyformat', 'named'):
def fget(self): p=self.paramstyle if p in ('format', 'qmark'): return self._values elif p in ('pyformat', 'numeric', 'named'): return self._named_values
class test_unique2(Fixture): tags=alltags[:] table='test_unique2' def setup(self): create="CREATE TABLE %s(id INTEGER UNIQUE NOT NULL, x INTEGER)" \ % self.table c=self.db.cursor() c.execute(create) c.close() class foo(P.PyDO): connectionAlias='pydotest' table='test_unique2' fields=(P.Unique('id'), 'x') self.obj=foo
class test_unique2(base_fixture): use_tables=['D'] tags=alltags def pre(self):
def test_unique1(): class baba(P.PyDO): fields=('x', 'y', 'z') unique=(('x', 'y'),) uniq=list(baba.getUniquenessConstraints()) assert len(uniq)==1 assert uniq[0]==frozenset(('x', 'y'))
foo.new(id=i, x=100)
self.D.new(id=i, x=100)
def setup(self): create="CREATE TABLE %s(id INTEGER UNIQUE NOT NULL, x INTEGER)" \ % self.table c=self.db.cursor() c.execute(create) c.close() class foo(P.PyDO): connectionAlias='pydotest' table='test_unique2' fields=(P.Unique('id'), 'x') self.obj=foo for i in range(20): foo.new(id=i, x=100)
assert self.obj.getUnique(id=15).x==100 assert self.obj.getUnique(id=800)==None def cleanup(self): if self.db.autocommit: c=self.db.cursor() c.execute('drop table %s' % self.table) c.close() else: self.db.rollback()
assert self.D.getUnique(id=15).x==100 assert self.D.getUnique(id=800)==None
def run(self): assert self.obj.getUnique(id=15).x==100 assert self.obj.getUnique(id=800)==None
@tag(*alltags) def test_project5(): create="""CREATE TABLE test_project5 (id INTEGER NOT NULL PRIMARY KEY, x INTEGER)""" insert="""INSERT INTO test_project5 (id, x) VALUES (1, 1)""" db=P.getConnection('pydotest') c=db.cursor() c.execute(create) c.execute(insert) try: class bingo(P.PyDO): connectionAlias='pydotest' tabl...
class test_project5(base_fixture): usetables=['D'] tags=alltags def pre(self): self.D.new(id=1, x=1) def run(self): r1=self.D.getUnique(id=1)
def test_project4(): class torte4(P.PyDO): fields=(P.Sequence('id'), 'title', 'x', 'y', 'z') foo=torte4.project(P.Field('id'), 'title', 'x', 'y') assert not foo.getSequences(), "expected no sequences, got: %s" % str(foo.getSequences()) assert len(foo.getUniquenessConstraints())==0
r2=bingo.project('x').getSome()[0]
r2=self.D.project('x').getSome()[0]
def test_project5(): create="""CREATE TABLE test_project5 (id INTEGER NOT NULL PRIMARY KEY, x INTEGER)""" insert="""INSERT INTO test_project5 (id, x) VALUES (1, 1)""" db=P.getConnection('pydotest') c=db.cursor() c.execute(create) c.execute(insert) try: class bingo(P.PyDO): connectionAlias='pydotest' table='test_project...
finally: if db.autocommit: c.execute('drop table test_project5') else: db.rollback() c.close()
def test_project5(): create="""CREATE TABLE test_project5 (id INTEGER NOT NULL PRIMARY KEY, x INTEGER)""" insert="""INSERT INTO test_project5 (id, x) VALUES (1, 1)""" db=P.getConnection('pydotest') c=db.cursor() c.execute(create) c.execute(insert) try: class bingo(P.PyDO): connectionAlias='pydotest' table='test_project...
def run(self): pass
def cleanup(self): if self.db.autocommit: c=self.db.cursor() c.execute('drop table test_update1') c.close() else: self.db.rollback()
happens when a module called InitAlias is reloaded) are permitted.
happens when a module calling initAlias is reloaded) are permitted.
def initAlias(alias, driver, connectArgs, cache=False, verbose=False): """initializes a connection alias with the stated connection arguments. It can cause confusion to let this be called repeatedly; you might think you are initializing it one way and not realize it is being initialized elsewhere differently. Therefo...
self.compname=relpath(compname)
self.compname=computils.relpath(compname)
def __init__(self, name, compname, comptype=None, cache=computils.NO, **kw): Slot.__init__(self, name) self.compname=relpath(compname) if comptype is None: self.comptype=guess_comptype(compname) self.cache=cache self.extra=kw
self.comptype=guess_comptype(compname)
self.comptype=computils.guess_comptype(compname)
def __init__(self, name, compname, comptype=None, cache=computils.NO, **kw): Slot.__init__(self, name) self.compname=relpath(compname) if comptype is None: self.comptype=guess_comptype(compname) self.cache=cache self.extra=kw
res=include(self.compname)
res=computils.include(self.compname)
def __call__(self, **kwargs): cache=kwargs.pop('cache', self.cache) kwargs.update(self.extra) try: push_slot(self.name) if self.comptype==DT_INCLUDE: res=include(self.compname) else: res=component(self.compname, comptype=self.comptype, cache=cache, **kwargs)
res=component(self.compname, comptype=self.comptype, cache=cache, **kwargs)
res=computils.component(self.compname, comptype=self.comptype, cache=cache, **kwargs)
def __call__(self, **kwargs): cache=kwargs.pop('cache', self.cache) kwargs.update(self.extra) try: push_slot(self.name) if self.comptype==DT_INCLUDE: res=include(self.compname) else: res=component(self.compname, comptype=self.comptype, cache=cache, **kwargs)
def __init__(self, connectArgs, cache=False, verbose=False): if cache and not hasattr(cache, 'connect'): cache=PsycopgCache() super(PsycopgDBI, self).__init__(connectArgs, cache, verbose)
def __init__(self, connectArgs, pool=None, verbose=False): if pool and not hasattr(pool, 'connect'): pool=ConnectionPool() super(PsycopgDBI, self).__init__(connectArgs, psycopg.connect, pool, verbose)
def __init__(self, connectArgs, cache=False, verbose=False): if cache and not hasattr(cache, 'connect'): cache=PsycopgCache() super(PsycopgDBI, self).__init__(connectArgs, cache, verbose)
def _connect(self): return psycopg.connect(self.connectArgs)
def _connect(self): return psycopg.connect(self.connectArgs)
def execute(self, sql, values=(), fields=(), qualified=False):
def execute(self, sql, values=(), qualified=False):
def execute(self, sql, values=(), fields=(), qualified=False): """Executes the statement with the values and does conversion of the return result as necessary. result is list of dictionaries, or number of rows affected""" if self.verbose: debug("SQL: %s", sql) debug("bind variables: %s", values) c=self.conn.cursor() if...
class PsycopgCache(ConnectionCache): def real_connect(self, connectArgs): return psycopg.connect(**connectArgs)
def getSequence(self, name): cur=self.conn.cursor() sql="select nextval('%s')" % name if self.verbose: debug("SQL: %s", (sql,)) cur.execute(sql) res=cur.fetchone() if not res: raise PyDOError, "could not get value for sequence %s!" % name return res[0]
if hasattr(Configuration, 'groupToRunAs'): gid = grp.getgrnam(Configuration.groupToRunAs)[2] os.setgid(gid)
groupToRunAs=getattr(Configuration, 'groupToRunAs', None) userToRunAs=getattr(Configuration, 'userToRunAs', None) if groupToRunAs is not None or userToRunAs is not None: try: seteuid=os.seteuid except AttributeError: pass else: seteuid(os.getuid()) if groupToRunAs is not None: gid = grp.getgrnam(groupToRunAs)[2] ...
def run(self): import Hooks
if hasattr(Configuration, 'userToRunAs'): uid = pwd.getpwnam(Configuration.userToRunAs)[2] if hasattr(os, 'seteuid'): os.seteuid(os.getuid()) os.setuid(uid)
if userToRunAs is not None: uid = pwd.getpwnam(userToRunAs)[2] os.setuid(uid)
def run(self): import Hooks
elif isinstance(unique, (list,tuple)):
elif isinstance(unique, (frozenset,list,tuple)):
def _matchUnique(cls, kw): """return a tuple of column names that will uniquely identify a row given the choices from kw """ for unique in cls._unique: if isinstance(unique, (unicode,str)): if kw.get(unique)!=None: return (unique,) elif isinstance(unique, (list,tuple)): for u in unique: if not kw.has_key(u): break else...
if not results:
if not results or not isinstance(results, (list,tuple)):
def getUnique(cls, **fieldData): """ Retrieve one particular instance of this class. Given the attribute/value pairs in fieldData, retrieve a unique row and return a data class instance representing said row or None if no row was retrieved. """ cls._validateFields(fieldData) conn = cls.getDBI() where, values = cls._un...
return conn.execute(query, values)
return conn.execute(' '.join(query), values)
def deleteSome(cls, *args, **fieldData): """delete possibly many records at once, and return the number deleted""" if not cls.mutable: raise ValueError, "cannot deleteSome through an immutable class" conn=cls.getDBI() sql, values=cls._processWhere(conn, args, fieldData) query=["DELETE FROM %s" % cls.getTable()] if sql:...
raise ValueError, "value not present in domain: %s" % value
raise ValueError, "value for '%s' not present in domain: %s" % (self, name, value)
def checkValue(self, value): """ determines whether the value is permissible for the field. This is not meant to perform validation of user input, but to prevent programmatic errors. """ value=Field.checkValue(self, value) if not self.in_domain(value): raise ValueError, "value not present in domain: %s" % value return ...
return self.http_error(status, message, mimetype, template)
return self.http_error(401, message, mimetype, template)
def do401(self, message=None, mimetype=None, template=None): return self.http_error(status, message, mimetype, template)
f=Field(f)
f=cls._create_field(f)
def __init__(cls, cl_name, bases, namespace):
f=Field(**f)
f=cls._create_field(**f)
def __init__(cls, cl_name, bases, namespace):
f=Field(*f)
f=cls._create_field(*f)
def __init__(cls, cl_name, bases, namespace):
@classmethod def getTable(cls):
@staticmethod def _create_field(*args, **kwargs): """ controls how fields are created when declared in the field list with a simple string, list, tuple, or dictionary rather than a field instance. By default, passes field declaration to the Field constructor. """ return Field(*args, **kwargs) @classmethod def getTab...
def __init__(cls, cl_name, bases, namespace):
if any. If cls._guess_tablename is True and no table name has been defined, the class name will be used.
if any, is withSchema is true. If cls._guess_tablename is True and no table name has been defined, the class name will be used.
def getTable(cls): """returns the name of the table, qualified with the schema, if any. If cls._guess_tablename is True and no table name has been defined, the class name will be used. """ if cls.table is None and cls._guess_tablename: table=cls.__name__.lower() else: table=cls.table if cls.schema: return '%s.%s' % (...
if cls.schema:
if cls.schema and withSchema:
def getTable(cls): """returns the name of the table, qualified with the schema, if any. If cls._guess_tablename is True and no table name has been defined, the class name will be used. """ if cls.table is None and cls._guess_tablename: table=cls.__name__.lower() else: table=cls.table if cls.schema: return '%s.%s' % (...
table=cls.getTable(),
table=cls.getTable(False),
def project(cls, fields): s=[] for f in fields: if isinstance(f, Field): s.append(f.name.lower()) elif isinstance(f, str): s.append(f.lower()) elif isinstance(f, tuple): if not len(f): raise ValueError, "empty tuple in field list" s.append(f[0].lower()) else: raise ValueError, "weird thing in field list: %s" % f s.sort...
return self.__class__(dict(self).copy())
return self.__class__(dict(self))
def copy(self): return self.__class__(dict(self).copy())
if not self.unique:
if not self._unique:
def delete(self): """remove the row that represents me in the database""" if not self.mutable: # this used to be a value error, but there are no parameters, # so I'm using PyDOError raise PyDOError, "instance isn't mutable!" if not self.unique: raise PyDOError, "cannot delete, no unique index!" conn = self.getDBI() uni...
debug(unique)
def _uniqueWhere(cls, conn, kw): """given a connection and kw, using _matchUnique, generate a where clause to select a unique row. """ unique = cls._matchUnique(kw) debug(unique) if not unique: raise ValueError, 'No way to get unique row! %s %s' % \ (str(kw), unique) converter=conn.getConverter() if len(unique)==1: sql...
print uniq
def test_guess_columns1(): create="""CREATE TABLE test_guess_columns1 ( id %s PRIMARY KEY, x INTEGER NOT NULL UNIQUE, y INTEGER NOT NULL, z INTEGER UNIQUE, r1 INTEGER NOT NULL, r2 INTEGER NOT NULL, UNIQUE (r1, r2) )""" % dict(sqlite='INTEGER NOT NULL', psycopg='SERIAL', mysql='INTEGER NOT NULL AUTO INCREMENT')[config.D...
db.commit()
db.rollback()
def test_guess_columns1(): create="""CREATE TABLE test_guess_columns1 ( id %s PRIMARY KEY, x INTEGER NOT NULL UNIQUE, y INTEGER NOT NULL, z INTEGER UNIQUE, r1 INTEGER NOT NULL, r2 INTEGER NOT NULL, UNIQUE (r1, r2) )""" % dict(sqlite='INTEGER NOT NULL', psycopg='SERIAL', mysql='INTEGER NOT NULL AUTO INCREMENT')[config.D...
return '(%s %s)' % (op, self._convert(self[1]))
return '(%s %s)' % (self[0], self._convert(self[1]))
def _repr_single(self): return '(%s %s)' % (op, self._convert(self[1]))
if len(values)==1 and isinstance(values, dict):
if len(values)==1 and isinstance(values[0], dict):
def iterfetch(resultSpec, sqlTemplate, *values, **kwargs): """ a method that executes sql and returns rows of tuples of PyDO objects and scalar values, ordered according to a result set specification. resultSpec is a list that may contain: * PyDO classes; * 2-tuples of (PyDO class, alias string), which indicate that...
return self._dict.get(item, default) or default
return self._dict.get(item, default)
def get(self, item, default = None): """returns self[item] if it exists and is not None, otherwise returns default""" return self._dict.get(item, default) or default
except Response:
except Response, res:
def controllerHandler(connection, sessionDict): if not Cfg.MvcOn: return cname=sessionDict.get('CONTROLLER') data=sessionDict.get('CONTROLLER_ARGS') aname=sessionDict.get('ACTION') debug("do we have a controller? %s", ('No', 'Yes')[bool(cname)]) if cname: c=Cfg.controllers.get(cname) if c: if isinstance(c, basestring)...
sequenced={'id' : 'pydouser_id_seq'} unique=['id'] fields=('id',
fields=(Sequence('id', 'int', 'pydouser_id_seq'),
def getUsers(self): return self.joinTable('id', 'pydouser_pydogroup', 'group_id', 'user_id', PyDOUser, 'id')
sequenced={'id': 'article_id_seq'} unique=['id'] fields=(('id', 'int'),
fields=(Sequence('id', 'int', 'article_id_seq'),
def getArticles(self): return Article.getSome(creator=self.id, order='created DESC')
return _testsForNamespace(vars(m), namePat, *tags)
return _testsForNamespace(vars(m), namePat, tags)
def _testsForModule(m, namePat, tags): return _testsForNamespace(vars(m), namePat, *tags)
__slots__=('_conn', '_pool')
__slots__=('_conn', '_pool', '_closed')
def getConnection(alias): """get a connection given a connection alias""" _connlock.acquire() try: try: conndata=_aliases[alias] except KeyError: raise ValueError, "alias %s not recognized" % alias if not conndata.has_key('connection'): res=_connect(**conndata) conndata['connection']=res return res return conndata['con...
self.close()
if not self._closed: self.close()
def __del__(self): self.close()
keep=keep_poolsize<numconns
keep=keep_poolsize <= numconns
def release(self, conn): keep_poolsize=self._keep_poolsize self._lock.acquire() try: # do we keep this connection? free=self._free busy=self._busy numconns=len(free)+len(busy) keep=keep_poolsize<numconns busy.remove(conn) if keep: free.append(conn) self.onRelease(conn) finally: self._lock.release()
adopt_init_args(self, locals(), hide=0001)
def __init__(self, unit_cell, d_min=None, resolution_factor=None, step=None, symmetry_flags=None, space_group_info=None, mandatory_factors=None, max_prime=5, assert_shannon_sampling=0001): adopt_init_args(self, locals(), hide=0001) assert [d_min, step].count(None) == 1 if (step is not None): d_min = step*2 resolution_f...
adopt_init_args(self, locals(), hide=0001)
def __init__(self, peak_list, special_position_settings, general_positions_only=00000, min_cross_distance=None, max_clusters=None): adopt_init_args(self, locals(), hide=0001) if (min_cross_distance is None): min_cross_distance = special_position_settings.min_distance_sym_equiv() self._gridding = peak_list.gridding() se...
def complete_set(self, d_min_tolerance=1.e-6):
def complete_set(self, d_min_tolerance=1.e-6, d_max=None):
def complete_set(self, d_min_tolerance=1.e-6): assert self.anomalous_flag() in (False, True) if (self.indices().size() == 0): return set( crystal_symmetry=self, anomalous_flag=self.anomalous_flag(), indices=flex.miller_index()) return build_set( crystal_symmetry=self, anomalous_flag=self.anomalous_flag(), d_min=self.d_...
d_min=self.d_min()*(1-d_min_tolerance))
d_min=self.d_min()*(1-d_min_tolerance), d_max=d_max)
def complete_set(self, d_min_tolerance=1.e-6): assert self.anomalous_flag() in (False, True) if (self.indices().size() == 0): return set( crystal_symmetry=self, anomalous_flag=self.anomalous_flag(), indices=flex.miller_index()) return build_set( crystal_symmetry=self, anomalous_flag=self.anomalous_flag(), d_min=self.d_...
return_fail=None):
return_fail=None, d_max = None):
def completeness(self, use_binning=False, d_min_tolerance=1.e-6, return_fail=None): if (not use_binning): complete_set = self.complete_set(d_min_tolerance=d_min_tolerance) return self.indices().size() / max(1,complete_set.indices().size()) assert self.binner() is not None data = [] for n_given,n_complete in zip(self.bi...
complete_set = self.complete_set(d_min_tolerance=d_min_tolerance)
complete_set = self.complete_set(d_min_tolerance=d_min_tolerance, d_max = d_max)
def completeness(self, use_binning=False, d_min_tolerance=1.e-6, return_fail=None): if (not use_binning): complete_set = self.complete_set(d_min_tolerance=d_min_tolerance) return self.indices().size() / max(1,complete_set.indices().size()) assert self.binner() is not None data = [] for n_given,n_complete in zip(self.bi...
def build_set(crystal_symmetry, anomalous_flag, d_min): return set(
def build_set(crystal_symmetry, anomalous_flag, d_min, d_max=None): result = set(
def build_set(crystal_symmetry, anomalous_flag, d_min): return set( crystal_symmetry, index_generator( crystal_symmetry.unit_cell(), crystal_symmetry.space_group_info().type(), anomalous_flag, d_min).to_array(), anomalous_flag)
def show_summary(self, f=sys.stdout): print >> f, "Space group: %s (No. %d)" % ( str(self), self.type().number())
def show_summary(self, f=sys.stdout, prefix="Space group: "): print >> f, "%s%s (No. %d)" % ( prefix, str(self), self.type().number())
def show_summary(self, f=sys.stdout): print >> f, "Space group: %s (No. %d)" % ( str(self), self.type().number())
def d_target_d_dalphas_finite(obs, alphas, eps=1.e-8):
def d_target_d_alphas_finite(obs, alphas, eps=1.e-8):
def d_target_d_dalphas_finite(obs, alphas, eps=1.e-8): result = [] for i_alpha in xrange(len(alphas)): alphas_eps = list(alphas) ts = [] for signed_eps in [eps, -eps]: alphas_eps[i_alpha] = alphas[i_alpha] + signed_eps exp_sum = exp_i_alpha_sum(alphas=alphas_eps) target = least_squares(obs=obs, calc=exp_sum.f()) ts.app...
grads_fin = d_target_d_dalphas_finite(obs=obs, alphas=alphas)
grads_fin = d_target_d_alphas_finite(obs=obs, alphas=alphas)
def compare_analytical_and_finite(obs, alphas, out): grads_fin = d_target_d_dalphas_finite(obs=obs, alphas=alphas) print >> out, "grads_fin:", grads_fin exp_sum = exp_i_alpha_sum(alphas=alphas) target = least_squares(obs=obs, calc=exp_sum.f()) grads_ana = exp_sum.d_target_d_alphas(target=target) print >> out, "grads_an...
def path_exists(self): return os.path.exists(self.path)
def full_path(self, path_prefix=None): if (path_prefix is None): return self.path return os.path.join(path_prefix, self.path)
def path_exists(self): return os.path.exists(self.path)
def current_mtime(self): if (not self.path_exists()): return None return os.path.getmtime(self.path)
def current_mtime(self, path_prefix=None): full_path = self.full_path(path_prefix=path_prefix) if (not os.path.exists(full_path)): return None return os.path.getmtime(full_path)
def current_mtime(self): if (not self.path_exists()): return None return os.path.getmtime(self.path)
def current_md5(self): if (not self.path_exists()): return None
def current_md5(self, path_prefix=None): full_path = self.full_path(path_prefix=path_prefix) if (not os.path.exists(full_path)): return None
def current_md5(self): if (not self.path_exists()): return None m = md5.new() m.update(open(self.path, "rb").read()) return m.hexdigest()
m.update(open(self.path, "rb").read())
m.update(open(full_path, "rb").read())
def current_md5(self): if (not self.path_exists()): return None m = md5.new() m.update(open(self.path, "rb").read()) return m.hexdigest()
def has_changed(self, mtime_resolution=2):
def has_changed(self, path_prefix=None, mtime_resolution=2):
def has_changed(self, mtime_resolution=2): old_mtime = self.mtime if (old_mtime is None): return True self.mtime = self.current_mtime() if (self.mtime == old_mtime and time.time() > old_mtime + mtime_resolution): return False if (self.md5 is None): return True old_md5 = self.md5 self.md5 = self.current_md5() return sel...
self.mtime = self.current_mtime()
self.mtime = self.current_mtime(path_prefix=path_prefix)
def has_changed(self, mtime_resolution=2): old_mtime = self.mtime if (old_mtime is None): return True self.mtime = self.current_mtime() if (self.mtime == old_mtime and time.time() > old_mtime + mtime_resolution): return False if (self.md5 is None): return True old_md5 = self.md5 self.md5 = self.current_md5() return sel...
self.md5 = self.current_md5()
self.md5 = self.current_md5(path_prefix=path_prefix)
def has_changed(self, mtime_resolution=2): old_mtime = self.mtime if (old_mtime is None): return True self.mtime = self.current_mtime() if (self.mtime == old_mtime and time.time() > old_mtime + mtime_resolution): return False if (self.md5 is None): return True old_md5 = self.md5 self.md5 = self.current_md5() return sel...
def eval_needs_update(self, source_path=None):
def eval_needs_update(self, source_path=None, path_prefix=None):
def eval_needs_update(self, source_path=None): if (source_path != self.source.path): self.source = node_info(path=source_path) self.needs_update = True elif (not self.needs_update): if ( self.source.has_changed() or self.target.has_changed()): self.needs_update = True return self.needs_update
if ( self.source.has_changed() or self.target.has_changed()):
if ( self.source.has_changed(path_prefix=path_prefix) or self.target.has_changed(path_prefix=path_prefix)):
def eval_needs_update(self, source_path=None): if (source_path != self.source.path): self.source = node_info(path=source_path) self.needs_update = True elif (not self.needs_update): if ( self.source.has_changed() or self.target.has_changed()): self.needs_update = True return self.needs_update
def start_building_target(self):
def start_building_target(self, path_prefix=None):
def start_building_target(self): if (self.source.mtime is None): self.source.mtime = self.source.current_mtime() if (self.source.md5 is None): self.source.md5 = self.source.current_md5()
self.source.mtime = self.source.current_mtime()
self.source.mtime = self.source.current_mtime(path_prefix=path_prefix)
def start_building_target(self): if (self.source.mtime is None): self.source.mtime = self.source.current_mtime() if (self.source.md5 is None): self.source.md5 = self.source.current_md5()
self.source.md5 = self.source.current_md5()
self.source.md5 = self.source.current_md5(path_prefix=path_prefix)
def start_building_target(self): if (self.source.mtime is None): self.source.mtime = self.source.current_mtime() if (self.source.md5 is None): self.source.md5 = self.source.current_md5()
def done_building_target(self): self.target.mtime = self.target.current_mtime() self.target.md5 = self.target.current_md5()
def done_building_target(self, path_prefix=None): self.target.mtime = self.target.current_mtime(path_prefix=path_prefix) self.target.md5 = self.target.current_md5(path_prefix=path_prefix)
def done_building_target(self): self.target.mtime = self.target.current_mtime() self.target.md5 = self.target.current_md5() self.needs_update = False
def pair_info(self, source_path, target_path):
def pair_info(self, source_path, target_path, path_prefix=None):
def pair_info(self, source_path, target_path): result = self.pair_infos.get(target_path) if (result is None): result = pair_info(source_path=source_path, target_path=target_path) self.pair_infos[target_path] = result else: result.eval_needs_update(source_path=source_path) return result
result.eval_needs_update(source_path=source_path)
result.eval_needs_update( source_path=source_path, path_prefix=path_prefix)
def pair_info(self, source_path, target_path): result = self.pair_infos.get(target_path) if (result is None): result = pair_info(source_path=source_path, target_path=target_path) self.pair_infos[target_path] = result else: result.eval_needs_update(source_path=source_path) return result
assert approx_equal( grad, correct )
assert approx_equal( grad, correct, eps=1e-4 )
def exercise_real_space_refinement(): unit_cell=130.45,130.245,288.405,90,90,120 unit_cell_gridding_n=144,144,360 grid_cell=uctbx.unit_cell((130.45/144,130.245/144,388.405/360,90,90,120)) grid_mat = grid_cell.fractionalization_matrix() map = test_map.deep_copy() map.resize(flex.grid((-1,-2,-1),(3,3,5))) sites_cart = fl...
assert self.target_name in ("ls_wunit_k1","ls_wunit_k2","ls_wunit_kunit", "ls_wexp_k1" ,"ls_wexp_k2" ,"ls_wexp_kunit", "ls_wff_k1" ,"ls_wff_k2" ,"ls_wff_kunit", "lsm_k1" ,"lsm_k2" ,"lsm_kunit", "ml","mlhl")
assert self.target_name in ( "ls_wunit_k1","ls_wunit_k2","ls_wunit_kunit","ls_wunit_k1_fixed", "ls_wunit_k1ask3_fixed", "ls_wexp_k1" ,"ls_wexp_k2" ,"ls_wexp_kunit", "ls_wff_k1" ,"ls_wff_k2" ,"ls_wff_kunit","ls_wff_k1_fixed", "ls_wff_k1ask3_fixed", "lsm_k1" ,"lsm_k2" ,"lsm_kunit", "ml","mlhl")
def __init__(self, target_name, f_obs, flags, abcd = None, weights = None, use_sigmas_as_weights = False, scale_factor = 0): adopt_init_args(self, locals()) assert self.target_name in ("ls_wunit_k1","ls_wunit_k2","ls_wunit_kunit", "ls_wexp_k1" ,"ls_wexp_k2" ,"ls_wexp_kunit", ...
assert self.target_name.count("ls")+self.target_name.count("k") == 2
assert self.target_name.count("ls") == 1
def __init__(self, target_name, f_obs, flags, abcd = None, weights = None, use_sigmas_as_weights = False, scale_factor = 0): adopt_init_args(self, locals()) assert self.target_name in ("ls_wunit_k1","ls_wunit_k2","ls_wunit_kunit", "ls_wexp_k1" ,"ls_wexp_k2" ,"ls_wexp_kunit", ...
if(self.target_name.count("k1") == 1):
if(self.target_name.count("k1") == 1 and self.target_name.count("k1as") == 0):
def target_functor_w(self, selection = None): if(selection is None): f_obs = self.f_obs_w weights = self.weights_w abcd = self.abcd_w else: assert selection.size() == self.f_obs_w.data().size() f_obs = self.f_obs_w.select(selection) if(self.weights_w is not None): weights = self.weights_w.select(selection) else: ...
if(self.target_name.count("k2") == 1):
if(self.target_name.count("k2") == 1 and self.target_name.count("k2as") == 0):
def target_functor_w(self, selection = None): if(selection is None): f_obs = self.f_obs_w weights = self.weights_w abcd = self.abcd_w else: assert selection.size() == self.f_obs_w.data().size() f_obs = self.f_obs_w.select(selection) if(self.weights_w is not None): weights = self.weights_w.select(selection) else: ...
if(self.target_name.count("kunit") == 1): assert self.scale_factor == 1
if(self.target_name.count("kunit") == 1 or self.target_name.count("ask") == 1): assert self.scale_factor != 0.0
def target_functor_w(self, selection = None): if(selection is None): f_obs = self.f_obs_w weights = self.weights_w abcd = self.abcd_w else: assert selection.size() == self.f_obs_w.data().size() f_obs = self.f_obs_w.select(selection) if(self.weights_w is not None): weights = self.weights_w.select(selection) else: ...
if(self.target_name.count("k1") == 1):
if(self.target_name.count("k1") == 1 and self.target_name.count("k1as") == 0):
def target_functor_t(self, selection = None): if(selection is None): f_obs = self.f_obs_t weights = self.weights_t abcd = self.abcd_t else: assert selection.size() == self.f_obs_t.data().size() f_obs = self.f_obs_t.select(selection) if(self.weights_t is not None): weights = self.weights_t.select(selection) else: ...
if(self.target_name.count("k2") == 1):
if(self.target_name.count("k2") == 1 and self.target_name.count("k2as") == 0):
def target_functor_t(self, selection = None): if(selection is None): f_obs = self.f_obs_t weights = self.weights_t abcd = self.abcd_t else: assert selection.size() == self.f_obs_t.data().size() f_obs = self.f_obs_t.select(selection) if(self.weights_t is not None): weights = self.weights_t.select(selection) else: ...
if(self.target_name.count("kunit") == 1): assert self.scale_factor == 1
if(self.target_name.count("kunit") == 1 or self.target_name.count("ask") == 1): assert self.scale_factor != 0.0
def target_functor_t(self, selection = None): if(selection is None): f_obs = self.f_obs_t weights = self.weights_t abcd = self.abcd_t else: assert selection.size() == self.f_obs_t.data().size() f_obs = self.f_obs_t.select(selection) if(self.weights_t is not None): weights = self.weights_t.select(selection) else: ...
def __init__(self, symbol=None, table_id=None, group=None, number=None):
def __init__(self, symbol=None, table_id=None, group=None, number=None, space_group_t_den=None):
def __init__(self, symbol=None, table_id=None, group=None, number=None): assert [symbol, group, number].count(None) >= 2 if (number is not None): symbol = str(number) if (symbol is None): assert table_id is None self._group = group else: assert group is None if (table_id is None): self._group = space_group(space_group_...
self._group = space_group(space_group_symbols(symbol))
symbols = space_group_symbols(symbol)
def __init__(self, symbol=None, table_id=None, group=None, number=None): assert [symbol, group, number].count(None) >= 2 if (number is not None): symbol = str(number) if (symbol is None): assert table_id is None self._group = group else: assert group is None if (table_id is None): self._group = space_group(space_group_...
self._group = space_group(space_group_symbols(symbol, table_id))
symbols = space_group_symbols(symbol, table_id) if (space_group_t_den is None): self._group = space_group( space_group_symbols=symbols) else: self._group = space_group( space_group_symbols=symbols, t_den=space_group_t_den)
def __init__(self, symbol=None, table_id=None, group=None, number=None): assert [symbol, group, number].count(None) >= 2 if (number is not None): symbol = str(number) if (symbol is None): assert table_id is None self._group = group else: assert group is None if (table_id is None): self._group = space_group(space_group_...
print "Number of scatterers:", self.scatterers().size() print "At special positions:", self.special_position_indices().size()
print >> f, "Number of scatterers:", self.scatterers().size() print >> f, "At special positions:", self.special_position_indices().size()
def show_summary(self, f=sys.stdout): print "Number of scatterers:", self.scatterers().size() print "At special positions:", self.special_position_indices().size() crystal.symmetry.show_summary(self, f) return self
print "Label M Coordinates Occ Uiso or Ustar"
print >> f, "Label M Coordinates Occ Uiso or Ustar"
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,),
print >> f, "%-4s" % (scatterer.label,), print >> f, "%3d" % (scatterer.multiplicity(),), print >> f, "%7.4f %7.4f %7.4f" % scatterer.site, print >> f, "%4.2f" % (scatterer.occupancy,),
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
print "%6.4f" % (scatterer.u_iso,),
print >> f, "%6.4f" % (scatterer.u_iso,),
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
print ("%6.3f " * 5 + "%6.3f") % adptbx.u_star_as_u_cart(
print >> f, ("%6.3f " * 5 + "%6.3f") % adptbx.u_star_as_u_cart(
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
print
print >> f
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
print " fp,fdp = %6.4f,%6.4f" % (
print >> f, " fp,fdp = %6.4f,%6.4f" % (
def show_scatterers(self, f=sys.stdout): print "Label M Coordinates Occ Uiso or Ustar" for scatterer in self.scatterers(): print "%-4s" % (scatterer.label,), print "%3d" % (scatterer.multiplicity(),), print "%7.4f %7.4f %7.4f" % scatterer.site, print "%4.2f" % (scatterer.occupancy,), if (not scatterer.ani...
def assert_no_duplicates(self):
def have_duplicates(self):
def assert_no_duplicates(self): n_cosets = len(self.double_cosets) for ics in xrange(n_cosets): tmp_cs = self.double_cosets[ics] for jcs in xrange(n_cosets): if ics != jcs : tmp_cs_2 = self.double_cosets[jcs] # now check each element of tmp_cs for hi in tmp_cs: assert( not self.is_in_coset(hi, tmp_cs_2) )
assert( not self.is_in_coset(hi, tmp_cs_2) )
if (self.is_in_coset(hi, tmp_cs_2)): return True return False
def assert_no_duplicates(self): n_cosets = len(self.double_cosets) for ics in xrange(n_cosets): tmp_cs = self.double_cosets[ics] for jcs in xrange(n_cosets): if ics != jcs : tmp_cs_2 = self.double_cosets[jcs] # now check each element of tmp_cs for hi in tmp_cs: assert( not self.is_in_coset(hi, tmp_cs_2) )
from cctbx import sgtbx
def test_double_coset_decomposition(): from cctbx.sgtbx import subgroups from cctbx import sgtbx for space_group_number in xrange(17,44): parent_group_info = sgtbx.space_group_info(space_group_number) subgrs = subgroups.subgroups(parent_group_info).groups_parent_setting() g = parent_group_info.group() for h1 in subgrs...
tmp_new = double_unique_new(g, h1, h2) tmp_new.assert_no_duplicates()
tmp_new = double_cosets(g, h1, h2) assert not tmp_new.have_duplicates()
def test_double_coset_decomposition(): from cctbx.sgtbx import subgroups from cctbx import sgtbx for space_group_number in xrange(17,44): parent_group_info = sgtbx.space_group_info(space_group_number) subgrs = subgroups.subgroups(parent_group_info).groups_parent_setting() g = parent_group_info.group() for h1 in subgrs...
for colum_group in column_groups: result.append(colum_group)
for column_group in column_groups: info = info_prefix + column_group.info() result.append(column_group.set_info(info))
def as_miller_arrays(self, crystal_symmetry=None, force_symmetry=00000, info_prefix=""): other_symmetry = crystal_symmetry result = [] for i_crystal in xrange(self.ncrystals()): cryst = self.getCrystal(i_crystal) crystal_symmetry = crystal.symmetry( unit_cell=cryst.get_unit_cell(), space_group_info=self.get_space_group...