Exemplo n.º 1
0
def make_pressure_color_arrays(vesselgraph):
    edges = vesselgraph.edgelist
    flags = vesselgraph.edges['flags']
    data = vesselgraph.nodes['pressure']
    num_nodes = len(vesselgraph.nodes['position'])
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')

    is_set = lambda flags_, flag: np.asarray(np.bitwise_and(flags_, flag), np.
                                             bool)

    gray = np.asarray((0.1, 0.1, 0.1))
    lgray = np.asarray((0.5, 0.5, 0.5))

    circulated = is_set(flags, krebsutils.CIRCULATED)
    ncirculated = is_set(nflags, krebsutils.CIRCULATED)
    capillary = is_set(flags, krebsutils.CAPILLARY)
    ncapillary = is_set(nflags, krebsutils.CAPILLARY)
    p0 = np.amin(data[ncirculated])
    p1 = np.amax(data[ncirculated])
    cm = matplotlib.cm.ScalarMappable(cmap=cm_redblue)
    cm.set_clim(p0, p1)

    edgedata = np.average((data[edges[:, 0]], data[edges[:, 1]]), axis=0)
    edgecolors = cm.to_rgba(edgedata)[:, :3]
    edgecolors[~circulated] = gray
    #edgecolors[capillary] = lgray

    nodecolors = cm.to_rgba(data)[:, :3]
    nodecolors[~ncirculated] = gray
    #nodecolors[ncapillary] = lgray

    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
def renderSliceWithDistribution(vesselgroup, imagefn, options):
    vessel_ld = krebsutils.read_lattice_data_from_hdf(
        vesselgroup['vessels/lattice'])
    vessel_graph = krebsutils.read_vessels_from_hdf(
        vesselgroup['vessels'],
        ['position', 'flags', 'radius', 'pressure', 'shearforce', 'nodeflags'],
        return_graph=True)
    vessel_graph.edges['radius'] *= 4.

    #kwargs = deepcopy(kwargs)
    wbbox = vessel_ld.worldBox
    trafo = calc_centering_normalization_trafo(wbbox)
    height = (wbbox[5] - wbbox[4]) * trafo.w

    print('Vessel BBox:' + str(vessel_ld.worldBox))
    print(vessel_ld)
    print('Post Trafo Ld BBox:' + str(transform_ld(trafo, vessel_ld).worldBox))

    hasGfField = 'field_ld' in vesselgroup and vessel_ld.shape[2] == 1
    #hasGfField = False
    if hasGfField:
        volume_ld = krebsutils.read_lattice_data_from_hdf(
            vesselgroup['field_ld'])
        print('Volume BBox:' + str(volume_ld.worldBox))
        print(volume_ld)
        volumedata = np.asarray(vesselgroup['gf'])
        #print volumedata.shape, volumedata.min(), volumedata.max()
        volume_ld = transform_ld(trafo, volume_ld)
        print('Post Trafo Volume BBox:' + str(volume_ld.worldBox))
        print('volume data bounds:' + str(volumedata.min()),
              str(volumedata.max()))

    colorfactory(vessel_graph)

    with EasyPovRayRender(**options) as epv:
        epv.setBackground(options.pop('background', 0.0))

        cam_fov = 60.
        cam_distance_factor = ComputeCameraDistanceFactor(
            cam_fov, options['res'], wbbox)

        epv.setCamera((0, 0, cam_distance_factor * 1.05),
                      lookat=(0, 0, 0),
                      fov=cam_fov,
                      up='y')

        epv.addLight(10. * Vec3(1, 0.5, 2), 1.2)

        cm = matplotlib.cm.ScalarMappable(cmap=cm_gf)
        cm.set_clim(-0.01, 1.01)
        pvcm = matplotlibColormapToPovray('DATACOLORMAP', cm)
        epv.declareColorMap(pvcm)

        if hasGfField:
            volumedata = epv.declareVolumeData(volumedata, volume_ld.worldBox,
                                               volume_ld)
            epv.addVolumeDataSlice(volumedata, (0, 0, 0), (0, 0, 1.), pvcm)
        addVesselTree(epv, vessel_graph, trafo=trafo, **options)

        imagefn = epv.render(imagefn)
