from django import template
from colour import Color
red = Color("red")
COLORS = list(red.range_to(Color("green"), 101))

register = template.Library()


@register.filter
def to_percent(value):
    return int(round(value * 100))


@register.filter
def to_percent_float(value):
    return round(value * 100, 3)


@register.filter
def to_color(value):
    return COLORS[int(round(value * 100))]
Пример #2
0
def test_stroke_props_in_ctor(using_opengl_renderer):
    m = OpenGLVMobject(stroke_color=C.ORANGE, stroke_width=10)
    assert m.stroke_color == Color(C.ORANGE)
    assert m.stroke_width == 10
Пример #3
0
    clean = (sys.argv[1] == 'clean')

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 20

plt.rc('font', size=BIGGER_SIZE)  # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE)  # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE)  # fontsize of the x and y labels

a_s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

qs = [0.6, 0.65, 0.707, 0.75, 0.8, 0.9]
ps = [0., 0.1, 0.2, 0.25, 0.3, 0.35, 0.4]

begin_color = Color("blue")
colors = list(begin_color.range_to(Color("green"), len(qs)))

for a in a_s:
    for p in ps:
        for q in qs:
            create.mass_function(q, p, a, clean=clean)

        plt.figure(1).set_size_inches((8, 8), forward=False)
        i = 0
        for q in qs:
            x_axis = dat.get_x_axis_mass_function(q, p, a)
            column = dat.get_column_mass_function(q, p, a)

            plt.plot(x_axis,
                     column,
Пример #4
0
os.putenv('SDL_FBDEV', '/dev/fb1')
pygame.init()

#initialize the sensor
sensor = Adafruit_AMG88xx()

points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
grid_x, grid_y = np.mgrid[0:7:32j, 0:7:32j]

#sensor is an 8x8 grid so lets do a square
height = 240
width = 240

#the list of colors we can choose from
blue = Color("indigo")
colors = list(blue.range_to(Color("red"), COLORDEPTH))

#create the array of colors
colors = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255))
          for c in colors]

displayPixelWidth = width / 30
displayPixelHeight = height / 30

lcd = pygame.display.set_mode((width, height))

lcd.fill((255, 0, 0))

pygame.display.update()
pygame.mouse.set_visible(False)
Пример #5
0
    def __init__(self, device, pin, first_led_id, led_count):
        self.sensor = Analog(device, pin)

        self.value = None
        self.prev_value = None

        self.first_led_id = first_led_id
        self.led_count = led_count

        # configure the colors
        self.black = Color("black")
        self.color_range = [
            Color(rgb=(0, 0.02, 0)),
            Color(rgb=(0, 0.10, 0)),
            Color(rgb=(0, 0.15, 0)),
            Color(rgb=(0, 0.20, 0)),
            Color(rgb=(0, 0.35, 0)),
            Color(rgb=(0, 0.40, 0.05)),
            Color(rgb=(0, 0.55, 0.10)),
            Color(rgb=(0, 0.65, 0.15)),
            Color(rgb=(0, 0.70, 0.25)),
            Color(rgb=(0, 0.75, 0.30)),
            Color(rgb=(0.10, 0.60, 0.20)),
            Color(rgb=(0.25, 0.50, 0.10)),
            Color(rgb=(0.40, 0.40, 0.05)),
            Color(rgb=(0.60, 0.30, 0)),
            Color(rgb=(0.70, 0.20, 0)),
            Color(rgb=(0.80, 0.10, 0)),
            Color(rgb=(0.90, 0.05, 0)),
        ]
