Save sources - to multiple
        shapefiles corresponding to different source typolgies/geometries
        ('_point', '_area', '_simple', '_complex', '_planar')
963496
def write(self, destination, source_model, name=None):
        
        if os.path.exists(destination + ".shp"):
            os.system("rm %s.*" % destination)
        self.destination = destination
        self.filter_params(source_model)

        w_area = shapefile.Writer(shapefile.POLYGON)
        w_point = shapefile.Writer(shapefile.POINT)
        w_simple = shapefile.Writer(shapefile.POLYLINE)
        w_simple3d = shapefile.Writer(shapefile.POLYGONZ)
        w_complex = shapefile.Writer(shapefile.POLYLINEZ)
        w_planar = shapefile.Writer(shapefile.POLYGONZ)

        register_fields(w_area)
        register_fields(w_point)
        register_fields(w_simple)
        register_fields(w_simple3d)
        register_fields(w_complex)
        register_fields(w_planar)

        for src in source_model.sources:

            # Order is important here
            if "areaSource" in src.tag:
                set_params(w_area, src)
                set_area_geometry(w_area, src)
            elif "pointSource" in src.tag:
                set_params(w_point, src)
                set_point_geometry(w_point, src)
            elif "complexFaultSource" in src.tag:
                set_params(w_complex, src)
                set_complex_fault_geometry(w_complex, src)
            elif "simpleFaultSource" in src.tag:
                set_params(w_simple, src)
                set_simple_fault_geometry(w_simple, src)
                # Create the 3D polygon
                set_params(w_simple3d, src)
                set_simple_fault_geometry_3D(w_simple3d, src)
            elif "characteristicFaultSource" in src.tag:
                src_taglist = get_taglist(src)
                surface_node = src.nodes[src_taglist.index("surface")]
                for subnode in surface_node:
                    if "simpleFaultGeometry" in subnode.tag:
                        set_params(w_simple, src)
                        set_params(w_simple3d, src)
                    elif "complexFaultGeometry" in subnode.tag:
                        set_params(w_complex, src)
                    elif "planarSurface" in subnode.tag:
                        set_params(w_planar, src)
                    else:
                        raise ValueError(
                            'Geometry class %s not recognized'
                            % subnode.tag)
                    set_characteristic_geometry(w_simple, w_simple3d,
                                                w_complex, w_planar, src)
            else:
                raise ValueError('Source type %s not recognized'
                                 % src.tag)

        root = self.destination
        if len(w_area.shapes()) > 0:
            w_area.save('%s_area' % root)
        if len(w_point.shapes()) > 0:
            w_point.save('%s_point' % root)
        if len(w_complex.shapes()) > 0:
            w_complex.save('%s_complex' % root)
        if len(w_simple.shapes()) > 0:
            w_simple.save('%s_simple' % root)
            w_simple3d.save('%s_simple3d' % root)
        if len(w_planar.shapes()) > 0:
            w_planar.save('%s_planar' % root)
1016412
def localize_sources(gta, **kwargs):    
    
    # Localize all point sources
    for src in sorted(gta.roi.sources, key=lambda t: t['ts'], reverse=True):
        #    for s in gta.roi.sources:
        
        if not src['SpatialModel'] == 'PointSource':
            continue
        if src['offset_roi_edge'] > -0.1:
            continue
        
        gta.localize(src.name, **kwargs)

    gta.optimize()
    gta.print_roi()
45857
def extract_source_geom(dstore, srcidxs):
    
    for i in srcidxs.split(','):
        rec = dstore['source_info'][int(i)]
        geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
        yield rec['source_id'], geom
852030
def set_sources(self, sources):
        
        if len(sources) == 0:
            raise Exception('Must declare at least one source for a geocoder')
        self._sources = []
        for source in sources:  # iterate through a list of sources
            self.add_source(source)
791088
def append_sources_from(self, other):
        """"""
        # Get aliases lists from this `CatDict` and other
        self_aliases = self[self._KEYS.SOURCE].split(',')
        other_aliases = other[self._KEYS.SOURCE].split(',')

        # Store alias to `self`
        self[self._KEYS.SOURCE] = uniq_cdl(self_aliases + other_aliases)

        return