Exemplo n.º 3
0
    def get(self):
        logging.info('GET self.request.body = {}'.format(self.request.body))
        reqType = self.request.get('reqType')

        if reqType == 'getJobInfo':
            job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))

            if self.user.user_id() != job.user_id:
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write({
                    "status": False,
                    "msg": "Not the right user"
                })

            result = {}
            stdout = ''
            stderr = ''
            complete = ''
            if job.outData is None:
                complete = 'yes'
            else:
                try:
                    fstdoutHandle = open(str(job.outData + '/stdout.log'), 'r')
                    stdout = fstdoutHandle.read()
                    fstdoutHandle.close()
                    fstderrHandle = open(str(job.outData + '/stderr.log'), 'r')
                    stderr = fstderrHandle.read()
                    fstderrHandle.close()
                    if os.path.exists("{0}/results/complete".format(
                            job.outData)):
                        complete = 'yes'
                except IOError as e:
                    traceback.print_exc()
                    result['status'] = False
                    result[
                        'msg'] = 'Error running the simulation: stdout/stderr outputs missing.'

            result.update({
                "id": int(self.request.get('id')),
                "jobStatus": job.status,
                "complete": complete,
                "resource": job.resource,
                "modelName": job.modelName,
                "outData": job.outData,
                "name": job.name,
                "uuid": job.cloudDatabaseID,
                "output_stored": job.output_stored,
                "stdout": stdout,
                "stderr": stderr,
                "indata": json.loads(job.indata)
            })

            logging.debug("result =\n\n{}".format(pprint.pformat(result)))

            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(result))
            return
        elif reqType == 'getMeshData':
            try:
                job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))

                data = json.loads(self.request.get('data'))

                logging.debug("data = {}".format(data))

                trajectory = data["trajectory"]
                timeIdx = data["timeIdx"]
                resultJS = {}

                #if not job.preprocessed or not os.path.exists(job.preprocessedDir):
                job.preprocess(trajectory)

                indir = job.preprocessedDir

                with open(os.path.join(indir, 'mesh.json'), 'r') as meshfile:
                    mesh = json.load(meshfile)

                with open(os.path.join(indir, 'voxelTuples.json'),
                          'r') as voxelTuplesFile:
                    voxelTuples = json.load(voxelTuplesFile)

                f = os.path.join(indir, 'result{0}'.format(trajectory))

                with h5py.File(f, 'r') as dataFile:
                    species = dataFile.keys()

                self.response.content_type = 'application/json'
                self.response.write(
                    json.dumps({
                        "mesh": mesh,
                        "voxelTuples": voxelTuples,
                        "species": species
                    }))

            except Exception as e:
                traceback.print_exc()
                result = {}
                result['status'] = False
                result['msg'] = 'Error: error fetching results {0}'.format(e)
                self.response.headers['Content-Type'] = 'application/json'

                self.response.write(json.dumps(result))
            return
        elif reqType == 'getTimeSeriesData':
            try:
                job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))
                data = json.loads(self.request.get('data'))
                logging.debug(
                    'patial.get(onlyColorRange): data={0}'.format(data))
                trajectory = data["trajectory"]
                sTime = data["timeStart"]
                eTime = data["timeEnd"]

                #TODO: what is the right value here?
                if eTime is None:
                    eTime = 0
                dataType = "population" if "showPopulation" in data and data[
                    "showPopulation"] else "concentration"

                resultJS = {}

                if job.preprocessed is None or trajectory not in job.preprocessed or not os.path.exists(
                        job.preprocessedDir):
                    job.preprocess(trajectory)

                f = os.path.join(job.preprocessedDir,
                                 'result{0}'.format(trajectory))

                limits = {}

                logging.debug(
                    'Spatial.get(onlyColorRange): sTime={0} eTime={0}'.format(
                        sTime, eTime))

                with h5py.File(f, 'r') as dataFile:
                    dataTmp = {}
                    colorTmp = {}

                    for specie in dataFile.keys():
                        data2 = dataFile[specie][dataType][sTime:eTime + 1]

                        dataTmp[specie] = data2

                        limits[specie] = {
                            'min': dataFile[specie][dataType].attrs['min'],
                            'max': dataFile[specie][dataType].attrs['max']
                        }

                        cm.set_clim(dataFile[specie][dataType].attrs['min'],
                                    dataFile[specie][dataType].attrs['max'])
                        rgbas = cm.to_rgba(data2, bytes=True).astype('uint32')

                        rgbas = numpy.left_shift(
                            rgbas[:, :, 0], 16) + numpy.left_shift(
                                rgbas[:, :, 1], 8) + rgbas[:, :, 2]

                        #rgbaInts = numpy.zeros((rgbas.shape[0], rgbas.shape[1]))

                        #for i in range(rgbas.shape[0]):
                        #    for j in range(rgbas.shape[1]):
                        #        rgbaInts[i, j] = int('0x%02x%02x%02x' % tuple(rgbas[i, j][0:3]), 0)

                        colorTmp[specie] = []
                        for i in range(rgbas.shape[0]):
                            colorTmp[specie].append(
                                list(rgbas[i].astype('int')))

                    colors = {}
                    data = {}
                    for i in range(abs(eTime - sTime + 1)):
                        colors[sTime + i] = {}
                        data[sTime + i] = {}
                        for specie in dataFile.keys():
                            colors[sTime + i][specie] = colorTmp[specie][i]
                            data[sTime + i][specie] = list(dataTmp[specie][i])

                self.response.content_type = 'application/json'
                self.response.write(
                    json.dumps({
                        "colors": colors,
                        "raw": data,
                        "limits": limits
                    }))

            except Exception as e:
                traceback.print_exc()
                result = {}
                result['status'] = False
                result['msg'] = 'Error: error fetching results {0}'.format(e)
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write(json.dumps(result))

            return

        self.render_response('spatial.html')