Пример #6
0
class nyu_handholder:
    """ Pose class for nyu hand dataset
        coordinate system:
            ---> y
            |
            |x
        which is the same as row-major np arrays.
    """

    image_size = (480, 640)
    region_size = 120.  # empirical spacial cropping radius
    crop_size = 128  # input image size to models (may changed)
    # hmap_size = 32  # for detection models
    # anchor_num = 16  # for attention model
    crop_range = 480.  # +/- spacial capture range
    z_range = (100., 3060.)  # empirical valid depth range
    z_max = 9999.  # max distance set to 10m
    # camera info
    focal = (588.036865, 587.075073)
    centre = (320, 240)
    # focal = (587.075073, 588.036865)
    # centre = (240, 320)

    # joints description
    join_name = [
        'Palm', 'Wrist1', 'Wrist2', 'Thumb.R1', 'Thumb.R2', 'Thumb.T',
        'Index.R', 'Index.T', 'Mid.R', 'Mid.T', 'Ring.R', 'Ring.T', 'Pinky.R',
        'Pinky.T'
    ]

    join_num = 14
    join_type = ('C', 'W', 'T', 'I', 'M', 'R', 'P')
    join_color = (Color('black'), Color('cyan'), Color('magenta'),
                  Color('blue'), Color('lime'), Color('yellow'), Color('red'))
    join_keep = (0, 3, 6, 9, 12, 15, 18, 21, 24, 25, 27, 30, 31, 32)
    join_id = ((0), (1, 2), (3, 4, 5), (6, 7), (8, 9), (10, 11), (12, 13))
    bbox_color = Color('orange')

    def _prepare_data_full_path(self, target, precon_list, store_name,
                                path_pre_fn, mode, filepack, batchallot):
        precon_h5 = {}
        num_line = 0
        for precon in precon_list:
            precon_h5[precon] = filepack.push_h5(
                path_pre_fn(store_name[precon], mode))
            num_line = precon_h5[precon][precon].shape[0]
        store_size = batchallot.store_size
        print(
            'preparing data ({}): {:d} lines with store size {:d} ...'.format(
                path_pre_fn(store_name[target], mode), num_line, store_size))
        target_h5, batch_data = batchallot.create_fn[target](
            filepack, path_pre_fn(store_name[target], mode), num_line)
        timerbar = progressbar.ProgressBar(maxval=num_line,
                                           widgets=[
                                               progressbar.Percentage(), ' ',
                                               progressbar.Bar('=', '[', ']'),
                                               ' ',
                                               progressbar.ETA()
                                           ]).start()
        write_beg = 0
        li = 0
        while True:
            write_end = min(write_beg + store_size, num_line)
            proc_size = write_end - write_beg
            if 0 >= proc_size:
                break
            args = [range(proc_size)]
            for precon in precon_list:
                args.append(precon_h5[precon][precon][write_beg:write_end,
                                                      ...])
            datapro.puttensor_mt(args, self.store_prow[target], self, mode,
                                 batch_data)
            target_h5[write_beg:write_end, ...] = \
                batch_data[0:proc_size, ...]
            write_beg = write_end
            li += proc_size
            timerbar.update(li)
        timerbar.finish()

    def prepare_data_recur(self, target, store_name, filepack, batchallot):
        precon_list = self.store_precon[target]
        if not precon_list:
            return
        for precon in precon_list:
            self.prepare_data_recur(precon, store_name, filepack, batchallot)
        path_train = self.prepared_join(store_name[target], 'train')
        if not os.path.exists(path_train):
            self._prepare_data_full_path(target, precon_list, store_name,
                                         self.prepared_join, 'train', filepack,
                                         batchallot)
        path_test = self.prepared_join(store_name[target], 'test')
        if not os.path.exists(path_test):
            self._prepare_data_full_path(target, precon_list, store_name,
                                         self.prepared_join, 'test', filepack,
                                         batchallot)

    def _remove_out_frame_mat(self,
                              mat_name,
                              h5_name,
                              mode,
                              filepack,
                              shuffle=False,
                              num_line=None):
        mat_reader = scipy.io.loadmat(mat_name)
        mat_xyz = mat_reader['joint_xyz']
        # mat_xyz_shape = mat_xyz.shape
        # mat_xyz = mat_xyz.transpose().reshape(mat_xyz_shape)
        if num_line is None:
            num_line = mat_xyz.shape[1]
        shuffleid = np.arange(num_line)
        if shuffle:
            np.random.shuffle(shuffleid)
        print(mat_xyz.flags)
        print(mat_xyz.shape)
        poses_sel = mat_xyz[0, ...]
        print(poses_sel.shape)
        poses_sel = poses_sel[:num_line, ...]
        print(poses_sel.shape)
        poses_sel = poses_sel[:, self.join_keep, :]
        print(poses_sel.flags)
        print(poses_sel.shape)
        # poses_sel = mat_xyz[0, :num_line, self.join_keep, :]
        poses_sel[..., 1] *= -1
        # poses_sel[..., [0, 1]] = poses_sel[..., [1, 0]]
        poses_sel = poses_sel[:, ::-1, :]
        poses_sel = poses_sel.flatten(order='A')
        poses_sel = poses_sel.reshape(-1, self.join_num * 3)
        if shuffle:
            poses_sel = poses_sel[shuffleid, ...]
        print(poses_sel.flags)
        print(poses_sel.shape)
        # import matplotlib.pyplot as mpplot
        # p0 = poses_sel[0, ...].reshape(-1, 3)
        # pose2d, pose_z = dataops.raw_to_2dz(p0, self)
        # # mpplot.imshow(dep, cmap=mpplot.cm.bone_r)
        # mpplot.plot(pose2d[:, 0], pose2d[:, 1], 'o')
        # mpplot.show()
        batchallot = batch_index(self, num_line)
        store_size = batchallot.store_size
        h5file, batch_data = batchallot.create_index(filepack, h5_name,
                                                     num_line, None)
        pose_limit = np.array([
            [np.inf, np.inf, np.inf],
            [-np.inf, -np.inf, -np.inf],
        ])
        timerbar = progressbar.ProgressBar(maxval=num_line,
                                           widgets=[
                                               progressbar.Percentage(), ' ',
                                               progressbar.Bar('=', '[', ']'),
                                               ' ',
                                               progressbar.ETA()
                                           ]).start()
        read_beg = 0
        write_beg = 0
        li = 0
        while True:
            read_end = min(read_beg + store_size, num_line)
            proc_size = read_end - read_beg
            if 0 >= proc_size:
                break
            # index = (write_beg + 1) + np.arange(proc_size)
            index = shuffleid[read_beg:read_end] + 1
            poses = poses_sel[read_beg:read_end, :]
            args = [np.arange(proc_size), index, poses]
            batch_data['valid'] = np.full((store_size, ), False)
            datapro.puttensor_mt(args, datapro.prow_index, self, mode,
                                 batch_data)
            valid = batch_data['valid']
            valid_num = np.sum(valid)
            write_end = write_beg + valid_num
            if write_beg < write_end:
                h5file['index'][write_beg:write_end, ...] = \
                    batch_data['index'][valid, ...]
                poses = batch_data['poses'][valid, ...]
                h5file['poses'][write_beg:write_end, ...] = \
                    poses
                h5file['resce'][write_beg:write_end, ...] = \
                    batch_data['resce'][valid, ...]
                poses = poses.reshape(-1, 3)
                pose_limit[0, :] = np.minimum(pose_limit[0, :],
                                              np.min(poses, axis=0))
                pose_limit[1, :] = np.maximum(pose_limit[1, :],
                                              np.max(poses, axis=0))
            read_beg = read_end
            write_beg = write_end
            li += proc_size
            if 0 == (li % 10e2):
                timerbar.update(li)
        timerbar.finish()
        batchallot.resize(h5file, write_beg)
        # if shuffle:
        #     batchallot.shuffle(h5file)
        return write_beg, pose_limit

    # def _merge_annotation(self):
    #     annotation_train = self.prepared_join(self.annotation, 'train')
    #     annotation_test = self.prepared_join(self.annotation, 'test')
    #     annotation_merged = self.prepared_join(self.annotation + '_merged', 'train')
    #     with file_pack() as filepack:
    #         batchallot = batch_index(self, self.num_annotation)
    #         h5out, _ = batchallot.create_index(
    #             filepack, annotation_merged,
    #             self.num_annotation, None)
    #         batchallot.write(
    #             filepack.push_h5(annotation_train),
    #             h5out, 0, self.num_training)
    #         batchallot.write(
    #             filepack.push_h5(annotation_test),
    #             h5out, self.num_training, self.num_annotation)

    def remove_out_frame_annot(self):
        annot_origin_train = self.images_join('joint_data.mat', 'train')
        annot_origin_test = self.images_join('joint_data.mat', 'test')
        annotation_train = self.prepared_join(self.annotation, 'train')
        annotation_test = self.prepared_join(self.annotation, 'test')
        self.num_training = int(0)
        self.num_evaluate = int(0)
        pose_limit = np.array([
            [np.inf, np.inf, np.inf],
            [-np.inf, -np.inf, -np.inf],
        ])
        num_eval = self.args.num_eval
        with file_pack() as filepack:
            if num_eval is None:
                self.num_training, lim = self._remove_out_frame_mat(
                    annot_origin_train,
                    annotation_train,
                    'train',
                    filepack,
                    shuffle=True)
            else:
                self.num_training, lim = self._remove_out_frame_mat(
                    annot_origin_train,
                    annotation_train,
                    'train',
                    filepack,
                    shuffle=True,
                    num_line=(num_eval * 10))
            pose_limit[0, :] = np.minimum(pose_limit[0, :], lim[0, :])
            pose_limit[1, :] = np.maximum(pose_limit[1, :], lim[1, :])
        # use splited training data only
        with file_pack() as filepack:
            if num_eval is None:
                self.num_evaluate, lim = self._remove_out_frame_mat(
                    annot_origin_test, annotation_test, 'test', filepack)
            else:
                self.num_evaluate, lim = self._remove_out_frame_mat(
                    annot_origin_test,
                    annotation_test,
                    'test',
                    filepack,
                    num_line=num_eval)
            pose_limit[0, :] = np.minimum(pose_limit[0, :], lim[0, :])
            pose_limit[1, :] = np.maximum(pose_limit[1, :], lim[1, :])
        self.num_annotation = self.num_training + self.num_evaluate
        # self._merge_annotation()
        return pose_limit

    def init_data(self):
        update_log = False
        annotation_train = self.prepared_join(self.annotation, 'train')
        annotation_test = self.prepared_join(self.annotation, 'test')
        if ((not os.path.exists(annotation_train))
                or (not os.path.exists(annotation_test))):
            from timeit import default_timer as timer
            from datetime import timedelta
            time_s = timer()
            self.logger.info('cleaning data ...')
            pose_limit = self.remove_out_frame_annot()
            time_e = str(timedelta(seconds=timer() - time_s))
            self.logger.info(
                '{:d} training images, {:d} evaluate images after cleaning, time: {}'
                .format(self.num_training, self.num_evaluate, time_e))
            self.logger.info('pose limit: {} --> {}'.format(
                pose_limit[0, :], pose_limit[1, :]))
            update_log = True
            dataio.h5_to_txt(annotation_test, annotation_test + '.txt')
        else:
            with h5py.File(annotation_train, 'r') as h5file:
                self.num_training = h5file['index'].shape[0]
            with h5py.File(annotation_test, 'r') as h5file:
                self.num_evaluate = h5file['index'].shape[0]
            self.num_annotation = self.num_training + self.num_evaluate

        # split the data into 10 portions
        split_num = int(10)
        portion = int(np.ceil(float(self.num_training) / split_num))
        # the last portion is used for test (compare models)
        self.train_test_split = 0
        self.train_valid_split = int(portion * (split_num - 1))

        # # use splited training data only
        # self.train_test_split = int(portion * (split_num - 1))
        # self.train_valid_split = int(portion * (split_num - 2))
        # self.num_annotation = self.num_training
        # self.num_evaluate = self.num_annotation - self.train_test_split
        # self.num_training = self.train_test_split

        # # use splited training data only
        # annotation_test = self.annotation_test
        # if not os.path.exists(annotation_test):
        #     with h5py.File(annotation_train, 'r') as h5file:
        #         index = h5file['index'][self.train_test_split:, ...]
        #         poses = h5file['poses'][self.train_test_split:, ...]
        #         with h5py.File(annotation_test, 'w') as writer:
        #             dataio.write_h5(writer, index, poses)
        #         # with open(annotation_test + '_1.txt', 'w') as writer:
        #         #     dataio.write_txt(writer, index, poses)
        #     # dataio.h5_to_txt(annotation_test, annotation_test + '.txt')
        #     print('split out test annoations.')

        self.logger.info(
            'collected {:d} images: {:d} training, {:d} validation, {:d} evaluate'
            .format(self.num_annotation, self.train_valid_split,
                    self.num_training - self.train_valid_split,
                    self.num_evaluate))

        return update_log

    def images_join(self, filename='', mode='train'):
        return os.path.join(self.data_dir, mode, filename)
        # return os.path.join(self.data_dir, 'train', filename)

    def prepared_join(self, filename='', mode='train'):
        return os.path.join(self.out_dir, 'prepared', mode, filename)
        # return os.path.join(self.out_dir, 'prepared', filename)

    def __init__(self, args):
        self.args = args
        self.data_dir = args.data_dir
        self.out_dir = args.out_dir
        self.logger = args.logger
        self.crop_size = args.crop_size
        # self.anchor_num = args.anchor_num
        self.crop_range = args.crop_range
        # self.z_range[1] = self.crop_range * 2. + self.z_range[0]
        self.annotation = 'annotation'
        self.annotation_test = self.prepared_join('annotation', 'test')
        # self.annotation_test = self.prepared_join('annotation_test', 'test')
        prepared_train = self.prepared_join('', 'train')
        if not os.path.exists(prepared_train):
            os.makedirs(prepared_train)
        prepared_test = self.prepared_join(
            '',
            'test',
        )
        if not os.path.exists(prepared_test):
            os.makedirs(prepared_test)
        self.store_precon = {
            'index': [],
            'poses': [],
            'resce': [],
            'pose_c': ['poses', 'resce'],
            'pose_hit': ['poses', 'resce'],
            'pose_lab': ['poses', 'resce'],
            'crop2': ['index', 'resce'],
            'clean': ['index', 'resce'],
            'ortho3': ['index', 'resce'],
            'ov3edt2': ['ortho3', 'poses', 'resce'],
            'pcnt3': ['index', 'resce'],
            'tsdf3': ['pcnt3'],
            'vxhit': ['index', 'resce'],
            'vxudir': ['pcnt3', 'poses', 'resce'],
            'edt2': ['clean', 'poses', 'resce'],
            'hmap2': ['poses', 'resce'],
            'udir2': ['clean', 'poses', 'resce'],
            'edt2m': ['edt2', 'udir2'],
            'ov3dist2': ['vxudir'],
            'ov3edt2': ['ortho3', 'poses', 'resce'],
            'ov3edt2m': ['ov3edt2', 'ov3dist2'],
        }
        self.store_prow = {
            'pose_c': datapro.prow_pose_c,
            # 'pose_c1': datapro.prow_pose_c1,
            'pose_hit': datapro.prow_pose_hit,
            'pose_lab': datapro.prow_pose_lab,
            'crop2': datapro.prow_crop2,
            'clean': datapro.prow_clean,
            'ortho3': datapro.prow_ortho3,
            'pcnt3': datapro.prow_pcnt3,
            # 'truncd': datapro.prow_truncd,
            'tsdf3': datapro.prow_tsdf3,
            'vxhit': datapro.prow_vxhit,
            # 'vxoff': datapro.prow_vxoff,
            'vxudir': datapro.prow_vxudir,
            'hmap2': datapro.prow_hmap2,
            'udir2': datapro.prow_udir2,
            # 'vxedt': datapro.prow_vxedt,
            'edt2': datapro.prow_edt2,
            'ov3edt2': datapro.prow_ov3edt2,
            'edt2m': datapro.prow_edt2m,
            'ov3dist2': datapro.prow_ov3dist2,
            'ov3edt2m': datapro.prow_ov3edt2m,
        }
