# Get the atlas id
def query_atlases(search_pattern):
    return rma.build_query_url(rma.model_stage('Atlas',
                                               criteria="[name$il'%s']" % (search_pattern),
                                               only=['id', 'name']))

atlases = o.do_query(query_atlases, read_data, 'mouse*')
pretty(atlases)


# get the structure
def query_structure(acronym, ontology_id):
    return rma.build_query_url(rma.model_stage('Structure',
                                               criteria="[acronym$eq'%s'][ontology_id$eq%d]" % (acronym, ontology_id),
                                               only=['id','name']))

structure = o.do_query(query_structure, read_data, 'VISp', 1)[0]
pretty(structure)


def query_hemisphere(name):
    return rma.build_query_url(rma.model_stage('Hemisphere', criteria="[name$il'%s']" % (name)))
                               
left_hemisphere_id = o.do_query(query_hemisphere, read_data, 'left')[0]['id']

left_hemisphere_id

mca = MouseConnectivityApi()
experiments = mca.get_experiments(structure['id'])

# TODO: figure out why this didn't work w/ left hemisphere
other_hemisphere_id = 3

# get experiments doesn't take hemisphere into account, so filter the results with a list comprehension
left_hemisphere_experiments = [e for e in experiments
                               if any([(injection['primary_injection_structure']['hemisphere_id'] == other_hemisphere_id)
                               for injection in e['specimen']['stereotaxic_injections']])]
                                                          
pretty(left_hemisphere_experiments)

"""
Explanation: Download lists of experiments by injection hemisphere, mouse cre line, and injection structure
Download Pvalb experiments injected in the left hemisphere VISp
End of explanation
"""


from allensdk.api.queries.grid_data.grid_data_api import GridDataApi

"""
Explanation: Download grid data for these experiments at a particular resolution
End of explanation
"""


gda = GridDataApi()

# TODO: show search to get this
section_data_set_id = 183282970

image_list = ['projection_density',
              'projection_energy',
              'injection_fraction',
              'injection_density',
              'injection_energy']

resolution = 100 # or 10, 25, 50

# Hmm, this didn't work for an image list of length > 1
for image in image_list:
    q = gda.build_projection_grid_download_query(section_data_set_id,
                                                 image=[image],
                                                 resolution=resolution)
    print(q)

# gda.download_projection_grid_data(section_data_set_id,
#                                   image=image,
#                                   resolution=resolution)


# TODO: data mask

"""
Explanation: 10, 25, 50, or 100 micron volumes for:
* Projection density

* projection energy

* injection fraction

* Injection density

* Injection energy

* Data mask (mask of valid voxels per experiment)
End of explanation
"""


q = gda.build_expression_grid_download_query(section_data_set_id, include=image_list)
print q

"""
Explanation: http://help.brain-map.org//display/mouseconnectivity/API#API-Expression3DGrids
End of explanation
"""


#http://api.brain-map.org/api/v2/data/query.csv?criteria=
#model::ProjectionStructureUnionize,
#rma::criteria,[is_injection$eq'f'],hemisphere,structure,section_data_set[id$eq183282970](specimen(stereotaxic_injections(primary_injection_structure,stereotaxic_injection_coordinates))),rma::include,section_data_set(specimen(stereotaxic_injections(primary_injection_structure))),
#rma::options[tabular$eq'distinct+specimens.name+as+specimen_name,stereotaxic_injection_coordinates.coordinates_ap,stereotaxic_injection_coordinates.coordinates_dv,stereotaxic_injection_coordinates.coordinates_ml,data_sets.id+as+data_set_id,stereotaxic_injections.primary_injection_structure_id,structures.acronym+as+target_structure,hemispheres.symbol+as+hemisphere,projection_structure_unionizes.is_injection,projection_structure_unionizes.sum_pixels,projection_structure_unionizes.sum_projection_pixels,projection_structure_unionizes.sum_pixel_intensity,projection_structure_unionizes.sum_projection_pixel_intensity,projection_structure_unionizes.projection_density,projection_structure_unionizes.projection_intensity,projection_structure_unionizes.projection_energy,projection_structure_unionizes.volume,projection_structure_unionizes.projection_volume,projection_structure_unionizes.normalized_projection_volume,projection_structure_unionizes.max_voxel_density,projection_structure_unionizes.max_voxel_x,projection_structure_unionizes.max_voxel_y,projection_structure_unionizes.max_voxel_z'][start_row$eq0][num_rows$eq3000]