Exemplo n.º 4
0
def make_any_color_arrays(vesselgraph, data_name):
    edges = vesselgraph.edgelist
    num_nodes = len(vesselgraph.nodes['position'])
    flags = vesselgraph.edges['flags']
    flags = np.asarray(flags, dtype='uint32')
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')

    mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    nmask = myutils.bbitwise_and(nflags, krebsutils.CIRCULATED)

    if data_name in vesselgraph.edges:
        edgedata = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, edgedata,
                                                    'avg')
    else:
        nodedata = vesselgraph.nodes[data_name]
        edgedata = np.average((nodedata[edges[:, 0]], nodedata[edges[:, 1]]),
                              axis=0)

    gray = np.asarray((0.1, 0.1, 0.1))
    edgecolors = np.repeat(gray.reshape(1, -1), len(edgedata), axis=0)
    nodecolors = np.repeat(gray.reshape(1, -1), len(nodedata), axis=0)
    #colors = lambda arr: cm.to_rgba(arr)[:,:3]
    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)

    if data_name == 'hematocrit':
        cm = matplotlib.cm.ScalarMappable(cmap=cm_hematocrit)
        cm.set_clim(0, 1)
        unmapped_range = (0., 1.)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'pressure':
        #this looks really ugly if there is a zero pressure node
        #p0 = np.amin(nodedata)
        p0 = np.min(nodedata[np.nonzero(nodedata)])
        p1 = np.amax(nodedata)
        unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_redblue)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'shearforce':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = -4  #np.amin(edgedata)
        p1 = -1  #np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'S_tot':
        #mask = mask & (edgedata>0)
        #nmask = nmask & (nodedata>0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        #print("p0: %f, p1: %f" % (p0,p1))
        #unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        #edgedata = np.log10(edgedata)
        #nodedata = np.log10(nodedata)
        #p0 = -4#np.amin(edgedata)
        #p1 = -1#np.amax(edgedata)
        #cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        #cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flow':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = np.floor(np.amin(edgedata))
        p1 = np.ceil(np.amax(edgedata))
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'conductivitySignal':
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'metabolicSignal':
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flags':
        edgecolors[mask
                   & (flags & krebsutils.ARTERY).astype(np.bool)] = np.asarray(
                       (1., 0., 0.))
        nodecolors[nmask & (nflags
                            & krebsutils.ARTERY).astype(np.bool)] = np.asarray(
                                (1., 0., 0.))
        edgecolors[mask
                   & (flags & krebsutils.VEIN).astype(np.bool)] = np.asarray(
                       (0., 0., 1.))
        nodecolors[nmask
                   & (nflags & krebsutils.VEIN).astype(np.bool)] = np.asarray(
                       (0., 0., 1.))
        edgecolors[mask
                   & (flags
                      & krebsutils.CAPILLARY).astype(np.bool)] = np.asarray(
                          (0., 1., 0.))
        nodecolors[nmask
                   & (nflags
                      & krebsutils.CAPILLARY).astype(np.bool)] = np.asarray(
                          (0., 1., 0.))
        for idx in vesselgraph.roots:
            nodecolors[idx] = np.asarray((1., 1., 0.))
        cm, unmapped_range = None, (None, None)
    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm, unmapped_range