Пример #7
0
 def set_color(self, color):
     self.highlight(color)
     self.color = Color(color)
     return self
Пример #8
0
 def get_color(self):
     return Color(self.color)
Пример #9
0
 def clear(self):
     rgba = (*Color(self.background_color).get_rgb(),
             self.background_opacity)
     self.fbo.clear(*rgba)
Пример #10
0
def dimmed(c):
    return Color(hue=c.hue,
                 saturation=c.saturation,
                 luminance=c.luminance * 0.6)
Пример #11
0
 def parse_hex_color(cls, color):
     try:
         color = Color(color).get_rgb()
         return tuple(c * 255 for c in reversed(color))
     except Exception:
         return None
Пример #12
0
    def render(self,
               output,
               image_width,
               image_height,
               extent=30,
               line_width=0.2,
               show_vertices_labels=False,
               face_colors=("thistle", "steelblue", "lightcoral")):
        print("=" * 40)
        print(self.get_info())

        surface = cairo.SVGSurface(output, image_width, image_height)
        ctx = cairo.Context(surface)
        ctx.scale(image_height / extent, -image_height / extent)
        ctx.translate(extent / 2, -extent / 2)
        ctx.scale(1, -1)
        ctx.set_source_rgb(0, 0, 0)
        ctx.paint()
        ctx.set_line_width(line_width)
        ctx.set_line_cap(cairo.LINE_CAP_ROUND)
        ctx.set_line_join(cairo.LINE_JOIN_ROUND)

        bar = tqdm.tqdm(desc="processing polygons", total=self.num_faces)
        for (i, j), flist in self.face_indices.items():
            color1 = Color(face_colors[self.vertex_at_mirrors(i, j)])
            color2 = dimmed(color1)
            for face in flist:
                domain1, domain2 = face.get_alternative_domains()
                pts = [self.project(p) for p in face.coords]
                domain1 = [[self.project(p) for p in D] for D in domain1]
                domain2 = [[self.project(p) for p in D] for D in domain2]
                for D in domain1:
                    ctx.move_to(*D[0])
                    for p in D[1:]:
                        ctx.line_to(*p)
                    ctx.close_path()
                    ctx.set_source_rgb(*color1.rgb)
                    ctx.fill_preserve()
                    ctx.set_line_width(0.01)
                    ctx.stroke()

                for D in domain2:
                    ctx.move_to(*D[0])
                    for p in D[1:]:
                        ctx.line_to(*p)
                    ctx.close_path()
                    ctx.set_source_rgb(*color2.rgb)
                    ctx.fill_preserve()
                    ctx.set_line_width(0.01)
                    ctx.stroke()

                ctx.set_line_width(line_width)
                ctx.move_to(*pts[0])
                for p in pts[1:]:
                    ctx.line_to(*p)
                ctx.close_path()
                ctx.set_source_rgb(0.2, 0.2, 0.2)
                ctx.stroke()

                bar.update(1)

        bar.close()

        if show_vertices_labels:
            ctx.set_font_size(0.7)
            for i, p in enumerate(self.vertices_coords[:1000]):
                x, y = self.project(p)
                ctx.arc(x, y, 0.5, 0, 2 * np.pi)
                ctx.set_source_rgb(*Color("darkolivegreen").rgb)
                ctx.fill()
                ctx.set_source_rgb(*Color("papayawhip").rgb)
                ctx.select_font_face("Serif", cairo.FONT_SLANT_NORMAL,
                                     cairo.FONT_WEIGHT_BOLD)
                _, _, w, h, _, _ = ctx.text_extents(str(i))
                ctx.move_to(x - w / 2, y + h / 2)
                ctx.show_text(str(i))

        print("saving to svg...")
        surface.finish()
        size = os.path.getsize(output) >> 10
        print("{}KB svg file has been written to disk".format(size))
        print("=" * 40)