866900
def _create_source(self, src):
        """"""

        if src['SpatialType'] == 'SkyDirFunction':
            pylike_src = pyLike.PointSource(self.like.logLike.observation())
            pylike_src.setDir(src.skydir.ra.deg, src.skydir.dec.deg, False,
                              False)
        elif src['SpatialType'] == 'SpatialMap':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            sm = pyLike.SpatialMap(filepath)
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)
        elif src['SpatialType'] == 'RadialProfile':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            sm = pyLike.RadialProfile(filepath)
            sm.setCenter(src['ra'], src['dec'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)
        elif src['SpatialType'] == 'RadialGaussian':
            sm = pyLike.RadialGaussian(src.skydir.ra.deg, src.skydir.dec.deg,
                                       src.spatial_pars['Sigma']['value'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)

        elif src['SpatialType'] == 'RadialDisk':
            sm = pyLike.RadialDisk(src.skydir.ra.deg, src.skydir.dec.deg,
                                   src.spatial_pars['Radius']['value'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)

        elif src['SpatialType'] == 'MapCubeFunction':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            mcf = pyLike.MapCubeFunction2(filepath)
            pylike_src = pyLike.DiffuseSource(mcf,
                                              self.like.logLike.observation(),
                                              False)
        else:
            raise Exception('Unrecognized spatial type: %s',
                            src['SpatialType'])

        if src['SpectrumType'] == 'FileFunction':
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars)

            file_function = pyLike.FileFunction_cast(fn)
            filename = str(os.path.expandvars(src['Spectrum_Filename']))
            file_function.readFunction(filename)
        elif src['SpectrumType'] == 'DMFitFunction':

            fn = pyLike.DMFitFunction()
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars, fn)
            filename = str(os.path.expandvars(src['Spectrum_Filename']))
            fn.readFunction(filename)
        else:
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars)

        pylike_src.setSpectrum(fn)
        pylike_src.setName(str(src.name))

        return pylike_src
600009
def lyr_proj(lyr, t_srs, preserve_fields=True):
    
    #Need to check t_srs
    s_srs = lyr.GetSpatialRef()
    cT = osr.CoordinateTransformation(s_srs, t_srs)

    #Do everything in memory
    drv = ogr.GetDriverByName('Memory')

    #Might want to save clipped, warped shp to disk?
    # create the output layer
    #drv = ogr.GetDriverByName('ESRI Shapefile')
    #out_fn = '/tmp/temp.shp'
    #if os.path.exists(out_fn):
    #    driver.DeleteDataSource(out_fn)
    #out_ds = driver.CreateDataSource(out_fn)
    
    out_ds = drv.CreateDataSource('out')
    outlyr = out_ds.CreateLayer('out', srs=t_srs, geom_type=lyr.GetGeomType())

    if preserve_fields:
        # add fields
        inLayerDefn = lyr.GetLayerDefn()
        for i in range(0, inLayerDefn.GetFieldCount()):
            fieldDefn = inLayerDefn.GetFieldDefn(i)
            outlyr.CreateField(fieldDefn)
        # get the output layer's feature definition
    outLayerDefn = outlyr.GetLayerDefn()

    # loop through the input features
    inFeature = lyr.GetNextFeature()
    while inFeature:
        # get the input geometry
        geom = inFeature.GetGeometryRef()
        # reproject the geometry
        geom.Transform(cT)
        # create a new feature
        outFeature = ogr.Feature(outLayerDefn)
        # set the geometry and attribute
        outFeature.SetGeometry(geom)
        if preserve_fields:
            for i in range(0, outLayerDefn.GetFieldCount()):
                outFeature.SetField(outLayerDefn.GetFieldDefn(i).GetNameRef(), inFeature.GetField(i))
        # add the feature to the shapefile
        outlyr.CreateFeature(outFeature)
        # destroy the features and get the next input feature
        inFeature = lyr.GetNextFeature()
    #NOTE: have to operate on ds here rather than lyr, otherwise segfault
    return out_ds
100626
def _write_source_data(self, sources):
        
        for i, source in enumerate(sources):
            self._write_source(source)
1268449
def write_line_shp(line_list, out_shp):
        """"""
        print('Write line shapefile: %s' % out_shp)
        driver = ogr_GetDriverByName(str('ESRI Shapefile'))
        if driver is None:
            print('ESRI Shapefile driver not available.')
            sys.exit(1)
        if os.path.exists(out_shp):
            driver.DeleteDataSource(out_shp)
        ds = driver.CreateDataSource(out_shp.rpartition(os.sep)[0])
        if ds is None:
            print('ERROR Output: Creation of output file failed.')
            sys.exit(1)
        lyr = ds.CreateLayer(str(out_shp.rpartition(os.sep)[2].split('.')[0]), None, wkbLineString)
        for l in line_list:
            line = ogr_Geometry(wkbLineString)
            for i in l:
                line.AddPoint(i[0], i[1])
            templine = ogr_CreateGeometryFromJson(line.ExportToJson())
            feature = ogr_Feature(lyr.GetLayerDefn())
            feature.SetGeometry(templine)
            lyr.CreateFeature(feature)
            feature.Destroy()
        ds.Destroy()
934589
def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True):
        """"""
        geoms = {}
        raw_data = []
        for key in sorted(excluded):
            locations = excluded[key]
            for location in locations:
                assert location in self.locations, "Can't find location {}".format(location)
            included = self.all_faces.difference(
                {face for loc in locations for face in self.data[loc]}
            )
            raw_data.append((key, self.faces_fp, included))
        if use_mp:
            with Pool(cpu_count() - 1) as pool:
                results = pool.map(_union, raw_data)
            geoms = dict(results)
        else:
            geoms = dict([_union(row) for row in raw_data])
        if simplify:
            geoms = {k: v.simplify(0.05) for k, v in geoms.items()}
        if fp:
            labels = sorted(geoms)
            self.write_geoms_to_file(fp, [geoms[key] for key in labels], labels)
            return fp
        else:
            return geoms
