def plot_command_jitter_cdf(command_stats, command, save_folder):
    """Compares the jitter of remote and local commands"""
    ax = get_ax()
    locations = ['lan', 'wan']
    for location in locations:
        # if "on" in command and "alexa" not in command and "google" not in command:
        command_jitter_values = sorted(command_stats[command]['android']
                                       [location]['input_jitter_sequence'])
        command_jitter_cdf = np.arange(
            1,
            len(command_jitter_values) + 1) / len(command_jitter_values)
        label = None
        if "lan" in location:
            label = "lan"
        elif "wan" in location:
            label = "wan"
        ax.plot(command_jitter_values, command_jitter_cdf, label=label)
    # command_response_jitter = sorted(command_stats[command]['output_jitter'])

    # command_response_cdf = np.arange(1, len(command_response_jitter) + 1) / len(command_response_jitter)

    ax.set_xlabel("jitter (ms)")
    ax.set_ylabel("CDF")
    ax.set_title(command + ' input traffic jitter')
    # ax.plot(command_jitter_values, command_jitter_cdf, label='command jitter')
    # ax.plot(command_response_jitter, command_response_cdf, label='response jitter')
    plt.legend(loc='best')
    save_file = Path(save_folder) / command
    plt.savefig(str(save_file) + "jittercdf.png")
    plt.show()
    def device_signature_plots(self,device_objs):
        import tools
        ax = tools.get_ax()
        ax.set_xlabel("Mean traffic volume (bytes)")
        ax.set_ylabel("Standard deviation traffic volume (bytes)")
        used_colors = []
        def get_unique_colour():
            c = np.random.rand(3,)
            if np.any(used_colors == c):
                c = get_unique_colour()
            else:
                used_colors.append(c)
                return c

        for device_obj in device_objs:
            # if device_obj.device_name == "Dropcam":
            if "Router" in device_obj.device_name:
                continue
            window_vectors = device_obj.create_traffic_volume_features("bidirectional")
            x = []
            y = []
            for k in window_vectors:
                x.append(window_vectors[k]['mean'])
                y.append(window_vectors[k]['std'])
            if len(x) > 1 and len(y) > 1:
                col = get_unique_colour()
                ax.scatter(x, y, label=device_obj.device_name, color=col)
        # plt.legend(loc='best')
        save_path = Path(self.save_folder) / str(self.file_name+'device_signature.png')
        plt.savefig(str(save_path))
        handles, labels = ax.get_legend_handles_labels()
        self.save_legend(handles, labels, "device_signature.png")
        # ax1.figure.savefig('device_signature_legend.jpeg ')
        plt.show()
def plot_command_location_jitter(command_stats, command, controller, plot_type,
                                 save_folder):
    """This function plots the jitter of commands based on their locations. Plots all instances or an average of all instances"""
    ax = get_ax()
    if plot_type == "pkt_no":
        # x axis is number of packets in flow
        lan_input_x = command_stats[command][controller]['lan'][
            "input_no_of_pkts"]
        lan_output_x = command_stats[command][controller]['lan'][
            "output_no_of_pkts"]
        wan_input_x = command_stats[command][controller]['wan'][
            "input_no_of_pkts"]
        wan_output_x = command_stats[command][controller]['wan'][
            "output_no_of_pkts"]
        ax.set_xlabel("Number of packets")
    elif plot_type == "flow_duration":
        # x axis is flow duration time
        lan_input_x = command_stats[command][controller]['lan'][
            "input_flow_jitter_durations"]
        lan_output_x = command_stats[command][controller]['lan'][
            "output_flow_jitter_durations"]
        wan_input_x = command_stats[command][controller]['wan'][
            "input_flow_jitter_durations"]
        wan_output_x = command_stats[command][controller]['wan'][
            "output_flow_jitter_durations"]
        ax.set_xlabel("Flow duration (s)")

    ax.scatter(lan_input_x,
               command_stats[command][controller]['lan']['input_jitter_avg'],
               label="lan input",
               color='b')
    ax.scatter(lan_output_x,
               command_stats[command][controller]['lan']['output_jitter_avg'],
               label="lan output",
               color='y')
    ax.scatter(wan_input_x,
               command_stats[command][controller]['wan']['input_jitter_avg'],
               label="wan input",
               color='r')
    ax.scatter(wan_output_x,
               command_stats[command][controller]['wan']['output_jitter_avg'],
               label="wan output",
               color='g')

    ax.set_ylabel("Average jitter of flow (ms)")
    plt.legend(loc='best')
    save_path = Path(save_folder) / command
    plt.savefig(
        str(save_path) + "androidlocation" + plot_type + "jitterduration.png")
    plt.show()
    print(command, controller, "location jitter plotted")