Пример #13
0
import cv2
import numpy as np
import math
import sys
from colour import Color, hex2rgb
import tkinter
from tkinter import filedialog
import time

from vpython import *

angles = [0]

fHold = [0]

red = Color("red")
blue = Color("blue")

colors = list(red.range_to(blue, 200))

rads = 100

holdF = 0
rads = 0

inc = 0

for colorNow in colors:
    colorNow = str(colorNow.hex_l)
    print('tttt', colorNow)
    colorNow = hex2rgb(colorNow)
Пример #14
0
def rawrgb2rgb(a, b, c):
    return Color(rgb=(a / 255, b / 255, c / 255))
def main():
    global annot
    global _ax
    global sc
    global _sc_l
    global _fig
    global names
    global _is_annotate
    global _is_cache
    global _stride_array
    global _title
    is_screen_available()

    # -- PARSING COMMAND LINE --
    parse_parameter()

    # -- OPEN LOG FILE --

    # we check if the last line is full (could not be if the program was stopped)
    _title = open(_fileLog_mem).readline()
    file_txt = open(_fileLog_mem, 'rt').readlines()
    len_first = len(file_txt[1])
    len_last = len(file_txt[-1])

    i = 0
    res = ""
    for word in _title.split():
        cr = ""
        if (i >= 7):
            cr = "\n"
            i = 0
        res += word + " " + cr
        i = i + 1
    _title = res

    log_file_array = 1
    if (len_first > len_last):
        log_file_array = np.loadtxt(file_txt[:-1],
                                    delimiter=',',
                                    dtype='float',
                                    comments='#')
    else:
        log_file_array = np.loadtxt(file_txt,
                                    delimiter=',',
                                    dtype='float',
                                    comments='#')

    # -- PARSING LOG FILE --

    # 1st step: recover the stride (the first line) and delete it from the array
    _stride_array = log_file_array[0].astype(int)[1:]
    nb_of_stride = len(_stride_array)

    print(" --- Stride (" + str(nb_of_stride) + "): " +
          str(_stride_array[:3]) +
          ((" ... " + str(_stride_array[-3:])) if nb_of_stride > 3 else ''))
    log_file_array = np.delete(log_file_array, 0, axis=0)
    # 2nd step: recover the data set size --> the first column
    x_value_dataset_size = log_file_array[0:log_file_array.shape[0],
                                          0].astype(int)
    # x_value_dataset_size = [i * 1000 for i in x_value_dataset_size]
    print(" --- Data set in bit (" + str(len(x_value_dataset_size)) + ")" +
          str(x_value_dataset_size[:3]) +
          ((" ... " + str(x_value_dataset_size[-3:])
            if len(x_value_dataset_size) > 3 else '')))

    ## -- PLOT THE RESULTS --
    _fig, _ax = plt.subplots()  # create figure and axes

    title_font = {
        'fontname': 'Arial',
        'size': '15',
        'color': 'black',
        'verticalalignment': 'bottom'
    }
    axis_font = {'fontname': 'Arial', 'size': '14', 'weight': 'bold'}
    contour_color = 'white'

    # Color gradient to generate a different color for each stride
    gradient = list(Color("blue").range_to(Color("red"), len(_stride_array)))
    COLOR = [C.hex_l for C in gradient]

    # for each stride we draw a curve
    for i in range(0, nb_of_stride):
        y_value = log_file_array[:, i +
                                 1]  # get the column for the current stride
        y_value[y_value ==
                0] = np.nan  # replace 0 by nan to not plot not existing values
        y_value[
            y_value >
            10000] = np.nan  # replace 0 by nan to not plot not existing values
        # if (i % 2 == 0):
        _ax.plot(x_value_dataset_size,
                 y_value,
                 label=str(_stride_array[i]),
                 linestyle='-',
                 linewidth=1,
                 color=COLOR[i])
        # _ax.plot(x_value_dataset_size, y_value, label=str(str(_stride_array[i]) + "bw"), linewidth=1, linestyle='-')

        # If the annotation option is requested
        # - We draw a point with the scatter function to be able to generate a 'hover' event
        # - We generate a box which will be used when the cursor is on the point
        if _is_annotate:
            _sc_l.extend(
                [_ax.scatter(x_value_dataset_size, y_value, color=COLOR[i])])
            # annot = _ax.annotate("", xy=(0, 0), xytext=(20, 20), textcoords="offset points",
            #                      bbox=dict(boxstyle="round", fc="w"),
            #                      arrowprops=dict(arrowstyle="->"))
            # annot.set_visible(False)

    ## -- DRAWING VERTICAL LINES FOR CACHE L1 L2 L3 --
    if _is_cache:
        print(' --- Cache size : ', end='')
        for i in range(len(_cache_size)):
            print(_cache_label[i] + "(" + str(_cache_size[i]) + ") ", end='')
            plt.axvline(x=_cache_size[i],
                        linestyle='-',
                        color='red',
                        linewidth=1)
            plt.text(_cache_size[i],
                     _cache_hauteur[i],
                     _cache_label[i],
                     rotation=90,
                     color='red',
                     weight='bold',
                     horizontalalignment='right')
        print('')

    plt.xlabel("Data set size", **axis_font)
    plt.ylabel("Bandwidth (GBs/s)", **axis_font)
    plt.title(
        "Bench_mem - " +
        str(os.path.basename(_fileLog_mem) + str("\n") + _title), **title_font)

    plt.xscale('log')
    # TODO param this
    _ax.legend(title="Size of stride (byte)", loc=0, ncol=2, borderaxespad=0.)
    plt.gcf().set_facecolor(contour_color)

    # x_v = [10, 100, 1000, 10000, 100000, 1000000, 100000000, 10000000000,100000000000]
    # x_l = ['10byte', '100byte', '1Kb', '10Kb', '100Kb', '1Mb', '10Mb', '10000000000', '1Gb', '10Gb']
    # plt.xticks(x_v,x_l)

    _ax = _fig.add_subplot(1, 1, 1)
    for spine in _ax.spines:
        _ax.spines[spine].set_color('#C6C9CA')

    plt.grid(True)

    # If annotate option was set: connect the event to its handler
    if _is_annotate:
        _fig.canvas.mpl_connect("motion_notify_event", hover)

    # No negatives values
    plt.ylim(ymin=0)
    x1, x2, y1, y2 = plt.axis()
    plt.axis((x1, x2, 0, 800))

    # Output: graphical or png file ?
    if _screen:
        logging.info(" Output = Screen")
        plt.show()
        exit(-4)
    else:
        logging.info(" Output = " + _path_image_file)
        plt.savefig(str(_path_image_file))