def build_query(section_data_set_id):
    criteria_string = ''.join(["[is_injection$eq'f'],",
                               "hemisphere,",
                               "structure,",
                               "section_data_set[id$eq%d]" % (section_data_set_id),
                               "(specimen",
                               "(stereotaxic_injections",
                               "(primary_injection_structure,stereotaxic_injection_coordinates)",
                               "))"])
    include_string = ''.join(["section_data_set",
                              "(specimen",
                              "(stereotaxic_injections",
                              "(primary_injection_structure)",
                              "))"])
    tabular_list = ['distinct+specimens.name+as+specimen_name',
                    'stereotaxic_injection_coordinates.coordinates_ap',
                    'stereotaxic_injection_coordinates.coordinates_dv',
                    'stereotaxic_injection_coordinates.coordinates_ml',
                    'data_sets.id+as+data_set_id',
                    'stereotaxic_injections.primary_injection_structure_id',
                    'structures.acronym+as+target_structure',
                    'hemispheres.symbol+as+hemisphere',
                    'projection_structure_unionizes.is_injection',
                    'projection_structure_unionizes.sum_pixels',
                    'projection_structure_unionizes.sum_projection_pixels',
                    'projection_structure_unionizes.sum_pixel_intensity',
                    'projection_structure_unionizes.sum_projection_pixel_intensity',
                    'projection_structure_unionizes.projection_density',
                    'projection_structure_unionizes.projection_intensity',
                    'projection_structure_unionizes.projection_energy',
                    'projection_structure_unionizes.volume',
                    'projection_structure_unionizes.projection_volume',
                    'projection_structure_unionizes.normalized_projection_volume',
                    'projection_structure_unionizes.max_voxel_density',
                    'projection_structure_unionizes.max_voxel_x',
                    'projection_structure_unionizes.max_voxel_y',
                    'projection_structure_unionizes.max_voxel_z']
    model_stage = rma.model_stage('ProjectionStructureUnionize',
                                  criteria=criteria_string,
                                  include=include_string,
                                  tabular=["'%s'" % ','.join(tabular_list)],  # TODO: better handling of tabular quotes
                                  num_rows='all')
    url = rma.build_query_url(model_stage, fmt='csv')
    
    return url

print(build_query(183282970))
    


"""
Explanation: Read data (File mode):
Read experiment metadata by injection hemisphere, mouse cre line, and injection structure
    “I download a list of all experiments.  Which were injected in VISp?”
End of explanation
"""


resolution=25
q = mca.build_volumetric_data_download_url('annotation/ccf_2015', 'annotation_%d.nrrd' % (resolution))

# mca.download_volumetric_data_download('annotation/ccf_2015', 'annotation_%d.nrrd' % (resolution))

print(q)


"""
Explanation: Read experiment grid data for these experiments by type
    3D numpy arrays worked pretty well for Friday harbor last year

Process data:
Mask grid data using the data mask or injection fraction volumes

    “Give me the projection energy voxels from this experiment that are valid for analysis”

    “Give me the injection density voxels inside the injection site”

Mask grid data arrays by structure

    “Give me the projection density voxel data for voxels belonging to VISp”

    This will involve the annotation volume at the correct resolution
        http://download.alleninstitute.org/informatics-archive/current-release/mouse_ccf/annotation/ccf_2015/
End of explanation
"""