Exemplo n.º 5
0
    def get(self):
        logging.info('GET self.request.body = {}'.format(self.request.body))
        reqType = self.request.get('reqType')

        if reqType == 'getJobInfo':
            job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))

            if self.user.user_id() != job.user_id:
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write({ "status" : False, "msg" : "Not the right user" })

            result = {}
            stdout = ''
            stderr = ''
            complete = ''
            if job.outData is None:
                complete = 'yes'
            else:
                try:
                    fstdoutHandle = open(str(job.outData + '/stdout.log'), 'r')
                    stdout = fstdoutHandle.read()
                    fstdoutHandle.close()
                    fstderrHandle = open(str(job.outData + '/stderr.log'), 'r')
                    stderr = fstderrHandle.read()
                    fstderrHandle.close()
                    if os.path.exists("{0}/results/complete".format(job.outData)):
                        complete = 'yes'
                except IOError as e:
                    traceback.print_exc()
                    result['status'] = False
                    result['msg'] = 'Error running the simulation: stdout/stderr outputs missing.'

            result.update({"id" : int(self.request.get('id')),
                           "jobStatus" : job.status,
                           "complete" : complete,
                           "resource" : job.resource,
                           "modelName" : job.modelName,
                           "outData" : job.outData,
                           "name" : job.name,
                           "uuid": job.cloudDatabaseID,
                           "output_stored": job.output_stored,
                           "stdout" : stdout,
                           "stderr" : stderr,
                           "indata" : json.loads(job.indata) })

            logging.debug("result =\n\n{}".format(pprint.pformat(result)))

            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(result))
            return
        elif reqType == 'getMeshData':
            try:
                job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))

                data = json.loads(self.request.get('data'))

                logging.debug("data = {}".format(data))

                trajectory = data["trajectory"]
                timeIdx = data["timeIdx"]                
                resultJS = {}

                #if not job.preprocessed or not os.path.exists(job.preprocessedDir):
                job.preprocess(trajectory)

                indir = job.preprocessedDir
                    
                with open(os.path.join(indir, 'mesh.json') ,'r') as meshfile:
                    mesh = json.load(meshfile)

                with open(os.path.join(indir, 'voxelTuples.json') ,'r') as voxelTuplesFile:
                    voxelTuples = json.load(voxelTuplesFile)

                f = os.path.join(indir, 'result{0}'.format(trajectory))
                
                with h5py.File(f, 'r') as dataFile:
                    species = dataFile.keys()

                self.response.content_type = 'application/json'
                self.response.write(json.dumps({ "mesh" : mesh, "voxelTuples" : voxelTuples, "species" : species }))
            
            except Exception as e:
                traceback.print_exc()
                result = {}
                result['status'] = False
                result['msg'] = 'Error: error fetching results {0}'.format(e)
                self.response.headers['Content-Type'] = 'application/json'

                self.response.write(json.dumps(result))
            return
        elif reqType == 'getTimeSeriesData':
            try:
                job = SpatialJobWrapper.get_by_id(int(self.request.get('id')))
                data = json.loads(self.request.get('data'))
                logging.debug('patial.get(onlyColorRange): data={0}'.format(data))
                trajectory = data["trajectory"]
                sTime= data["timeStart"]
                eTime = data["timeEnd"]

                #TODO: what is the right value here?
                if eTime is None:
                    eTime = 0
                dataType = "population" if "showPopulation" in data and data["showPopulation"] else "concentration"

                resultJS = {}

                if job.preprocessed is None or trajectory not in job.preprocessed or not os.path.exists(job.preprocessedDir):
                    job.preprocess(trajectory)

                f = os.path.join(job.preprocessedDir, 'result{0}'.format(trajectory))

                limits = {}

                logging.debug('Spatial.get(onlyColorRange): sTime={0} eTime={0}'.format(sTime,eTime))

                with h5py.File(f, 'r') as dataFile:
                    dataTmp = {}
                    colorTmp = {}

                    for specie in dataFile.keys():
                        data2 = dataFile[specie][dataType][sTime:eTime + 1]

                        dataTmp[specie] = data2
                        
                        limits[specie] = { 'min' : dataFile[specie][dataType].attrs['min'],
                                           'max' : dataFile[specie][dataType].attrs['max'] }

                        cm.set_clim(dataFile[specie][dataType].attrs['min'], dataFile[specie][dataType].attrs['max'])
                        rgbas = cm.to_rgba(data2, bytes = True).astype('uint32')

                        rgbas = numpy.left_shift(rgbas[:, :, 0], 16) + numpy.left_shift(rgbas[:, :, 1], 8) + rgbas[:, :, 2]
                        
                        #rgbaInts = numpy.zeros((rgbas.shape[0], rgbas.shape[1]))

                        #for i in range(rgbas.shape[0]):
                        #    for j in range(rgbas.shape[1]):
                        #        rgbaInts[i, j] = int('0x%02x%02x%02x' % tuple(rgbas[i, j][0:3]), 0)

                        colorTmp[specie] = []
                        for i in range(rgbas.shape[0]):
                            colorTmp[specie].append(list(rgbas[i].astype('int')))

                    colors = {}
                    data = {}
                    for i in range(abs(eTime - sTime + 1)):
                        colors[sTime + i] = {}
                        data[sTime + i] = {}
                        for specie in dataFile.keys():
                            colors[sTime + i][specie] = colorTmp[specie][i] 
                            data[sTime + i][specie] = list(dataTmp[specie][i])

                self.response.content_type = 'application/json'
                self.response.write(json.dumps( { "colors" : colors, "raw" : data, "limits" : limits } ))

            except Exception as e:
                traceback.print_exc()
                result = {}
                result['status'] = False
                result['msg'] = 'Error: error fetching results {0}'.format(e)
                self.response.headers['Content-Type'] = 'application/json'
                self.response.write(json.dumps(result))

            return
        
        self.render_response('spatial.html')