Пример #16
0
    data=tsne_d2v,
    columns=["x", "y"])  # запишем результаты TSNE преобразования в датафрейм
tsne_d2v_df["toxic_score"] = train[
    "topic"].values[:
                    nrows]  # добавим столбец, отвечающий за наличие хотя бы одного типа токсичности

# %%
tsne_d2v_df["toxic_score"]
# %%
tsne_d2v_df.head()

# %%
tsne_d2v_df.shape
# %%
from colour import Color
red = Color("red")
colors = list(red.range_to(Color("blue"), 31))
# %%
colors
# %%
output_notebook()

docs_top_tsne = tsne.fit_transform(tsne_d2v_df)
p = figure(tools="pan,wheel_zoom,reset,save",
           toolbar_location="above",
           title="Doc2Vec t-SNE for all articles")

colormap = np.array([
    "red", "red", "red", "red", "red", "red", "red", "red", "red", "red",
    "red", "red", "red", "red", "red", "red", "red", "blue", "red", "red",
    "red", "red", "red", "red", "red", "red", "red", "red", "red", "red",
Пример #17
0
def random_bright_color() -> Color:
    color = random_color()
    curr_rgb = color_to_rgb(color)
    new_rgb = interpolate(curr_rgb, np.ones(len(curr_rgb)), 0.5)
    return Color(rgb=new_rgb)
Пример #18
0
    def draw_random(self, thedata, args):
        index_h5 = self.store_handle['index']
        store_size = index_h5.shape[0]
        frame_id = np.random.choice(store_size)
        # frame_id = 0  # frame_id = img_id - 1
        img_id = index_h5[frame_id, ...]
        frame_h5 = self.store_handle['clean'][frame_id, ...]
        poses_h5 = self.store_handle['poses'][frame_id, ...].reshape(-1, 3)
        resce_h5 = self.store_handle['resce'][frame_id, ...]
        udir2_h5 = self.store_handle['udir2'][frame_id, ...]
        print(self.store_handle['udir2'])

        print('[{}] drawing image #{:d} ...'.format(self.name_desc, img_id))
        print(np.min(frame_h5), np.max(frame_h5))
        print(np.histogram(frame_h5, range=(1e-4, np.max(frame_h5))))
        print(np.min(poses_h5, axis=0), np.max(poses_h5, axis=0))
        print(resce_h5)
        resce3 = resce_h5[0:4]
        cube = iso_cube()
        cube.load(resce3)
        cube.show_dims()
        sizel = np.floor(resce3[0]).astype(int)
        from colour import Color
        colors = [Color('orange').rgb, Color('red').rgb, Color('lime').rgb]
        fig, _ = mpplot.subplots(nrows=2, ncols=3, figsize=(3 * 5, 2 * 5))
        pose_raw = poses_h5
        joint_id = self.join_num - 1
        olmap_h5 = udir2_h5[..., :self.join_num]
        uomap_h5 = udir2_h5[..., self.join_num:]
        olmap = olmap_h5[..., joint_id]
        uomap = uomap_h5[..., 3 * joint_id:3 * (joint_id + 1)]
        depth_crop = cv2resize(frame_h5, (sizel, sizel))

        ax = mpplot.subplot(2, 3, 2)
        ax.imshow(depth_crop, cmap=mpplot.cm.bone_r)
        pose3d = cube.transform_center_shrink(poses_h5)
        pose2d, _ = cube.project_ortho(pose3d, roll=0, sort=False)
        pose2d *= sizel
        args.data_draw.draw_pose2d(
            ax,
            thedata,
            pose2d,
        )

        ax = mpplot.subplot(2, 3, 5)
        draw_uomap(fig, ax, frame_h5, uomap)

        ax = mpplot.subplot(2, 3, 6)
        draw_olmap(fig, ax, frame_h5, olmap)

        ax = mpplot.subplot(2, 3, 3)
        pose_out = self.yanker_hmap(resce_h5, olmap_h5, uomap_h5, frame_h5,
                                    self.caminfo)
        err_re = np.sum(np.abs(pose_out - pose_raw))
        if 1e-2 < err_re:
            print('ERROR: reprojection error: {}'.format(err_re))
        else:
            print('reprojection looks good: {}'.format(err_re))
        ax.imshow(depth_crop, cmap=mpplot.cm.bone_r)
        pose3d = cube.transform_center_shrink(pose_out)
        pose2d, _ = cube.project_ortho(pose3d, roll=0, sort=False)
        pose2d *= sizel
        args.data_draw.draw_pose2d(
            ax,
            thedata,
            pose2d,
        )

        ax = mpplot.subplot(2, 3, 1)
        mpplot.gca().set_title('test image - {:d}'.format(img_id))
        img_name = args.data_io.index2imagename(img_id)
        img = args.data_io.read_image(os.path.join(self.image_dir, img_name))
        ax.imshow(img, cmap=mpplot.cm.bone_r)
        pose_raw = self.yanker(poses_h5, resce_h5, self.caminfo)
        args.data_draw.draw_pose2d(ax, thedata,
                                   args.data_ops.raw_to_2d(pose_raw, thedata))
        rects = cube.proj_rects_3(args.data_ops.raw_to_2d, self.caminfo)
        for ii, rect in enumerate(rects):
            rect.draw(ax, colors[ii])

        # hmap2 = self.data_module.ops.raw_to_heatmap2(
        #     pose_raw, cube, self.hmap_size, self.caminfo
        # )
        # offset, olmap, uomap = self.data_module.ops.raw_to_udir2(
        #     frame_h5, pose_raw, cube, self.hmap_size, self.caminfo
        # )

        fig.tight_layout()
        mpplot.savefig(
            os.path.join(self.predict_dir,
                         'draw_{}_{}.png'.format(self.name_desc, img_id)))
        if self.args.show_draw:
            mpplot.show()
        print('[{}] drawing image #{:d} - done.'.format(
            self.name_desc, img_id))
Пример #19
0
    track: np.mean(data[data['Track'] == track]['Time'])
    for track in tracksFltr
}, {
    track: np.max(data[data['Track'] == track]['Time'])
    for track in tracksFltr
})

