results = db.outputs(experiment='historical',mip='day')

"""
Explanation: Pass to the session "outputs" method some arguments to search for data
End of explanation
"""


results.count()

"""
Explanation: The "outputs" method returns the corresponding rows from the Instance table as result.
We use the count() method to check how many Instances we got back
End of explanation
"""


results = db.outputs(experiment='rcp45',model='CNRM-CM5',mip='Amon',variable='tas', ensemble='r1i1p1')
results.count()

"""
Explanation: NB the search is very fast no matter how many rows we get back or how many fields we use as arguments. This is because we are not actually accessing the instance objects yet.
End of explanation
"""


for o in results:
    print("Available versions for ensemble " + str(o.ensemble))
    print("")
    for v in o.versions: 
        print(str(v.version) + " from " + str(v.path))
        print("")
    print("drstree path is " + str(o.drstree_path()))

"""
Explanation: We loop through the result object to find out the available versions and other Instance fields
End of explanation
"""


results = db.outputs(experiment='rcp45',mip='Amon',variable='clt')
results.count()

"""
Explanation: Another search this time without specifying the model
End of explanation
"""


models=set()

for o in results:
    models.add(str(o.model))

print(sorted(models))

from ARCCSSive.CMIP5.Model import Instance, Version

new_results=results.filter(Instance.model=='MIROC5').filter(Version.path.contains("/data1"))

for o in new_results:
    for v in o.versions:
        print(v.version,"is latest? ",v.is_latest,"last checked on",v.checked_on)
        print("")
        if v==o.latest()[0]:
            print("Latest available version on raijin is")
            print("")
            print(v.path)
            print("")
            print(v.filenames())
            print("")
            f=v.files[0]
            print(f.filename,f.tracking_id)
            print("")
                

"""
Explanation: Which models?
End of explanation
"""


