code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if (self.key or self.secret): return self.update() server_data = self.request(server) self.key = server_data["client_id"] self.secret = server_data["client_secret"] self.expirey = server_data["expires_at"]
def register(self, server=None)
Registers the client with the Pump API retrieving the id and secret
4.763598
4.078254
1.168048
error = "" if self.key is None: error = "To update a client you need to provide a key" if self.secret is None: error = "To update a client you need to provide the secret" if error: raise ClientException(error) self.request() ...
def update(self)
Updates the information the Pump server has about the client
4.793104
4.647406
1.03135
import distutils.sysconfig import distutils.ccompiler import tempfile import shutil from textwrap import dedent # common vars libraries = ['rrd'] include_dirs = [package_dir, '/usr/local/include'] library_dirs = ['/usr/local/lib'] compiler_args = dict( libraries=li...
def compile_extensions(macros, compat=False)
Compiler subroutine to test whether some functions are available on the target system. Since the rrdtool headers shipped with most packages do not disclose any versioning information, we cannot test whether a given function is available that way. Instead, use this to manually try to compile code and see...
3.138013
3.04603
1.030198
if self._members is None: self._members = Feed(self.links["members"], pypump=self._pump) return self._members
def members(self)
:class:`Feed <pypump.models.feed.Feed>` of collection members.
12.423948
4.879941
2.545922
activity = { "verb": "add", "object": { "objectType": obj.object_type, "id": obj.id }, "target": { "objectType": self.object_type, "id": self.id } } self._post_ac...
def add(self, obj)
Adds a member to the collection. :param obj: Object to add. Example: >>> mycollection.add(pump.Person('bob@example.org'))
4.20105
5.028156
0.835505
activity = { "verb": "remove", "object": { "objectType": obj.object_type, "id": obj.id }, "target": { "objectType": self.object_type, "id": self.id } } self._post...
def remove(self, obj)
Removes a member from the collection. :param obj: Object to remove. Example: >>> mycollection.remove(pump.Person('bob@example.org'))
4.133382
4.871734
0.848442
if self._outbox is None: self._outbox = Outbox(self.links['activity-outbox'], pypump=self._pump) return self._outbox
def outbox(self)
:class:`Outbox feed <pypump.models.feed.Outbox>` with all :class:`activities <pypump.models.activity.Activity>` sent by the person. Example: >>> for activity in pump.me.outbox[:2]: ... print(activity) ... pypumptest2 unliked a comment in reply to a no...
8.645177
6.296814
1.372945
if self._followers is None: self._followers = Followers(self.links['followers'], pypump=self._pump) return self._followers
def followers(self)
:class:`Feed <pypump.models.feed.Feed>` with all :class:`Person <pypump.models.person.Person>` objects following the person. Example: >>> alice = pump.Person('alice@example.org') >>> for follower in alice.followers[:2]: ... print(follower.id) ... ...
8.91851
8.644235
1.031729
if self._following is None: self._following = Following(self.links['following'], pypump=self._pump) return self._following
def following(self)
:class:`Feed <pypump.models.feed.Feed>` with all :class:`Person <pypump.models.person.Person>` objects followed by the person. Example: >>> bob = pump.Person('bob@example.org') >>> for followee in bob.following[:3]: ... print(followee.id) ... ...
15.19398
9.659867
1.572897
if self._favorites is None: self._favorites = Favorites(self.links['favorites'], pypump=self._pump) return self._favorites
def favorites(self)
:class:`Feed <pypump.models.feed.Feed>` with all objects liked/favorited by the person. Example: >>> for like in pump.me.favorites[:3]: ... print(like) ... note by alice@example.org image by bob@example.org comment by evan@e14n...
8.674396
7.981524
1.086809
if self._lists is None: self._lists = Lists(self.links['lists'], pypump=self._pump) return self._lists
def lists(self)
:class:`Lists feed <pypump.models.feed.Lists>` with all lists owned by the person. Example: >>> for list in pump.me.lists: ... print(list) ... Acquaintances Family Coworkers Friends
9.985243
8.102284
1.232398
if not self.isme: raise PyPumpException("You can't read other people's inboxes") if self._inbox is None: self._inbox = Inbox(self.links['activity-inbox'], pypump=self._pump) return self._inbox
def inbox(self)
:class:`Inbox feed <pypump.models.feed.Inbox>` with all :class:`activities <pypump.models.activity.Activity>` received by the person, can only be read if logged in as the owner. Example: >>> for activity in pump.me.inbox[:2]: ... print(activity.id) ... ...
9.666348
7.964137
1.213734
activity = { "verb": verb, "object": { "id": self.id, "objectType": self.object_type, } } self._post_activity(activity)
def _verb(self, verb)
Posts minimal activity with verb and bare self object. :param verb: verb to be used.
3.642334
3.368889
1.081168
# I think we always want to post to feed feed_url = "{proto}://{server}/api/user/{username}/feed".format( proto=self._pump.protocol, server=self._pump.client.server, username=self._pump.client.nickname ) data = self._pump.request(feed_url, me...
def _post_activity(self, activity, unserialize=True)
Posts a activity to feed
3.965558
3.84179
1.032216
if endpoints is None: endpoints = ["likes", "replies", "shares", "self", "followers", "following", "lists", "favorites", "members"] if links.get("links"): for endpoint in links['links']: # It would seem occasionally the links["li...
def _add_links(self, links, key="href", proxy_key="proxyURL", endpoints=None)
Parses and adds block of links
3.824825
3.859004
0.991143
mapping = mapping or obj._mapping if "data" in kwargs: for k, v in mapping.items(): if kwargs["data"].get(v, None) is not None: val = kwargs["data"][v] else: val = None self.add_attr(obj, k, val...
def parse_map(self, obj, mapping=None, *args, **kwargs)
Parses a dictionary of (model_attr, json_attr) items
2.639311
2.529934
1.043233
endpoint = self.links["likes"] if self._likes is None: self._likes = Feed(endpoint, pypump=self._pump) return self._likes
def likes(self)
A :class:`Feed <pypump.models.feed.Feed>` of the people who've liked the object. Example: >>> for person in mynote.likes: ... print(person.webfinger) ... pypumptest1@pumpity.net pypumptest2@pumpyourself.com
12.560334
6.895752
1.82146
endpoint = self.links["replies"] if self._comments is None: self._comments = Feed(endpoint, pypump=self._pump) return self._comments
def comments(self)
A :class:`Feed <pypump.models.feed.Feed>` of the comments for the object. Example: >>> for comment in mynote.comments: ... print(comment) ... comment by pypumptest2@pumpyourself.com
13.921675
8.867901
1.569895
if isinstance(comment, six.string_types): comment = self._pump.Comment(comment) comment.in_reply_to = self comment.send()
def comment(self, comment)
Add a :class:`Comment <pypump.models.comment.Comment>` to the object. :param comment: A :class:`Comment <pypump.models.comment.Comment>` instance, text content is also accepted. Example: >>> anote.comment(pump.Comment('I agree!'))
6.879441
7.244438
0.949617
endpoint = self.links["shares"] if self._shares is None: self._shares = Feed(endpoint, pypump=self._pump) return self._shares
def shares(self)
A :class:`Feed <pypump.models.feed.Feed>` of the people who've shared the object. Example: >>> for person in mynote.shares: ... print(person.webfinger) ... pypumptest1@pumpity.net pypumptest2@pumpyourself.com
13.56545
6.97033
1.94617
if hasattr(people, "object_type"): people = [people] elif hasattr(people, "__iter__"): people = list(people) return people
def _set_people(self, people)
Sets who the object is sent to
4.539488
4.874917
0.931193
mimetype = mimetypes.guess_type(filename)[0] or "application/octal-stream" headers = { "Content-Type": mimetype, "Content-Length": str(os.path.getsize(filename)), } # upload file file_data = self._pump.request( "/api/user/{0}/uploads...
def from_file(self, filename)
Uploads a file from a filename on your system. :param filename: Path to file on your system. Example: >>> myimage.from_file('/path/to/dinner.png')
3.019717
3.015954
1.001248
# copy activity attributes into object if "author" not in data["object"]: data["object"]["author"] = data["actor"] for key in ["to", "cc", "bto", "bcc"]: if key not in data["object"] and key in data: data["object"][key] = data[key] Mappe...
def unserialize(self, data)
From JSON -> Activity object
6.491857
5.782888
1.122598
if self._me is not None: return self._me self._me = self.Person("{username}@{server}".format( username=self.client.nickname, server=self.client.server, )) return self._me
def me(self)
Returns :class:`Person <pypump.models.person.Person>` instance of the logged in user. Example: >>> pump.me <Person: bob@example.org>
5.029531
4.284953
1.173766
if self.store_class is not None: return self.store_class.load(self.client.webfinger, self) raise NotImplementedError("You need to specify PyPump.store_class or override PyPump.create_store method.")
def create_store(self)
Creates store object
11.056337
10.392183
1.063909
server = None if "://" in endpoint: # looks like an url, let's break it down server, endpoint = self._deconstruct_url(endpoint) endpoint = endpoint.lstrip("/") url = "{proto}://{server}/{endpoint}".format( proto=self.protocol, ser...
def _build_url(self, endpoint)
Returns a fully qualified URL
3.984663
3.897409
1.022388
url = url.split("://", 1)[-1] server, endpoint = url.split("/", 1) return (server, endpoint)
def _deconstruct_url(self, url)
Breaks down URL and returns server and endpoint
3.890723
2.65752
1.464043
if "://" in url: server, endpoint = self._deconstruct_url(url) else: server = url if server not in self._server_cache: if not (key and secret): client = Client( webfinger=self.client.webfinger, ...
def _add_client(self, url, key=None, secret=None)
Creates Client object with key and secret for server and adds it to _server_cache if it doesnt already exist
2.73803
2.433539
1.125123
# get tokens from server and make a dict of them. self._server_tokens = self.request_token() self.store["oauth-request-token"] = self._server_tokens["token"] self.store["oauth-request-secret"] = self._server_tokens["token_secret"] # now we need the user to authorize me...
def oauth_request(self)
Makes a oauth connection
6.698251
6.532977
1.025298
response = self._requester(requests.head, "{0}://{1}/".format(self.protocol, self.client.server), allow_redirects=False ) if response.is_redirect: server = response.headers['loca...
def construct_oauth_url(self)
Constructs verifier OAuth URL
4.596212
4.499968
1.021388
if url and "://" in url: server, endpoint = self._deconstruct_url(url) else: server = self.client.server if server not in self._server_cache: self._add_client(server) if server == self.client.server: self.oauth = OAuth1( ...
def setup_oauth_client(self, url=None)
Sets up client for requests to pump
2.590319
2.647602
0.978364
client = OAuth1( client_key=self._server_cache[self.client.server].key, client_secret=self._server_cache[self.client.server].secret, callback_uri=self.callback, ) request = {"auth": client} response = self._requester( requests.pos...
def request_token(self)
Gets OAuth request token
3.640845
3.506259
1.038385
client = OAuth1( client_key=self._server_cache[self.client.server].key, client_secret=self._server_cache[self.client.server].secret, resource_owner_key=self.store["oauth-request-token"], resource_owner_secret=self.store["oauth-request-secret"], ...
def request_access(self, verifier)
Get OAuth access token so we can make requests
3.183128
3.130988
1.016653
if "oauth-access-token" not in self.store: return False response = self.request("/api/whoami", allow_redirects=False) # It should response with a redirect to our profile if it's logged in if response.status_code != 302: return False # the locat...
def logged_in(self)
Return boolean if is logged in
5.688001
5.432464
1.047039
handle = ctypes.c_void_p() status = _libcudnn.cudnnCreate(ctypes.byref(handle)) cudnnCheckStatus(status) return handle.value
def cudnnCreate()
Initialize cuDNN. Initializes cuDNN and returns a handle to the cuDNN context. Returns ------- handle : cudnnHandle cuDNN context
2.940314
3.861651
0.761414
status = _libcudnn.cudnnDestroy(ctypes.c_void_p(handle)) cudnnCheckStatus(status)
def cudnnDestroy(handle)
Release cuDNN resources. Release hardware resources used by cuDNN. Parameters ---------- handle : cudnnHandle cuDNN context.
4.07164
6.426199
0.6336
status = _libcudnn.cudnnSetStream(handle, id) cudnnCheckStatus(status)
def cudnnSetStream(handle, id)
Set current cuDNN library stream. Parameters ---------- handle : cudnnHandle cuDNN context. id : cudaStream Stream Id.
3.850753
6.312666
0.610004
id = ctypes.c_void_p() status = _libcudnn.cudnnGetStream(handle, ctypes.byref(id)) cudnnCheckStatus(status) return id.value
def cudnnGetStream(handle)
Get current cuDNN library stream. Parameters ---------- handle : int cuDNN context. Returns ------- id : int Stream ID.
2.685916
3.025859
0.887654
tensor = ctypes.c_void_p() status = _libcudnn.cudnnCreateTensorDescriptor(ctypes.byref(tensor)) cudnnCheckStatus(status) return tensor.value
def cudnnCreateTensorDescriptor()
Create a Tensor descriptor object. Allocates a cudnnTensorDescriptor_t structure and returns a pointer to it. Returns ------- tensor_descriptor : int Tensor descriptor.
2.861184
3.766624
0.759615
status = _libcudnn.cudnnSetTensor4dDescriptor(tensorDesc, format, dataType, n, c, h, w) cudnnCheckStatus(status)
def cudnnSetTensor4dDescriptor(tensorDesc, format, dataType, n, c, h, w)
Initialize a previously created Tensor 4D object. This function initializes a previously created Tensor4D descriptor object. The strides of the four dimensions are inferred from the format parameter and set in such a way that the data is contiguous in memory with no padding between dimensions. Paramet...
2.367252
4.063886
0.58251
status = _libcudnn.cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride) cudnnCheckStatus(status)
def cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride)
Initialize a Tensor descriptor object with strides. This function initializes a previously created generic Tensor descriptor object into a 4D tensor, similarly to cudnnSetTensor4dDescriptor but with the strides explicitly passed as parameters. This can be used to lay out the 4D tensor in any order or simpl...
2.109903
3.135347
0.672941
dataType = ctypes.c_int() n = ctypes.c_int() c = ctypes.c_int() h = ctypes.c_int() w = ctypes.c_int() nStride = ctypes.c_int() cStride = ctypes.c_int() hStride = ctypes.c_int() wStride = ctypes.c_int() status = _libcudnn.cudnnGetTensor4dDescriptor(tensorDesc, ctypes.byref(...
def cudnnGetTensor4dDescriptor(tensorDesc)
Get parameters of a Tensor descriptor object. This function queries the parameters of the previouly initialized Tensor4D descriptor object. Parameters ---------- tensorDesc : cudnnTensorDescriptor Handle to a previously initialized tensor descriptor. Returns ------- dataType :...
1.486429
1.30919
1.135381
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(srcDestDesc) if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']: alphaRef = ctypes.byref(ctypes.c_double(alpha)) betaRef = ctypes.byref(ctypes.c_double(beta)) else: alphaRef = ctypes.byref(ctypes.c_float(alpha)) ...
def cudnnAddTensor(handle, alpha, biasDesc, biasData, beta, srcDestDesc, srcDestData)
Tensor Bias addition : srcDest = alpha * bias + beta * srcDestDesc. This function adds the scaled values of one tensor to another tensor. The amount of data described by the biasDesc descriptor must match exactly the amount of data needed to perform the addition. Parameters ---------- handle :...
1.824146
1.920991
0.949586
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(srcDesc) if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']: alphaRef = ctypes.byref(ctypes.c_double(alpha)) else: alphaRef = ctypes.byref(ctypes.c_float(alpha)) status = _libcudnn.cudnnSetTensor(handle, srcDesc, srcData...
def cudnnSetTensor(handle, srcDesc, srcData, value)
Set all data points of a tensor to a given value : srcDest = alpha. Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. srcDesc : cudnnTensorDescriptor Handle to a previously initialized tensor descriptor. srcData : void_p Pointer to data...
2.395679
2.635947
0.908849
wDesc = ctypes.c_void_p() status = _libcudnn.cudnnCreateFilterDescriptor(ctypes.byref(wDesc)) cudnnCheckStatus(status) return wDesc.value
def cudnnCreateFilterDescriptor()
Create a filter descriptor. This function creates a filter descriptor object by allocating the memory needed to hold its opaque structure. Parameters ---------- Returns ------- wDesc : cudnnFilterDescriptor Handle to a newly allocated filter descriptor.
3.041454
3.324022
0.914992
status = _libcudnn.cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w) cudnnCheckStatus(status)
def cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w)
Initialize a filter descriptor. This function initializes a previously created filter descriptor object into a 4D filter. Filters layout must be contiguous in memory. Parameters ---------- wDesc : cudnnFilterDescriptor Handle to a previously created filter descriptor. dataType : cudnnD...
2.20799
3.568685
0.618713
dataType = ctypes.c_int() format = ctypes.c_int() k = ctypes.c_int() c = ctypes.c_int() h = ctypes.c_int() w = ctypes.c_int() status = _libcudnn.cudnnGetFilter4dDescriptor(wDesc, ctypes.byref(dataType), ctypes.byref(format), ...
def cudnnGetFilter4dDescriptor(wDesc)
Get parameters of filter descriptor. This function queries the parameters of the previouly initialized filter descriptor object. Parameters ---------- wDesc : cudnnFilterDescriptor Handle to a previously created filter descriptor. Returns ------- dataType : cudnnDataType D...
1.708128
1.499638
1.139027
convDesc = ctypes.c_void_p() status = _libcudnn.cudnnCreateConvolutionDescriptor(ctypes.byref(convDesc)) cudnnCheckStatus(status) return convDesc.value
def cudnnCreateConvolutionDescriptor()
Create a convolution descriptor. This function creates a convolution descriptor object by allocating the memory needed to hold its opaque structure. Returns ------- convDesc : cudnnConvolutionDescriptor Handle to newly allocated convolution descriptor.
2.698354
3.862934
0.698524
status = _libcudnn.cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode, computeType) cudnnCheckStatus(status)
def cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode, computeType)
Initialize a convolution descriptor. This function initializes a previously created convolution descriptor object into a 2D correlation. This function assumes that the tensor and filter descriptors corresponds to the formard convolution path and checks if their settings are valid. That same convolution...
1.913463
2.876742
0.665149
pad_h = ctypes.c_int() pad_w = ctypes.c_int() u = ctypes.c_int() v = ctypes.c_int() dilation_h = ctypes.c_int() dilation_w = ctypes.c_int() mode = ctypes.c_int() computeType = ctypes.c_int() status = _libcudnn.cudnnGetConvolution2dDescriptor(convDesc, ctypes.byref(pad_h), ...
def cudnnGetConvolution2dDescriptor(convDesc)
Get a convolution descriptor. This function queries a previously initialized 2D convolution descriptor object. Parameters ---------- convDesc : cudnnConvolutionDescriptor Handle to a previously created convolution descriptor. Returns ------- pad_h : int zero-padding height...
1.693028
1.532746
1.104572
n = ctypes.c_int() c = ctypes.c_int() h = ctypes.c_int() w = ctypes.c_int() status = _libcudnn.cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, wDesc, ctypes.byref(n), ctypes.byref...
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, wDesc)
Return the dimensions of the output tensor given a convolution descriptor. This function returns the dimensions of the resulting 4D tensor of a 2D convolution, given the convolution descriptor, the input tensor descriptor and the filter descriptor. This function can help to setup the output tensor and allo...
1.776243
1.768801
1.004208
algo = ctypes.c_int() status = _libcudnn.cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc, convDesc, destDesc, preference, ctypes.c_size_t(memoryLimitInbytes), ...
def cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc, convDesc, destDesc, preference, memoryLimitInbytes)
This function returns the best algorithm to choose for the forward convolution depending on the critera expressed in the cudnnConvolutionFwdPreference_t enumerant. Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. srcDesc : cudnnTensorDescriptor ...
1.971278
2.672586
0.737592
sizeInBytes = ctypes.c_size_t() status = _libcudnn.cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc, convDesc, destDesc, algo, ctypes.byref(sizeInBytes)) cudnnCheckStatus(status) return siz...
def cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc, convDesc, destDesc, algo)
This function returns the amount of GPU memory workspace the user needs to allocate to be able to call cudnnConvolutionForward with the specified algorithm. Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. srcDesc : cudnnTensorDescriptor Handl...
2.10807
2.944952
0.715825
dataType = cudnnGetTensor4dDescriptor(destDesc)[0] if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']: alphaRef = ctypes.byref(ctypes.c_double(alpha)) betaRef = ctypes.byref(ctypes.c_double(beta)) else: alphaRef = ctypes.byref(ctypes.c_float(alpha)) betaRef = ctypes.byre...
def cudnnConvolutionForward(handle, alpha, srcDesc, srcData, wDesc, w, convDesc, algo, workspace, workSpaceSizeInBytes, beta, destDesc, destData)
Perform forward convolution. All of the form "output = alpha * Op(inputs) + beta * output". This function executes convolutions or cross-correlations over src using the specified filters, returning results in dest. Scaling factors alpha and beta can be used to scale the input tensor and the output tensor r...
1.631291
1.884989
0.865412
dataType = cudnnGetTensor4dDescriptor(destDesc)[0] if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']: alphaRef = ctypes.byref(ctypes.c_double(alpha)) betaRef = ctypes.byref(ctypes.c_double(beta)) else: alphaRef = ctypes.byref(ctypes.c_float(alpha)) betaRef = ctypes.byre...
def cudnnSoftmaxForward(handle, algorithm, mode, alpha, srcDesc, srcData, beta, destDesc, destData)
This routing computes the softmax function Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. algorithm : cudnnSoftmaxAlgorithm Enumerant to specify the softmax algorithm. mode : cudnnSoftmaxMode Enumerant to specify the softmax mode. ...
1.72222
1.970018
0.874216
poolingDesc = ctypes.c_void_p() status = _libcudnn.cudnnCreatePoolingDescriptor(ctypes.byref(poolingDesc)) cudnnCheckStatus(status) return poolingDesc.value
def cudnnCreatePoolingDescriptor()
Create pooling descriptor. This function creates a pooling descriptor object by allocating the memory needed to hold its opaque structure, Returns ------- poolingDesc : cudnnPoolingDescriptor Newly allocated pooling descriptor.
2.792563
3.921876
0.712048
status = _libcudnn.cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth, verticalPadding, horizontalPadding, verticalStride, horizontalStride) cudnnCheckStatus(status)
def cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth, verticalPadding, horizontalPadding, verticalStride, horizontalStride)
Initialize a 2D pooling descriptor. This function initializes a previously created pooling descriptor object. Parameters ---------- poolingDesc : cudnnPoolingDescriptor Handle to a previously created pooling descriptor. mode : cudnnPoolingMode Enumerant to specify the pooling mode....
2.016771
3.283459
0.614222
mode = ctypes.c_int() windowHeight = ctypes.c_int() windowWidth = ctypes.c_int() verticalPadding = ctypes.c_int() horizontalPadding = ctypes.c_int() verticalStride = ctypes.c_int() horizontalStride = ctypes.c_int() status = _libcudnn.cudnnGetPooling2dDescriptor(poolingDesc, ctypes...
def cudnnGetPooling2dDescriptor(poolingDesc)
This function queries a previously created pooling descriptor object. Parameters ---------- poolingDesc : cudnnPoolingDescriptor Handle to a previously created 2D pooling descriptor. Returns ------- mode : cudnnPoolingMode Enumerant to specify the pooling mode. windowHeight : i...
1.585663
1.407696
1.126424
dataType = cudnnGetTensor4dDescriptor(destDesc)[0] if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']: alphaRef = ctypes.byref(ctypes.c_double(alpha)) betaRef = ctypes.byref(ctypes.c_double(beta)) else: alphaRef = ctypes.byref(ctypes.c_float(alpha)) betaRef = ctypes.byre...
def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc, srcDiffData, destDesc, destData, beta, destDiffDesc, destDiffData)
Gradient of activation function. This routine computes the gradient of a neuron activation function. In-place operation is allowed for this routine; i.e., srcData and destData pointers may be equal and srcDiffData and destDiffData pointers may be equal. However, this requires the corresponding tensor ...
1.632128
1.839959
0.887046
# If there isn't a prefix don't bother if self.prefix is None: return key # Don't prefix key if it already has it if key.startswith(self.prefix + "-"): return key return "{0}-{1}".format(self.prefix, key)
def __prefix_key(self, key)
This will add the prefix to the key if one exists on the store
4.03037
3.599622
1.119665
data = {} for key, value in self.items(): data[key] = value return data
def export(self)
Exports as dictionary
4.812135
3.650307
1.318282
if self.filename is None: raise StoreException("Filename must be set to write store to disk") # We need an atomic way of re-writing the settings, we also need to # prevent only overwriting part of the settings file (see bug #116). # Create a temp file and only then ...
def save(self)
Saves dictionary to disk in JSON format.
4.173422
4.082867
1.022179
config_home = os.environ.get("XDG_CONFIG_HOME", "~/.config") config_home = os.path.expanduser(config_home) base_path = os.path.join(config_home, "PyPump") if not os.path.isdir(base_path): os.makedirs(base_path) return os.path.join(base_path, "credentials.js...
def get_filename(cls)
Gets filename of store on disk
2.651104
2.586082
1.025143
filename = cls.get_filename() if os.path.isfile(filename): data = open(filename).read() data = json.loads(data) store = cls(data, filename=filename) else: store = cls(filename=filename) store.prefix = webfinger return sto...
def load(cls, webfinger, pypump)
Load JSON from disk into store object
3.583134
3.030237
1.18246
if message is not None: print(message, end='') sys.stdout.flush() getch() print()
def pause(message='Press any key to continue . . . ')
Prints the specified message if it's not None and waits for a keypress.
3.668833
3.521877
1.041727
bonds=[] for a, b in atoms: bond_distance=( element_data[a.element.title()]['atomic radius'] + element_data[ b.element.title()]['atomic radius']) / 100 dist=distance(a._vector, b._vector) if dist <= bond_distance * threshold: bonds.append(...
def covalent_bonds(atoms, threshold=1.1)
Returns all the covalent bonds in a list of `Atom` pairs. Notes ----- Uses information `element_data`, which can be accessed directly through this module i.e. `isambard.ampal.interactions.element_data`. Parameters ---------- atoms : [(`Atom`, `Atom`)] List of pairs of `Atoms`. ...
4.453268
4.933696
0.902623
sectors=gen_sectors(ampal.get_atoms(), max_range * 1.1) bonds=[] for sector in sectors.values(): atoms=itertools.combinations(sector, 2) bonds.extend(covalent_bonds(atoms, threshold=threshold)) bond_set=list(set(bonds)) if tag: for bond in bond_set: a, b=bond...
def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True)
Finds all covalent bonds in the AMPAL object. Parameters ---------- ampal : AMPAL Object Any AMPAL object with a `get_atoms` method. max_range : float, optional Used to define the sector size, so interactions at longer ranges will not be found. threshold : float, optional ...
2.130155
2.1633
0.984678
bond_graph=networkx.Graph() for inter in covalent_bonds: bond_graph.add_edge(inter.a, inter.b) return bond_graph
def generate_covalent_bond_graph(covalent_bonds)
Generates a graph of the covalent bond network described by the interactions. Parameters ---------- covalent_bonds: [CovalentBond] List of `CovalentBond`. Returns ------- bond_graph: networkx.Graph A graph of the covalent bond network.
3.297668
3.059821
1.077732
bond_graph.remove_edge(atom1, atom2) try: subgraphs=list(networkx.connected_component_subgraphs( bond_graph, copy=False)) finally: # Add edge bond_graph.add_edge(atom1, atom2) return subgraphs
def generate_bond_subgraphs_from_break(bond_graph, atom1, atom2)
Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not work if there are cycles in the bond graph. Parameters ---------- bond_graph: networkx.Graph Graph of covalent bond network atom1: isambard.ampal.Atom First atom in the bond. atom2...
3.046488
3.41126
0.893068
s = str(v) return s if len(s) <= l else s[-l:]
def cap(v, l)
Shortens string is above certain length.
4.204917
3.411529
1.232561
return [x for x in atoms if distance(x, point) <= cutoff_distance]
def find_atoms_within_distance(atoms, cutoff_distance, point)
Returns atoms within the distance from the point. Parameters ---------- atoms : [ampal.atom] A list of `ampal.atoms`. cutoff_distance : float Maximum distance from point. point : (float, float, float) Reference point, 3D coordinate. Returns ------- filtered_atom...
3.365861
7.311403
0.460358
points = [x._vector for x in atoms] if mass_weighted: masses = [x.mass for x in atoms] else: masses = [] return centre_of_mass(points=points, masses=masses)
def centre_of_atoms(atoms, mass_weighted=True)
Returns centre point of any list of atoms. Parameters ---------- atoms : list List of AMPAL atom objects. mass_weighted : bool, optional If True returns centre of mass, otherwise just geometric centre of points. Returns ------- centre_of_mass : numpy.array 3D coordi...
3.011061
3.938176
0.764583
if hasattr(self, 'ligands'): atoms = self.get_atoms(ligands=True, inc_alt_states=True) else: atoms = self.get_atoms(inc_alt_states=True) for atom in atoms: w_str = None a_ff_id = None if atom.element == 'H': con...
def assign_force_field(self, ff, mol2=False)
Assigns force field parameters to Atoms in the AMPAL object. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style labels will also be used.
2.973528
2.972616
1.000307
aff = False if force_ff_assign: aff = True elif 'assigned_ff' not in self.tags: aff = True elif not self.tags['assigned_ff']: aff = True if aff: self.assign_force_field(ff, mol2=mol2) return
def update_ff(self, ff, mol2=False, force_ff_assign=False)
Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style ...
3.45348
4.374835
0.789397
if not ff: ff = global_settings['buff']['force_field'] if assign_ff: self.update_ff(ff, mol2=mol2, force_ff_assign=force_ff_assign) interactions = find_intra_ampal(self, ff.distance_cutoff) buff_score = score_interactions(interactions, ff) return ...
def get_internal_energy(self, assign_ff=True, ff=None, mol2=False, force_ff_assign=False)
Calculates the internal energy of the AMPAL object. This method is assigned to the buff_internal_energy property, using the default arguments. Parameters ---------- assign_ff: bool, optional If true the force field will be updated if required. ff: BuffForceF...
5.642954
4.390525
1.285257
q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians) for atom in self.get_atoms(inc_alt_states=inc_alt_states): atom._vector = q.rotate_vector(v=atom._vector, point=point) return
def rotate(self, angle, axis, point=None, radians=False, inc_alt_states=True)
Rotates every atom in the AMPAL object. Parameters ---------- angle : float Angle that AMPAL object will be rotated. axis : 3D Vector (tuple, list, numpy.array) Axis about which the AMPAL object will be rotated. point : 3D Vector (tuple, list, numpy.array...
3.537927
4.449509
0.795127
vector = numpy.array(vector) for atom in self.get_atoms(inc_alt_states=inc_alt_states): atom._vector += vector return
def translate(self, vector, inc_alt_states=True)
Translates every atom in the AMPAL object. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternate conformations ...
4.200772
5.864163
0.716346
assert type(self) == type(other) if backbone and hasattr(self, 'backbone'): points1 = self.backbone.get_atoms() points2 = other.backbone.get_atoms() else: points1 = self.get_atoms() points2 = other.get_atoms() points1 = [x._vector ...
def rmsd(self, other, backbone=False)
Calculates the RMSD between two AMPAL objects. Notes ----- No fitting operation is performs and both AMPAL objects must have the same number of atoms. Parameters ---------- other : AMPAL Object Any AMPAL object with `get_atoms` method. backbo...
2.209358
2.401076
0.920153
if isinstance(item, Monomer): self._monomers.append(item) else: raise TypeError( 'Only Monomer objects can be appended to an Polymer.') return
def append(self, item)
Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling.
3.989413
3.347637
1.19171
if isinstance(polymer, Polymer): self._monomers.extend(polymer) else: raise TypeError( 'Only Polymer objects may be merged with a Polymer using unary operator "+".') return
def extend(self, polymer)
Extends the `Polymer` with the contents of another `Polymer`. Notes ----- Does not update labelling.
7.603903
7.778357
0.977572
if ligands and self.ligands: monomers = self._monomers + self.ligands._monomers else: monomers = self._monomers return iter(monomers)
def get_monomers(self, ligands=True)
Retrieves all the `Monomers` from the AMPAL object. Parameters ---------- ligands : bool, optional If true, will include ligand `Monomers`.
2.846089
3.389252
0.83974
if ligands and self.ligands: monomers = self._monomers + self.ligands._monomers else: monomers = self._monomers atoms = itertools.chain( *(list(m.get_atoms(inc_alt_states=inc_alt_states)) for m in monomers)) return atoms
def get_atoms(self, ligands=True, inc_alt_states=False)
Flat list of all the Atoms in the Polymer. Parameters ---------- inc_alt_states : bool If true atoms from alternate conformations are included rather than only the "active" states. Returns ------- atoms : itertools.chain Returns an it...
2.678757
2.955501
0.906363
if labels: if len(self._monomers) == len(labels): for monomer, label in zip(self._monomers, labels): monomer.id = str(label) else: error_string = ( 'Number of Monomers ({}) and number of labels ' ...
def relabel_monomers(self, labels=None)
Relabels the either in numerically or using a list of labels. Parameters ---------- labels : list, optional A list of new labels. Raises ------ ValueError Raised if the number of labels does not match the number of component Monoer ob...
2.136132
2.290721
0.932515
counter = start for atom in self.get_atoms(): atom.id = counter counter += 1 return
def relabel_atoms(self, start=1)
Relabels all `Atoms` in numerical order. Parameters ---------- start : int, optional Offset the labelling by `start` residues.
3.824436
10.059972
0.380164
if any([False if x.id else True for x in self._monomers]): self.relabel_monomers() if self.ligands and inc_ligands: monomers = self._monomers + self.ligands._monomers else: monomers = self._monomers pdb_str = write_pdb(monomers, self.id, alt_s...
def make_pdb(self, alt_states=False, inc_ligands=True)
Generates a PDB string for the `Polymer`. Parameters ---------- alt_states : bool, optional Include alternate conformations for `Monomers` in PDB. inc_ligands : bool, optional Includes `Ligands` in PDB. Returns ------- pdb_str : str ...
3.111059
3.17917
0.978576
pdb_str = write_pdb( [self], ' ' if not self.ampal_parent else self.ampal_parent.id) return pdb_str
def make_pdb(self)
Generates a PDB string for the `Monomer`.
9.869787
7.296373
1.352698
chain = self.ampal_parent.ampal_parent.id residue = self.ampal_parent.id return chain, residue, self.id
def unique_id(self)
Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id)
9.165264
6.268597
1.462092
q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians) self._vector = q.rotate_vector(v=self._vector, point=point) return
def rotate(self, angle, axis, point=None, radians=False)
Rotates `Atom` by `angle`. Parameters ---------- angle : float Angle that `Atom` will be rotated. axis : 3D Vector (tuple, list, numpy.array) Axis about which the `Atom` will be rotated. point : 3D Vector (tuple, list, numpy.array), optional P...
3.996499
5.852245
0.6829
vector = numpy.array(vector) for atom in self.get_atoms(inc_alt_states=inc_alt_states): atom._vector += vector return self._vector += numpy.array(vector) return
def translate(self, vector)
Translates `Atom`. Parameters ---------- vector : 3D Vector (tuple, list, numpy.array) Vector used for translation. inc_alt_states : bool, optional If true, will rotate atoms in all states i.e. includes alternate conformations for sidechains.
7.858894
5.29565
1.484028
pisces_dict = {} if path: pisces_path = Path(pisces_output) pisces_content = pisces_path.read_text().splitlines()[1:] else: pisces_content = pisces_output.splitlines()[1:] for line in pisces_content: pdb = line.split()[0][:4].lower() chain = line.split()[0][-...
def parse_PISCES_output(pisces_output, path=False)
Takes the output list of a PISCES cull and returns in a usable dictionary. Notes ----- Designed for outputs of protein sequence redundancy culls conducted using the PISCES server. http://dunbrack.fccc.edu/PISCES.php G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinfor...
1.904769
2.007121
0.949006
if verbose: print("Downloading data from " + URL) req = Request(URL) try: with urlopen(req) as u: decoded_file = u.read().decode(encoding) except URLError as e: if hasattr(e, 'reason'): print('Server could not be reached.') print('Reason: ...
def download_decode(URL, encoding='utf-8', verbose=True)
Downloads data from URL and returns decoded contents.
1.885787
1.843761
1.022794
pdb_code = pdb_id[:4].lower() olderado_url = 'http://www.ebi.ac.uk/pdbe/nmr/olderado/searchEntry?pdbCode=' + pdb_code olderado_page = download_decode(olderado_url, verbose=False) if olderado_page: parsed_page = BeautifulSoup(olderado_page, 'html.parser') else: return None tr...
def olderado_best_model(pdb_id)
Checks the Olderado web server and returns the most representative conformation for PDB NMR structures. Notes ----- Uses OLDERADO from the EBI. See http://www.ebi.ac.uk/pdbe/nmr/olderado/ and citations therein. Parameters ---------- pdb_id : str The 4-character PDB code for the NMR...
3.865082
3.42936
1.127057
specification, sequence, parsed_ind = params model = specification(*parsed_ind) model.build() model.pack_new_sequences(sequence) return model.buff_interaction_energy.total_energy
def buff_eval(params)
Builds and evaluates BUFF energy of model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence, and the parameters for model building. Returns ------- model.bude_score: float BUFF score for model to be assign...
22.181137
15.999803
1.386338
specification, sequence, parsed_ind = params model = specification(*parsed_ind) model.build() model.pack_new_sequences(sequence) return model.buff_internal_energy.total_energy
def buff_internal_eval(params)
Builds and evaluates BUFF internal energy of a model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence and the parameters for model building. Returns ------- model.bude_score: float BUFF internal energy sc...
21.100164
12.576259
1.677778
specification, sequence, parsed_ind, reference_pdb = rmsd_params model = specification(*parsed_ind) model.pack_new_sequences(sequence) ca, bb, aa = run_profit(model.pdb, reference_pdb, path1=False, path2=False) return bb
def rmsd_eval(rmsd_params)
Builds a model and runs profit against a reference model. Parameters ---------- rmsd_params Returns ------- rmsd: float rmsd against reference model as calculated by profit.
16.469872
16.096052
1.023224
top1, top2, params1, params2, seq1, seq2, movements = comparator_params xrot, yrot, zrot, xtrans, ytrans, ztrans = movements obj1 = top1(*params1) obj2 = top2(*params2) obj2.rotate(xrot, [1, 0, 0]) obj2.rotate(yrot, [0, 1, 0]) obj2.rotate(zrot, [0, 0, 1]) obj2.translate([xtrans, ytr...
def comparator_eval(comparator_params)
Gets BUFF score for interaction between two AMPAL objects
3.996987
3.465527
1.153356
scaled_ind = [] for i in range(len(self._params['value_means'])): scaled_ind.append(self._params['value_means'][i] + ( individual[i] * self._params['value_ranges'][i])) fullpars = list(self._params['arrangement']) for k in range(len(self._params['vari...
def parse_individual(self, individual)
Converts a deap individual into a full list of parameters. Parameters ---------- individual: deap individual from optimization Details vary according to type of optimization, but parameters within deap individual are always between -1 and 1. This function conv...
3.182582
3.143891
1.012307
self._params['popsize'] = popsize self._params['numgen'] = numgen self._params['processors'] = processors self._params['plot'] = plot self._params['log'] = log # allows us to pass in additional arguments e.g. neighbours self._params.update(**kwargs) ...
def run_opt(self, popsize, numgen, processors, plot=False, log=False, **kwargs)
Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return:
2.112112
2.123709
0.994539
self._params['sequence'] = sequence self._params['value_means'] = value_means self._params['value_ranges'] = value_ranges self._params['arrangement'] = arrangement if any(x <= 0 for x in self._params['value_ranges']): raise ValueError("range values must be gr...
def parameters(self, sequence, value_means, value_ranges, arrangement)
Relates the individual to be evolved to the full parameter string. Parameters ---------- sequence: str Full amino acid sequence for specification object to be optimized. Must be equal to the number of residues in the model. value_means: list ...
2.321162
2.191749
1.059046
best_ind = self.halloffame[0] model_params = self.parse_individual( best_ind) # need to change name of 'params' with open( '{0}{1}_log.txt'.format( self._params['output_path'], self._params['run_id']), 'a+') as log_fil...
def log_results(self)
Saves files for the minimization. Notes ----- Currently saves a logfile with best individual and a pdb of the best model.
2.781791
2.7143
1.024865