###############################################################################
# Traces Plot
###############################################################################
# Style calculations ----------------------------------------------------------
colorSwatch = mk.generateColorSwatch('#233090',
                                     len(fshdRunsIDs),
                                     alphaOffset=(.1, .8),
                                     lumaOffset=(.25, 1))
highlight = list(Color('#EE006E').get_rgb())
highlight.append(.9)
# Timing ----------------------------------------------------------------------
runsCTimesC = mk.convertTimeFromSec(runsCTimesC, timeTarget='Minutes')
runsCTimesC['Total'] = [
    time.strftime("%H:%M:%S", time.gmtime(i)) for i in runsCTimes['Time']
]
# Calculate fastest run -------------------------------------------------------
endTimes = runsCTimesC[runsCTimesC['Track'] == tracksFltr[-1]]
fastest = min(endTimes['Time'])
fid = endTimes[endTimes['Time'] == fastest]['ID'].values[0]
fPos = fshdRunsIDs.index(fid)
colorSwatch[fPos] = tuple(highlight)
# Convert to human-readable times ---------------------------------------------
fig = px.line(runsCTimesC,
              x="Track",
Пример #20
0
import os
import numpy as np
from colour import Color
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt

from vgtk.pc import save_ply

red = Color('red')
blue = Color('blue')
white = Color('black')
crange = [np.array(c.rgb) for c in list(red.range_to(blue, 1000))]
crange = np.array(crange)
wrrange = [np.array(c.rgb) for c in list(white.range_to(red, 1000))]
wrrange = np.array(wrrange)


def clip_to_crange(x, spectrum, xmin, xmax):
    x = x.squeeze()
    cscale = len(spectrum)

    xmin = x.min() if xmin is None else xmin
    xmax = x.max() if xmax is None else xmax

    x = (x - xmin) * cscale / (xmax - xmin)
    x = x.astype(np.int32)
    x = np.clip(x, 0, cscale - 1)
    return spectrum[x]


def visualize_one_spheres_np(points,
Пример #21
0
def get_gradient_color(startColor: str, endColor: str, colorNum: int):
    from colour import Color
    startColorObj = Color(startColor)
    endColorObj = Color(endColor)

    return list(startColorObj.range_to(endColorObj, colorNum))
Пример #22
0
filepath  = './trajectory_real_physionet_subject72.pkl'
embedding = joblib.load(filepath) 
u72,l72 = embedding

fig = plt.figure(figsize=(15,15))

ibeg = 65
iend = 135

nplot = 1
for ui,si in zip([u1,u8,u47,u72], [1,8,47,72]):
    ax = fig.add_subplot(2,2,nplot)
    ax.scatter(ui[ibeg,1], ui[ibeg,2], facecolors='none', edgecolors='g', s=200)
    ax.scatter(ui[iend,1], ui[iend,2], facecolors='none', edgecolors='r', s=200)
    green = Color("green")
    colors = list(green.range_to(Color("red"),len(range(ibeg, iend+1))))     
    for i in range(ibeg, iend+1):
        ax.scatter(ui[i,1], ui[i,2], c=colors[i-ibeg].get_rgb(), edgecolors='none', s=120)
    plt.title('Subject ' + str(si), fontsize=22)
    nplot = nplot+1   

#%%







Пример #23
0
class Keypad(object):
    """A keypad; this is pretty specific to my board"""
    REQUIRED_KEYS = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'input', 'ok'])

    ACTIVE_COLOR = Color("green")
    INACTIVE_COLOR = Color("green", saturation=0.5)

    DISABLED_COLOR = Color("orange")
    DISABLED_ACTIVE_COLOR = Color("red")

    BLINK_COLOR = Color("blue")
    BLINK_INTERVAL_SEC = 0.5

    def __init__(self, buttons, displays):
        # did we get the buttons we require?
        provided = set(buttons.keys())
        if provided != self.REQUIRED_KEYS:
            raise RuntimeError(
                "Keypad requires a dictionary of buttons with exactly keys %s, but %s was provided"
                % (self.REQUIRED_KEYS, provided))

        # save ref to displays
        self.displays = displays

        # save and initialize callbacks on key press
        self.buttons = buttons
        for label in self.buttons:
            self.buttons[label].callback = self.callback_for(label)

        # internal state
        self.next_blink = 0
        self.input_mode = False
        self.blink_on_mode = False

        # set colors on the buttons
        self.set_button_colors()

        # what should we be displaying right now?
        self.last_display = None
        self.display = ['H', 'E', 'H']
        self.value = 0

    def callback_for(self, label):
        return lambda btn: self.key_pressed(label, btn)

    def key_pressed(self, label, btn):
        # we only care about key press, not key release
        if not btn.active():
            return

        if label == 'input':
            if not self.input_mode:
                self.input_mode = True

        elif label == 'ok':
            if self.input_mode:
                self.input_mode = False
                self.value = "".join([str(s) for s in self.display])

        else:
            if self.input_mode:
                self.display = self.display[1:] + [label]

    def set_button_colors(self):
        """sets the colors for all the keys based on the current mode"""
        # in input mode, the number keys and the ok key are active
        if self.input_mode:
            # numbers are active (aka green)
            number_active_color = self.ACTIVE_COLOR
            number_inactive_color = self.INACTIVE_COLOR

            # input button is inactive
            self.buttons['input'].ACTIVE_COLOR = self.DISABLED_ACTIVE_COLOR
            self.buttons['input'].INACTIVE_COLOR = self.DISABLED_COLOR

            # the ok button is active and blinking
            self.buttons['ok'].ACTIVE_COLOR = self.ACTIVE_COLOR
            if self.blink_on_mode:
                self.buttons['ok'].INACTIVE_COLOR = self.BLINK_COLOR
            else:
                self.buttons['ok'].INACTIVE_COLOR = self.INACTIVE_COLOR

        # otherwise, only the input key is active (and is blinking)
        else:
            # numbers are inactive
            number_active_color = self.DISABLED_ACTIVE_COLOR
            number_inactive_color = self.DISABLED_COLOR

            # ok button is inactive too
            self.buttons['ok'].ACTIVE_COLOR = self.DISABLED_ACTIVE_COLOR
            self.buttons['ok'].INACTIVE_COLOR = self.DISABLED_COLOR

            # the input button is active and blinking
            self.buttons['input'].ACTIVE_COLOR = self.ACTIVE_COLOR
            if self.blink_on_mode:
                self.buttons['input'].INACTIVE_COLOR = self.BLINK_COLOR
            else:
                self.buttons['input'].INACTIVE_COLOR = self.INACTIVE_COLOR

        # now we need to iterate through the number keys and set them
        for key in xrange(0, 10):
            btn = self.buttons[key]
            btn.ACTIVE_COLOR = number_active_color
            btn.INACTIVE_COLOR = number_inactive_color

    def read(self):
        # handle blinking
        now = time.time()
        if now > self.next_blink:
            self.next_blink = now + self.BLINK_INTERVAL_SEC
            self.blink_on_mode = not self.blink_on_mode

        # set the button colors based on the current mode
        self.set_button_colors()

        # make sure the display is correct
        self.set_display()

        # now lets read the inputs; that will set colors if necessary
        for btn in self.buttons.values():
            btn.read()

    def set_display(self):
        for idx, char in enumerate(self.display):
            d = self.displays[idx]
            d.display(char)