def InsertGraphColors(vesselgraph, po2field, data_name):
    edges = vesselgraph.edgelist
    num_nodes = len(vesselgraph.nodes['position'])

    if data_name in vesselgraph.edges:
        edgedata = data = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, data,
                                                    'avg')
    else:
        nodedata = data = vesselgraph.nodes[data_name]
        edgedata = np.average((data[edges[:, 0]], data[edges[:, 1]]), axis=0)

    if data_name == 'po2vessels':
        try:
            p1 = np.amax(data)
        except ValueError:
            print("p1 not found")
            pass
        if po2field is not None:
            p1 = max(p1, np.amax(po2field))
        try:
            p0 = np.amin(data)
        except ValueError:
            print("p0 not found")
            pass
        if po2field is not None:
            p0 = min(p0, np.amin(po2field))
        #p1 = math.ceil(p1/10.0)*10.0  # round to powers of something
        #p1 = 100.0
        value_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_po2)
    elif data_name == 'saturation':
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        vesselgraph.edges['saturation']
        value_range = (np.min(vesselgraph.edges['saturation']),
                       np.max(vesselgraph.edges['saturation']))
        #value_range = (0,1.)
    elif data_name == 'hboconc':
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.gnuplot)
        p1 = math.ceil(np.amax(data))
        value_range = (0., p1)
    cm.set_clim(*value_range)

    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)
    if data_name in vesselgraph.edges:
        edgecolors = colors(data)
        nodecolors = colors(nodedata)
    else:
        edgecolors = colors(edgedata)
        nodecolors = colors(data)

    flags = vesselgraph.edges['flags']
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')
    is_not_set = lambda flags_, flag: np.bitwise_not(
        np.asarray(np.bitwise_and(flags_, flag), np.bool))
    gray = np.asarray((0.3, 0.3, 0.3))
    uncirculated = is_not_set(flags, krebsutils.CIRCULATED)
    nuncirculated = is_not_set(nflags, krebsutils.CIRCULATED)
    edgecolors[uncirculated] = gray
    nodecolors[nuncirculated] = gray

    print 'colormap range ', cm.get_clim()

    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm
Exemplo n.º 7
0
def InsertGraphColors(vesselgraph, ifffield, data_name, automatic_scale=False, max_conc=1.0):
  edges = vesselgraph.edgelist
  num_nodes = len(vesselgraph.nodes['position'])

#  if data_name in vesselgraph.edges:
#    edgedata = data = vesselgraph.edges[data_name]
#    nodedata = krebsutils.edge_to_node_property(num_nodes, edges, data, 'avg')
#  else:
#    nodedata = data = vesselgraph.nodes[data_name]
#    edgedata = np.average((data[edges[:,0]], data[edges[:,1]]), axis=0)
  #note everything is uncirculated anyway
  #edgedata = data = vesselgraph.edges['radius']
  #nodedata = krebsutils.edge_to_node_property(num_nodes, edges, data, 'avg')

  if data_name == 'auc':
    #p1 = np.amax(data)
    #if po2field is not None:
    #  p1 = max(p1, np.amax(po2field))
    #p1 = math.ceil(p1/10.0)*10.0  # round to powers of something
    
    #p1 = 100.0
    #value_range = (np.amin(ifffield), np.amax(ifffield))
    color_norm = matplotlib.colors.LogNorm().autoscale(ifffield)
    cm = matplotlib.cm.ScalarMappable(cmap = 'Reds', norm=color_norm)
    #value_range = (0, 37000)
    value_range = (np.amin(ifffield), np.amax(ifffield))
    if value_range[0]==0 and value_range[1] == 0:
      value_range = (-1,1)
    #cm = matplotlib.cm.ScalarMappable(cmap = 'Reds')
    cm.set_clim(*value_range)
    #cm = matplotlib.colors.LinearSegmentedColormap.from_list('my_cmap',[(0,0,0,0),'red'],256)
    #cm = plt.get_cmap('Reds')
  elif data_name == 'iff_pressure':
    cm = matplotlib.cm.ScalarMappable(cmap = matplotlib.cm.spectral)
    value_range = (np.amin(ifffield), np.amax(ifffield))
    cm.set_clim(*value_range)
  elif data_name == 'drug_conc':
    cm = matplotlib.cm.ScalarMappable(cmap = matplotlib.cm.Spectral, norm=matplotlib.colors.LogNorm())
    if automatic_scale:
      value_range = (np.amin(ifffield), np.amax(ifffield))
    else:
      value_range= (1e-3,0.5e0)
    # new global variable
    if not max_conc == 1.0:
      value_range = (1e-3, max_conc)
    else:
      value_range = (np.amin(ifffield), np.amax(ifffield))
    print(value_range)
    if value_range[0]==0 and value_range[1] == 0:
      value_range = (1,2)
    #value_range = (0, 0.42)
    #color_norm = matplotlib.colors.LogNorm(*value_range)
    #color_norm = matplotlib.colors.LogNorm().autoscale(ifffield)
    #cm = matplotlib.cm.ScalarMappable(cmap = 'Reds', norm=color_norm)
    #cm = matplotlib.cm.ScalarMappable(cmap = 'Reds', norm=color_norm)
    #if np.amin(ifffield) <0:
    #  value_range = (0, np.amax(ifffield))
    #else:
    #value_range = (np.amin(ifffield), np.amax(ifffield))
    #value_range = (1e-7, 0.5)
    
    #value_range = (0, 0.42)
    
    #value_range = (0.01, 0.3)
    cm.set_clim(*value_range)
    #cm.autoscale(ifffield)
    #cm.LogNorm()
  else:
    cm = matplotlib.cm.ScalarMappable(cmap = matplotlib.cm.gnuplot)
    p1 = math.ceil(np.amax(data))
    value_range = (0., p1)
    
  

  #colors = lambda arr: np.power(cm.to_rgba(arr)[:,:3], 2.4)
  edgedata = vesselgraph.edges['radius']
  nodedata = krebsutils.edge_to_node_property(num_nodes, edges, edgedata, 'avg')
  
  if 1:
    print('custom cm:')
    mycm = matplotlib.colors.Colormap('Reds')
    
    theEdgeColors = np.ones((len(edgedata),3))
    theNodeColors = np.ones((len(nodedata),3))
    blue=matplotlib.colors.colorConverter.to_rgba('blue')
    normalizedEdgeData = matplotlib.colors.Normalize(vmin=np.amin(edgedata),vmax=np.amax(edgedata))(edgedata)
    normalizedNodeData = matplotlib.colors.Normalize(vmin=np.amin(edgedata),vmax=np.amax(edgedata))(nodedata)
    #normalizedEdgeData = matplotlib.colors.LogNorm(vmin=np.amin(edgedata),vmax=np.amax(edgedata))(edgedata)
    #normalizedNodeData = matplotlib.colors.LogNorm(vmin=np.amin(edgedata),vmax=np.amax(edgedata))(nodedata)
    #normalizedEdgeData = matplotlib.colors.LogNorm()(edgedata)
    #normalizedNodeData = matplotlib.colors.LogNorm()(nodedata)
    for (no, intensity) in enumerate(normalizedEdgeData):
      theEdgeColors[no,:] = np.multiply(blue[0:3],intensity)
    for (no, intensity) in enumerate(normalizedNodeData):
      theNodeColors[no,:] = np.multiply(blue[0:3],intensity)
    vesselgraph.edges['colors'] = theEdgeColors
    vesselgraph.nodes['colors'] = theNodeColors
  return cm