def compare_command_location_ttl(command_stats, command, save_folder):
    ax = get_ax()
    ax.scatter(command_stats[command]['android']['lan']['ttl_pkt_no'],
               command_stats[command]['android']['lan']['input_avg_ttl'],
               label='lan input flow')
    ax.scatter(command_stats[command]['android']['wan']['ttl_pkt_no'],
               command_stats[command]['android']['wan']['input_avg_ttl'],
               label='wan input flow')
    ax.set_ylabel('TTL')
    ax.set_xlabel('Number of packets')
    ax.set_title("Comparison of command location TTL values (input)")
    file = save_folder / command
    save_file = str(file) + "compare_command_location_ttl.png"
    plt.legend(loc='best')
    plt.savefig(save_file)
def compare_command_inputs(command_stats, save_folder):
    ax = get_ax()
    ax.set_ylabel("Flow size (bytes)")
    ax.set_xlabel("Flow duration (seconds)")
    ax.set_title("Command type flow characteristics")
    for command in command_stats:
        if len(command_stats[command]['android']['lan']) > 0 or len(
                command_stats[command]['android']['wan']) > 0:
            for location in command_stats[command]['android']:
                label = command + ' ' + location + " flow"
                ax.scatter(
                    command_stats[command]['android'][location]
                    ['input_duration'],
                    command_stats[command]['android'][location]['input_size'],
                    label=label)
    plt.legend(loc='best')
    plt.savefig(str(save_folder) + "commandinputflows.png")
    print('compare command inputs plotted')
def pkt_size_cdf(input_pkt_sizes, output_pkt_sizes, file_name):
    input_pkt_sizes_sorted = sorted(input_pkt_sizes)
    output_pkt_sizes_sorted = sorted(output_pkt_sizes)
    print(output_pkt_sizes_sorted)
    input_p = np.arange(1, len(input_pkt_sizes) + 1) / len(input_pkt_sizes)
    output_p = np.arange(1, len(output_pkt_sizes) + 1) / len(output_pkt_sizes)

    # plot the cdf
    ax = get_ax()
    ax.plot(input_pkt_sizes_sorted, input_p, label='input packets')
    ax.plot(output_pkt_sizes_sorted, output_p, label='output packets')

    ax.set_xlabel("Packet size (bytes)")
    ax.set_ylabel("CDF")
    plt.legend(loc='best')
    file_name = str(file_name) + "/pkt_size_cdf.png"
    plt.savefig(file_name)
    plt.show()
    def device_flow_direction_signature(self, device_objs):
        import tools
        ax = tools.get_ax()
        plot_name = 'input_flow_device_signature.png'
        ax.set_xlabel("Mean traffic volume (bytes)")
        ax.set_ylabel("Standard deviation traffic volume (bytes)")
        ax.set_title("Device flow direction rate signature")
        filter_out = ["PIX-STAR Photo-frame", "iHome"]
        color = iter(cm.rainbow(np.linspace(0, 1, len(device_objs) * 2)))
        used_colors = []

        def get_unique_colour():
            c = np.random.rand(3,)
            if np.any(used_colors == c):
                c = get_unique_colour()
            else:
                used_colors.append(c)
                return c

        for device_obj in device_objs:
            input_vectors = device_obj.create_traffic_volume_features("input")
            output_vectors = device_obj.create_traffic_volume_features("output")
            input_x, input_y = [],[]
            output_x, output_y = [],[]
            for t in input_vectors:
                input_x.append(input_vectors[t]['mean'])
                input_y.append(input_vectors[t]['std'])
            for time in output_vectors:
                output_x.append(output_vectors[time]['mean'])
                output_y.append(output_vectors[time]['std'])
            if len(input_x) > 0 and len(input_y) > 0:
                col = get_unique_colour()
                ax.scatter(input_x, input_y, label=device_obj.device_name + ' inputs', color=col)
            # if len(output_x) > 0 and len(output_y) > 0:
            #     col = get_unique_colour()
            #     ax.scatter(output_x, output_y, label=device_obj.device_name + ' ouputs', color=col)

        save_path = Path(self.save_folder) / str(self.file_name + plot_name)
        plt.savefig(str(save_path))
        handles, labels = ax.get_legend_handles_labels()
        self.save_legend(handles, labels, plot_name)
        plt.show()
def plot_command_pkt_size_cdf(command_stats, command, save_folder):
    ax = get_ax()
    locations = ['lan', 'wan']
    for location in locations:
        pkt_sizes = sorted(
            command_stats[command]['android'][location]["input_pkt_sizes"])
        pkt_sizes_cdf = np.arange(1, len(pkt_sizes) + 1) / len(pkt_sizes)
        label = None
        if "lan" in location:
            label = "lan"
        elif "wan" in location:
            label = "wan"
        ax.plot(pkt_sizes, pkt_sizes_cdf, label=label + ' input packets')

    ax.set_xlabel("Packet size (bytes)")
    ax.set_ylabel("CDF")
    ax.set_title(command + " packet size cdf")
    # ax.plot(command_jitter_values, command_jitter_cdf, label='command jitter')
    # ax.plot(command_response_jitter, command_response_cdf, label='response jitter')
    plt.legend(loc='best')
    save_file = Path(save_folder) / command
    plt.savefig(str(save_file) + "pktsizecdf.png")
    plt.show()