Пример #24
0
    def getColor(self):
        # Change increment size here (a bit buggy :/)
        inc = 1
        '''formula = (self.rowAmt * .025) / inc
        if formula > 1:
            self.color.saturation = formula
        else:
            self.color = Color("red")'''

        if self.rowAmt < inc:
            self.color.saturation = 0.027
        elif self.rowAmt < (2 * inc):
            self.color.saturation = 0.054
        elif self.rowAmt < (3 * inc):
            self.color.saturation = 0.081
        elif self.rowAmt < (4 * inc):
            self.color.saturation = 0.108
        elif self.rowAmt < (5 * inc):
            self.color.saturation = 0.135
        elif self.rowAmt < (6 * inc):
            self.color.saturation = 0.162
        elif self.rowAmt < (7 * inc):
            self.color.saturation = 0.189
        elif self.rowAmt < (8 * inc):
            self.color.saturation = 0.216
        elif self.rowAmt < (9 * inc):
            self.color.saturation = 0.143
        elif self.rowAmt < (10 * inc):
            self.color.saturation = 0.27
        elif self.rowAmt < (11 * inc):
            self.color.saturation = 0.297
        elif self.rowAmt < (12 * inc):
            self.color.saturation = 0.324
        elif self.rowAmt < (13 * inc):
            self.color.saturation = 0.351
        elif self.rowAmt < (14 * inc):
            self.color.saturation = 0.378
        elif self.rowAmt < (15 * inc):
            self.color.saturation = 0.405
        elif self.rowAmt < (16 * inc):
            self.color.saturation = 0.432
        elif self.rowAmt < (17 * inc):
            self.color.saturation = 0.459
        elif self.rowAmt < (18 * inc):
            self.color.saturation = 0.486
        elif self.rowAmt < (19 * inc):
            self.color.saturation = 0.513
        elif self.rowAmt < (20 * inc):
            self.color.saturation = 0.540
        elif self.rowAmt < (21 * inc):
            self.color.saturation = 0.567
        elif self.rowAmt < (22 * inc):
            self.color.saturation = 0.594
        elif self.rowAmt < (23 * inc):
            self.color.saturation = 0.621
        elif self.rowAmt < (24 * inc):
            self.color.saturation = 0.648
        elif self.rowAmt < (25 * inc):
            self.color.saturation = 0.675
        elif self.rowAmt < (26 * inc):
            self.color.saturation = 0.702
        elif self.rowAmt < (27 * inc):
            self.color.saturation = 0.729
        else:
            self.color = Color("black")

        return self.color.hex_l
Пример #25
0
def test_set_stroke(using_opengl_renderer):
    m = OpenGLVMobject()
    m.set_stroke(color=C.ORANGE, width=2, opacity=0.8)
    assert m.stroke_width == 2
    assert m.stroke_opacity == 0.8
    assert m.stroke_color == Color(C.ORANGE)
Пример #26
0
 def __init__(self, pos, model, unique_id):
     self.pos = pos
     self.rowAmt = 0
     self.color = Color("blue")
# high range of the sensor (this will be red on the screen)
MAXTEMP = 32.0
COLORDEPTH = 1024
SENSOR = adafruit_amg88xx.AMG88XX(I2C_BUS)

# pylint: disable=invalid-slice-index
POINTS = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
GRID_X, GRID_Y = np.mgrid[0:7:32j, 0:7:32j]
# pylint: enable=invalid-slice-index

# sensor is an 8x8 grid so lets do a square
HEIGHT = 240
WIDTH = 240

# the list of colors we can choose from
BLUE = Color("indigo")
COLORS = list(BLUE.range_to(Color("red"), COLORDEPTH))

# create the array of colors
COLORS = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255))
          for c in COLORS]


def map_value(x_value, in_min, in_max, out_min, out_max):
    """Maps value of the temperature to color"""
    return (x_value - in_min) * (out_max - out_min) / (in_max -
                                                       in_min) + out_min