Exemplo n.º 8
0
    'image_size': (375, 1242)
}

# Find indices of scene/object/distance
indices = {}
for s in cfg['sets']:
    for d in cfg['distances']:
        with open(os.path.join(cfg['data_path'], 'filenames_{:03d}.txt'.format(cfg['filenames_index'])), 'rt') as f:
            for index, row in enumerate(f):
                if row.strip('\n') == cfg['filename_fmt'].format(set=s, scene=cfg['scene'], object=cfg['object'], distance=d):
                    indices[(s, d)] = index
                    break

# Compile images
cm = matplotlib.cm.ScalarMappable(None, cmap='plasma')
cm.set_clim(0.00, 0.08)
disparities = np.load(os.path.join(cfg['disp_path'], cfg['disp_fmt'].format(cfg['filenames_index'])), mmap_mode='r')
full_image = np.zeros((2 * len(cfg['sets']) * cfg['image_size'][0], len(cfg['distances']) * cfg['image_size'][1], 3), dtype=np.uint8)
for si, s in enumerate(cfg['sets']):
    print('Set: {}'.format(s))
    imgs = np.zeros((cfg['image_size'][0], len(cfg['distances']) * cfg['image_size'][1], 3), dtype=np.uint8)
    disps = np.zeros_like(imgs)
    for di, d in enumerate(cfg['distances']):
        fn = cfg['filename_fmt'].format(set=s, scene=cfg['scene'], object=cfg['object'], distance=d)
        mask_fn = cfg['mask_fmt'].format(set=s, scene=cfg['scene'], object=cfg['object'], distance=d)
        img = imread(os.path.join(cfg['data_path'], fn))
        img = img_as_ubyte(resize(img, cfg['image_size']))
        imgs[:, (di * cfg['image_size'][1]):((di + 1) * cfg['image_size'][1])] = img
        mask = imread(os.path.join(cfg['data_path'], mask_fn))[:, :, 0]
        mask = resize(mask, cfg['image_size'])
        c = find_contours(mask, 0.5)[0]
    'image_size': (375, 1242)
}

