def save_gmfs_to_netcdf(gmfs, out_dir, to_mmi=False, resolution="10k",
        cleanup=False, magic=False):
    """
    Save ground motion fields to netCDF files for use in GMT and/or QGis
    """
    for ses_id in gmfs.keys():
        dir_name = os.path.join(out_dir, "SES{:s}".format(ses_id))
        os.makedirs(dir_name)
        for rup_id in gmfs[ses_id].keys():
            #lon = gmfs[ses_id][rup_id]["GMFs"][:, 0]
            lat = gmfs[ses_id][rup_id]["GMFs"][:, 1]
            #gmvs = gmfs[ses_id][rup_id]["GMFs"][:, 2:]
            ogmf = gmfs[ses_id][rup_id]["GMFs"]
           
            for i, imt in enumerate(gmfs[ses_id][rup_id]["IMT"][2:]):
                if to_mmi:
                    if imt in AK2007.keys():
                        get_mmi = True
                    else:
                        print "Cannot convert %s to MMI" % imt
                        get_mmi = False
                else:
                    get_mmi = False
                f_stem = os.path.join(dir_name, 
                    "ses{:s}_{:s}_{:s}".format(ses_id,
                                               rup_id.replace("-", "_"),
                                               imt))
                if magic:
                    ogmf = magic_flipud(ogmf, numpy.min(lat), numpy.max(lat))
                if get_mmi:
                    ogmf[:, 2], sigma = atkinson_kaka_2007_rsa2mmi(imt,
                                                                   ogmf[:, 2])
                    f_stem = f_stem.replace(imt, "{:s}2MMI".format(imt))
                f = open(f_stem + ".xyz", "w")
                numpy.savetxt(f, ogmf, fmt="%g", delimiter=" ")
                f.close()
                # Generate GMT xyz2grd string
                llon = numpy.min(ogmf[:, 0])
                ulon = numpy.max(ogmf[:, 0])
                llat = numpy.min(ogmf[:, 1])
                ulat = numpy.max(ogmf[:, 1])
                istring = " -I%s/%s" % (resolution, resolution)
                rstring = " -R" + "{:.5f}/".format(llon) + \
                    "{:.5f}/".format(ulon) +\
                    "{:.5f}/".format(llat) + "{:.5f}".format(ulat)
                if "SA" in imt:
                    mod1 = f_stem.replace("(", "\(")
                    f_stem = mod1.replace(")", "\)")
                    
                command_string = ("xyz2grd %s -G%s" % (f_stem + ".xyz",
                                  f_stem + ".NC")) + istring + rstring
                os.system(command_string)
        if cleanup:
            os.system("find . -name '*.xyz' -type f -delete")
def save_gmfs_to_netcdf(gmf_collection, out_dir, to_mmi=False, spacing="10k",
        cleanup=False):
    """
    Exports the ground motion fields to NetCDF format
    """
    for gmf_set in gmf_collection.gmfss:
        for imt in gmf_set.gmfs.keys():
            dir_name = '%s/StochasticEventSet_%s_%s' % \
                (out_dir, gmf_set.stochasticEventSetId, imt)
            os.makedirs(dir_name)
            if to_mmi:
                if imt in AK2007.keys():
                    get_mmi = True
                else:
                    print "Cannot convert %s to MMI" % imt
                    get_mmi = False
            else:
                get_mmi = False

            map_values = []
            for rup_id, values in gmf_set.gmfs[imt]:
                rup_id = rup_id.replace("|","_")
                rup_id = rup_id.replace("=","")

                print 'saving file for rupture %s' % rup_id
                if get_mmi:
                    values[:, 2], sigma = atkinson_kaka_2007_rsa2mmi(
                        imt, 
                        values[:, 2])
                f_stem = '%s/%s' % (dir_name, rup_id)

                f = open(f_stem + ".xyz", 'w')
                numpy.savetxt(f, values, fmt='%5.2f %5.2f %g')
                f.close()
                # Generate GMT xyz2grd string
                values = numpy.array(values)
                llon = numpy.min(values[:, 0])
                ulon = numpy.max(values[:, 0])
                llat = numpy.min(values[:, 1])
                ulat = numpy.max(values[:, 1])
                istring = " -I%s/%s" % (spacing, spacing)
                rstring = " -R" + "{:.5f}/".format(llon) + \
                    "{:.5f}/".format(ulon) + "{:.5f}/".format(llat) +\
                    "{:.5f}".format(ulat)
                if "SA" in imt:
                    mod1 = f_stem.replace("(", "\(")
                    f_stem = mod1.replace(")", "\)")
                
                command_string = ("xyz2grd %s -G%s" % (f_stem + ".xyz",
                                  f_stem + ".NC")) + istring + rstring
                os.system(command_string)
    if cleanup:
        os.system("find . -name '*.xyz' -type f -delete")
def save_gmfs_to_netcdf(gmfs, out_dir, to_mmi=False, resolution="10k",
        cleanup=False, magic=False):
    """
    Save ground motion fields to netCDF files for use in GMT and/or QGis
    """
    for imt in gmfs.keys():
        dir_name = '%s/GMFS_%s' % (out_dir, imt)
        os.makedirs(dir_name)
        if to_mmi:
            if imt in AK2007.keys():
                get_mmi = True
            else:
                print "Cannot convert %s to MMI" % imt
                get_mmi = False
        else:
            get_mmi = False
            
        for i, gmf in enumerate(gmfs[imt]):
            f_stem = '%s/gmf_%s' % (dir_name, (i + 1))
            ogmf = numpy.array(gmf)
            if magic:
                ogmf = magic_flipud(ogmf,
                                    numpy.min(ogmf[:, 1]),
                                    numpy.max(ogmf[:, 1]))
            if get_mmi:
                ogmf[:, 2], sigma = atkinson_kaka_2007_rsa2mmi(imt, ogmf[:, 2])
            f = open(f_stem + ".xyz", "w")
            numpy.savetxt(f, ogmf, fmt="%g", delimiter=" ")
            f.close()
            # Generate GMT xyz2grd string
            llon = numpy.min(ogmf[:, 0])
            ulon = numpy.max(ogmf[:, 0])
            llat = numpy.min(ogmf[:, 1])
            ulat = numpy.max(ogmf[:, 1])
            istring = " -I%s/%s" % (resolution, resolution)
            rstring = " -R" + "{:.5f}/".format(llon) + "{:.5f}/".format(ulon) +\
                "{:.5f}/".format(llat) + "{:.5f}".format(ulat)
            if "SA" in imt:
                mod1 = f_stem.replace("(", "\(")
                f_stem = mod1.replace(")", "\)")
                
            command_string = ("xyz2grd %s -G%s" % (f_stem + ".xyz",
                              f_stem + ".NC")) + istring + rstring
            os.system(command_string)
    if cleanup:
        os.system("find . -name '*.xyz' -type f -delete")