307963
def convertor(geometry, method="wgs2gcj"):
    
    if geometry['type'] == 'Point':
        coords = geometry['coordinates']
        coords[0], coords[1] = methods[method](coords[0], coords[1])
    elif geometry['type'] == 'LineString' or geometry['type'] == 'MutliPoint':
        coordinates = geometry['coordinates']
        for coords in coordinates:
            coords[0], coords[1] = methods[method](coords[0], coords[1])
    elif geometry['type'] == 'Polygon' or geometry['type'] == 'MultiLineString':
        coordinates = geometry['coordinates']
        for rings in coordinates:
            for coords in rings:
                coords[0], coords[1] = methods[method](coords[0], coords[1])
    elif geometry['type'] == 'MultiPolygon':
        coordinates = geometry['coordinates']
        for rings in coordinates:
            for lines in rings:
                for coords in lines:
                    coords[0], coords[1] = methods[method](coords[0], coords[1])
    return geometry
272776
def pysourcefiles(self):
        """"""
        sourcefiles = set()
        for (name, child) in vars(self).items():
            try:
                parents = inspect.getmro(child)
            except AttributeError:
                continue
            for parent in parents:
                try:
                    sourcefile = inspect.getfile(parent)
                except TypeError:
                    break
                sourcefiles.add(sourcefile)
        return Lines(*sourcefiles)
386874
def update_source_model(sm_node, fname):
    
    i = 0
    for group in sm_node:
        if 'srcs_weights' in group.attrib:
            raise InvalidFile('srcs_weights must be removed in %s' % fname)
        if not group.tag.endswith('sourceGroup'):
            raise InvalidFile('wrong NRML, got %s instead of '
                              'sourceGroup in %s' % (group.tag, fname))
        psrcs = []
        others = []
        for src in group:
            try:
                del src.attrib['tectonicRegion']  # make the trt implicit
            except KeyError:
                pass  # already missing
            if src.tag.endswith('pointSource'):
                psrcs.append(src)
            else:
                others.append(src)
        others.sort(key=lambda src: (src.tag, src['id']))
        i, sources = _pointsources2multipoints(psrcs, i)
        group.nodes = sources + others
1206437
def dump(self, zone, output_dir, lenient, split, source, *sources):
        '''
        
        '''
        self.log.info('dump: zone=%s, sources=%s', zone, sources)

        # We broke out source to force at least one to be passed, add it to any
        # others we got.
        sources = [source] + list(sources)

        try:
            sources = [self.providers[s] for s in sources]
        except KeyError as e:
            raise Exception('Unknown source: {}'.format(e.args[0]))

        clz = YamlProvider
        if split:
            clz = SplitYamlProvider
        target = clz('dump', output_dir)

        zone = Zone(zone, self.configured_sub_zones(zone))
        for source in sources:
            source.populate(zone, lenient=lenient)

        plan = target.plan(zone)
        if plan is None:
            plan = Plan(zone, zone, [], False)
        target.apply(plan)
1309346
def set_point_geometry(w, src):
    
    assert "pointSource" in src.tag
    geometry_node = src.nodes[get_taglist(src).index("pointGeometry")]
    point_attrs = parse_point_geometry(geometry_node)
    w.point(point_attrs["point"][0], point_attrs["point"][1])
1188571
def _copy_sources(self, target, results_dir):
    
    buildroot = get_buildroot()
    source_relative_to = target.address.spec_path
    for source in target.sources_relative_to_buildroot():
      dest = os.path.join(results_dir, os.path.relpath(source, source_relative_to))
      safe_mkdir(os.path.dirname(dest))
      shutil.copyfile(os.path.join(buildroot, source), dest)
61426
def read(self, input_shapefile, validate=False,
             simple_fault_spacing=1.0, complex_mesh_spacing=5.0,
             mfd_spacing=0.1):
        
        reader = shapefile.Reader(input_shapefile)
        fields = [field[0] for field in reader.fields[1:]]
        shapes = reader.shapes()
        records = reader.records()
        sources = []
        if validate:
            converter = SourceConverter(1.0, simple_fault_spacing,
                                        complex_mesh_spacing,
                                        mfd_spacing,
                                        10.0)
        for iloc in range(0, reader.numRecords):
            # Build record dictionary
            record = record_to_dict(records[iloc], fields)
            shape = shapes[iloc]
            if "pointSource" in record["sourcetype"]:
                src = build_point_source_from_shp(shape, record)
            elif "areaSource" in record["sourcetype"]:
                src = build_area_source_from_shp(shape, record)
            elif "simpleFaultSource" in record["sourcetype"]:
                src = build_simple_fault_source_from_shp(shape, record)
            elif "complexFaultSource" in record["sourcetype"]:
                src = build_complex_fault_source_from_shp(shape, record)
            elif "characteristicFaultSource" in record["sourcetype"]:
                print("Characteristic Fault Source Not Yet Supported - Sorry!")
                src = None
            if src and validate:
                print("Validating Source %s" % src.attrib["id"])
                converter.convert_node(src)
            if src:
                sources.append(src)
        return SourceModel(sources)