Exemplo n.º 1
0
def query_mouselight(query):
    """
		[Sends a GET request, not currently used for anything.]
	"""
    if not connected_to_internet():
        raise ConnectionError(
            "You need an internet connection for API queries, sorry.")

    base_url = "http://ml-neuronbrowser.janelia.org/"

    full_query = base_url + query

    # send the query, package the return argument as a json tree
    response = requests.get(full_query)
    if response.ok:
        json_tree = response.json()
        if json_tree['success']:
            return json_tree
        else:
            exception_string = 'did not complete api query successfully'
    else:
        exception_string = 'API failure. Allen says: {}'.format(
            response.reason)

    # raise an exception if the API request failed
    raise ValueError(exception_string)
Exemplo n.º 2
0
def request(url):
    if not connected_to_internet():
        raise ConnectionError(
            "You need to have an internet connection to send requests.")
    response = requests.get(url)
    if response.ok:
        return response
    else:
        exception_string = 'URL request failed: {}'.format(response.reason)
    raise ValueError(exception_string)
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        if not connected_to_internet():
            raise ConnectionError("You will need to be connected to the internet to use the AllenMorphology class")

        Paths.__init__(self, *args, **kwargs)

        # Create a Cache for the Cell Types Cache API
        self.ctc = CellTypesCache(manifest_file=os.path.join(self.morphology_allen, 'manifest.json'))

        # Get a list of cell metadata for neurons with reconstructions, download if necessary
        self.neurons = pd.DataFrame(self.ctc.get_cells(species=[CellTypesApi.MOUSE], require_reconstruction = True))
        self.n_neurons = len(self.neurons)
        if not self.n_neurons: raise ValueError("Something went wrong and couldn't get neurons metadata from Allen")

        self.downloaded_neurons = self.get_downloaded_neurons()
Exemplo n.º 4
0
def post_mouselight(url, query=None, clean=False, attempts=3):
    """
		[sends a POST request to a user URL. Query can be either a string (in which case clean should be False) or a dictionary.]
	"""
    if not connected_to_internet():
        raise ConnectionError(
            "You need an internet connection for API queries, sorry.")

    request = None
    if query is not None:
        for i in range(attempts):
            try:
                if not clean:
                    time.sleep(0.01)  # avoid getting an error from server
                    request = requests.post(url, json={'query': query})
                else:
                    time.sleep(0.01)  # avoid getting an error from server
                    request = requests.post(url, json=query)
            except Exception as e:
                exception = e
                request = None
                print('MouseLight API query failed. Attempt {} of {}'.format(
                    i + 1, attempts))
            if request is not None: break

        if request is None:
            raise ConnectionError(
                "\n\nMouseLight API query failed with error message:\n{}.\
						\nPerhaps the server is down, visit 'http://ml-neuronbrowser.janelia.org' to find out."
                .format(exception))
    else:
        raise NotImplementedError

    if request.status_code == 200:
        jreq = request.json()
        if 'data' in list(jreq.keys()):
            return jreq['data']
        else:
            return jreq
    else:
        raise Exception(
            "Query failed to run by returning code of {}. {} -- \n\n{}".format(
                request.status_code, query, request.text))
Exemplo n.º 5
0
    def __init__(self):
        SvgApi.__init__(
            self
        )  # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/svg_api.py
        ImageDownloadApi.__init__(
            self
        )  # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/image_download_api.py
        self.annsetsapi = AnnotatedSectionDataSetsApi(
        )  # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/annotated_section_data_sets_api.py
        self.oapi = OntologiesApi(
        )  # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/ontologies_api.py

        # Get metadata about atlases
        self.atlases = pd.DataFrame(self.oapi.get_atlases_table())
        self.atlases_names = sorted(list(self.atlases['name'].values))

        self.mouse_coronal_atlas_id = int(self.atlases.loc[
            self.atlases['name'] == "Mouse, P56, Coronal"].id.values[0])
        self.mouse_sagittal_atlas_id = int(self.atlases.loc[
            self.atlases['name'] == "Mouse, P56, Sagittal"].id.values[0])
        self.mouse_3D_atlas_id = int(self.atlases.loc[
            self.atlases['name'] == "Mouse, Adult, 3D Coronal"].id.values[0])

        # Get metadata about products
        if connected_to_internet():
            self.products = pd.DataFrame(
                send_query(
                    "http://api.brain-map.org/api/v2/data/query.json?criteria=model::Product"
                ))
            self.mouse_brain_reference_product_id = 12
            self.mouse_brain_ish_data_product_id = 1
            self.products_names = sorted(list(self.products["name"].values))
            self.mouse_products_names = sorted(
                list(self.products.loc[self.products.species == "Mouse"]
                     ["name"].values))
        else:
            raise ConnectionError(
                "It seems that you are not connected to the internet, you won't be able to download stuff."
            )