# let the sensor initialize
time.sleep(0.1)
Пример #28
0
def network_graph(yearRange, AccountToSearch):

    edge1 = pd.read_csv('Edgelist_sample.csv')
    node1 = pd.read_csv('nodes_sample.csv')
    # filter the record by datetime, to enable interactive control through the input box
    #edge1['Datetime'] = ""  # add empty Datetime column to edge1 dataframe
    accountSet=set()  # contain unique account
    edge1['Datetime'] = pd.to_datetime(edge1['Date'], infer_datetime_format=True)
    for index in range(0, len(edge1)):
        #edge1['Datetime'][index] = datetime.strptime(edge1['Date'][index], '%d/%m/%Y')
        if edge1['Datetime'][index].year < yearRange[0] or edge1['Datetime'][index].year > yearRange[1]:
            edge1.drop(axis=0, index=index, inplace=True)
            continue
        accountSet.add(edge1['Source'][index])
        accountSet.add(edge1['Destination'][index])

    # to define the centric point of the networkx layout
    shells=[]
    shell1=[]
    shell1.append(AccountToSearch)
    shells.append(shell1)
    shell2=[]
    for ele in accountSet:
        if ele!=AccountToSearch:
            shell2.append(ele)
    shells.append(shell2)
    print(shells)
    G = nx.from_pandas_edgelist(edge1, 'Source', 'Destination', ['Source', 'Destination', 'Edge_ID', 'Date'], create_using=nx.MultiDiGraph())
    nx.set_node_attributes(G, node1.set_index('ID')['Nome'].to_dict(), 'Nome')
    nx.set_node_attributes(G, node1.set_index('ID')['Type'].to_dict(), 'Type')
    # pos = nx.layout.spring_layout(G)
    # pos = nx.layout.circular_layout(G)
    # nx.layout.shell_layout only works for more than 3 nodes
    if len(shell2)>1:
        pos = nx.drawing.layout.shell_layout(G, shells)
    else:
        pos = nx.drawing.layout.spring_layout(G)
    for node in G.nodes:
        G.nodes[node]['pos'] = list(pos[node])


    if len(shell2)==0:
        traceRecode = []  # contains edge_trace, node_trace, middle_node_trace

        node_trace = go.Scatter(x=tuple([1]), y=tuple([1]), text=tuple([str(AccountToSearch)]), textposition="bottom center",
                                mode='markers+text',
                                marker={'size': 50, 'color': 'LightSkyBlue'})
        traceRecode.append(node_trace)

        node_trace1 = go.Scatter(x=tuple([1]), y=tuple([1]),
                                mode='markers',
                                marker={'size': 50, 'color': 'LightSkyBlue'},
                                opacity=0)
        traceRecode.append(node_trace1)

        figure = {
            "data": traceRecode,
            "layout": go.Layout(title='Visualizzazione Interattiva di Cooccorrenza', showlegend=False,
                                margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
                                xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                                yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                                height=600
                                )}
        return figure


    traceRecode = []  # contains edge_trace, node_trace, middle_node_trace
    ############################################################################################################################################################
    colors = list(Color('lightcoral').range_to(Color('darkred'), len(G.edges())))
    colors = ['rgb' + str(x.rgb) for x in colors]

    index = 0
    for edge in G.edges:
        x0, y0 = G.nodes[edge[0]]['pos']
        x1, y1 = G.nodes[edge[1]]['pos']
        weight = float(G.edges[edge]['Edge_ID']) / max(edge1['Edge_ID']) * 10
        trace = go.Scatter(x=tuple([x0, x1, None]), y=tuple([y0, y1, None]),
                           mode='lines',
                           line={'width': weight},
                           marker=dict(color=colors[index]),
                           line_shape='spline',
                           opacity=1)
        traceRecode.append(trace)
        index = index + 1
    ###############################################################################################################################################################
    node_trace = go.Scatter(x=[], y=[], hovertext=[], text=[], mode='markers+text', textposition="bottom center",
                            hoverinfo="text", marker={'size': 50, 'color': 'LightSkyBlue'})

    index = 0
    for node in G.nodes():
        x, y = G.nodes[node]['pos']
        hovertext = "Nome: " + str(G.nodes[node]['Nome']) + "<br>" + "AccountType: " + str(
            G.nodes[node]['Type'])
        text = node1['ID'][index]
        node_trace['x'] += tuple([x])
        node_trace['y'] += tuple([y])
        node_trace['hovertext'] += tuple([hovertext])
        node_trace['text'] += tuple([text])
        index = index + 1

    traceRecode.append(node_trace)
    ################################################################################################################################################################
    middle_hover_trace = go.Scatter(x=[], y=[], hovertext=[], mode='markers', hoverinfo="text",
                                    marker={'size': 20, 'color': 'LightSkyBlue'},
                                    opacity=0)

    index = 0
    for edge in G.edges:
        x0, y0 = G.nodes[edge[0]]['pos']
        x1, y1 = G.nodes[edge[1]]['pos']
        hovertext = "From: " + str(G.edges[edge]['Source']) + "<br>" + "To: " + str(
            G.edges[edge]['Destination']) + "<br>" + "Edge_ID: " + str(
            G.edges[edge]['Edge_ID']) + "<br>" + "Data Documento: " + str(G.edges[edge]['Date'])
        middle_hover_trace['x'] += tuple([(x0 + x1) / 2])
        middle_hover_trace['y'] += tuple([(y0 + y1) / 2])
        middle_hover_trace['hovertext'] += tuple([hovertext])
        index = index + 1

    traceRecode.append(middle_hover_trace)
    #################################################################################################################################################################
    figure = {
        "data": traceRecode,
        "layout": go.Layout(title='Visualizzazione Interattiva di Cooccorrenze', showlegend=False, hovermode='closest',
                            margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
                            xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                            yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                            height=600,
                            clickmode='event+select',
                            # annotations=[
                            #     dict(
                            #         ax=(G.nodes[edge[0]]['pos'][0] + G.nodes[edge[1]]['pos'][0]) / 2,
                            #         ay=(G.nodes[edge[0]]['pos'][1] + G.nodes[edge[1]]['pos'][1]) / 2, axref='x', ayref='y',
                            #         x=(G.nodes[edge[1]]['pos'][0] * 3 + G.nodes[edge[0]]['pos'][0]) / 4,
                            #         y=(G.nodes[edge[1]]['pos'][1] * 3 + G.nodes[edge[0]]['pos'][1]) / 4, xref='x', yref='y',
                            #         showarrow=True,
                            #         arrowhead=3,
                            #         arrowsize=4,
                            #         arrowwidth=1,
                            #         opacity=1
                            #     ) for edge in G.edges]
                            )}
    return figure
Пример #29
0
def rgb_to_color(rgb: Iterable[float]) -> Color:
    return Color(rgb=rgb)
Пример #30
0
    print('Loaded idf tables with max idf {}'.format(max_idf))
    return ret, max_idf

#################
idf_pickle_path = "C:\\Users\\dvpap\\Downloads\\bioasq_all\\idf.pkl"
w2v_bin_path    = "C:\\Users\\dvpap\\Downloads\\bioasq_all\\pubmed2018_w2v_30D.bin"
# idf_pickle_path = "/home/dpappas/bioasq_all/idf.pkl"
# w2v_bin_path    = "/home/dpappas/bioasq_all/pubmed2018_w2v_30D.bin"
#################
idf, max_idf    = load_idfs(idf_pickle_path)
print('loading w2v')
wv              = KeyedVectors.load_word2vec_format(w2v_bin_path, binary=True)
wv              = dict([(word, wv[word]) for word in wv.vocab.keys()])
#################

white           = Color("white")
yellow_colors   = list(white.range_to(Color("yellow"), 101))
yellow_colors   = [c.get_hex_l() for c in yellow_colors]
blue_colors     = list(white.range_to(Color("blue"), 101))
blue_colors     = [c.get_hex_l() for c in blue_colors]
green_colors    = list(white.range_to(Color("green"), 101))
green_colors    = [c.get_hex_l() for c in green_colors]

app = Flask(__name__)

def create_one_hot_and_sim(tokens1, tokens2):
    '''
    :param tokens1:
    :param tokens2:
    :return:
    exxample call : create_one_hot_and_sim('c d e'.split(), 'a b c'.split())