# Find indices of scene/object/distance
# indices = {}
# for s in cfg['sets']:
#     for d in cfg['distances']:
#         with open(os.path.join(cfg['data_path'], 'filenames_{:03d}.txt'.format(cfg['filenames_index'])), 'rt') as f:
#             for index, row in enumerate(f):
#                 if row.strip('\n') == cfg['filename_fmt'].format(set=s, scene=cfg['scene'], object=cfg['object'], distance=d):
#                     indices[(s, d)] = index
#                     break

# Compile images
cm = matplotlib.cm.ScalarMappable(None, cmap='plasma')
cm.set_clim(0.00, 0.20)
# disparities = np.load(os.path.join(cfg['disp_path'], cfg['disp_fmt'].format(cfg['filenames_index'])), mmap_mode='r')
full_image = np.zeros((2 * len(cfg['sets']) * cfg['image_size'][0],
                       len(cfg['distances']) * cfg['image_size'][1], 3),
                      dtype=np.uint8)
for si, s in enumerate(cfg['sets']):
    print('Set: {}'.format(s))
    imgs = np.zeros((cfg['image_size'][0],
                     len(cfg['distances']) * cfg['image_size'][1], 3),
                    dtype=np.uint8)
    disps = np.zeros_like(imgs)
    for di, d in enumerate(cfg['distances']):
        fn = cfg['filename_fmt'].format(set=s,
                                        scene=cfg['scene'],
                                        object=cfg['object'],
                                        distance=d)
Exemplo n.º 10
0
def make_any_color_arrays(vesselgraph, data_name):
    edges = vesselgraph.edgelist
    num_nodes = len(vesselgraph.nodes['position'])
    flags = vesselgraph.edges['flags']
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')

    mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    nmask = myutils.bbitwise_and(nflags, krebsutils.CIRCULATED)

    if data_name in vesselgraph.edges:
        edgedata = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, edgedata,
                                                    'avg')
    else:
        nodedata = vesselgraph.nodes[data_name]
        edgedata = np.average((nodedata[edges[:, 0]], nodedata[edges[:, 1]]),
                              axis=0)

    gray = np.asarray((0.1, 0.1, 0.1))
    edgecolors = np.repeat(gray.reshape(1, -1), len(edgedata), axis=0)
    nodecolors = np.repeat(gray.reshape(1, -1), len(nodedata), axis=0)
    #colors = lambda arr: cm.to_rgba(arr)[:,:3]
    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)

    if data_name == 'hematocrit':
        cm = matplotlib.cm.ScalarMappable(cmap=cm_hematocrit)
        cm.set_clim(0, 1)
        unmapped_range = (0., 1.)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'pressure':
        p0 = np.amin(nodedata)
        p1 = np.amax(nodedata)
        unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_redblue)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'shearforce':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = -4  #np.amin(edgedata)
        p1 = -1  #np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flow':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = np.floor(np.amin(edgedata))
        p1 = np.ceil(np.amax(edgedata))
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flags':
        unmapped_range = (0., 1.)
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        edgedata = np.bitwise_and(edgedata, krebsutils.ARTERY)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm, unmapped_range