text:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from numpy import array

NMAX = 1000000

PROCS = 4
STP = 5.0e-5

NEARL = 0.01
FARL = 0.1
ZONEWIDTH = 0.1

REJECT = 0.1*STP
ATTRACT = 0.9*STP

SPLIT_LIMIT = NEARL*1.2
FLIP_LIMIT = NEARL*0.5
FLIP_CURVATURE = 0.95

OBJ = './data/cyl.obj'
SCALE = 6*NEARL

SEEDTYPE = 'surface'
SEEDRATIO = None # None means all vertices, otherwise use a number ∈ (0,1)
SEED_FREQ = 1

DIMINISH = 0.995
SMOOTH = 0.1

SCREEN_SIZE = 1000
INITIAL_SCALE = 1.2
AUTOROTATE = True
SAVE_IMG = None
SPEEDUP = 6

def main():

  from differentialMesh3d import DifferentialMesh3d
  from modules.ioOBJ import load_move_scale as load_obj
  from modules.random import random_unit_vec
  from modules.geometry import get_show_geometry
  from modules.utils import get_seed_selector
  from modules.utils import print_stats
  from modules.utils import get_exporter

  from fn import Fn
  fn = Fn(prefix='./res/', postfix='.obj')

  DM = DifferentialMesh3d(
      nmax=NMAX,
      zonewidth=ZONEWIDTH,
      nearl=NEARL,
      farl=FARL,
      procs=PROCS
      )

  data = load_obj(
      OBJ,
      s=SCALE,
      mx=[0.5] * 3
      )
  info = DM.initiate_faces(list(data['vertices']), list(data['faces']))

  if info['min_edge'] < NEARL:
    print('all edges are too short. try scaling up initial size.')
    return

  seed_selector = get_seed_selector(DM, SEEDTYPE, SEEDRATIO)

  noise = random_unit_vec(DM.get_vnum(), STP*100.)
  DM.position_noise(noise, scale_intensity=-1)

  DM.optimize_edges(SPLIT_LIMIT, FLIP_LIMIT, FLIP_CURVATURE)

  for he in range(DM.get_henum()):
    DM.set_edge_intensity(he, 1.0)

  show_geometry = get_show_geometry(DM, NMAX)

  def geometry_generator():
    seeds = seed_selector()
    i = 0
    k = 0
    box = array((-1, -1, -1, 1, 1), 'float')
    while True:
      i += 1
      for _ in range(SPEEDUP):
        k += 1
        DM.optimize_position(
            REJECT,
            ATTRACT,
            DIMINISH,
            SMOOTH,
            scale_intensity=1
            )

        DM.optimize_edges(SPLIT_LIMIT, FLIP_LIMIT, FLIP_CURVATURE)

        if len(seeds) > 0:
          DM.set_vertices_intensity(seeds, 1.0)

        if k%SEED_FREQ == 0:
          seeds = seed_selector()

      print_stats(k, DM, meta='alive v: {:d}'.format(len(seeds)))

      box = show_geometry()

      yield box

  from view3d import View3d
  v3d = View3d(
      size=SCREEN_SIZE,
      initial_scale=INITIAL_SCALE,
      autorotate=AUTOROTATE,
      save_img=SAVE_IMG
      )
  v3d.start(geometry_generator)

  export = get_exporter(DM, fn, NMAX)
  export()

if __name__ == '__main__':
  main()

ext: py

reason: from numpy


text:
import click
import pandas as pd
import numpy as np
import os
import cv2
import skvideo.io
import sys
import time
import tempfile
import tensorflow as tf
import xlsxwriter
import json

from PIL import Image
from luminoth.tools.checkpoint import get_checkpoint_config
from luminoth.utils.config import get_config, override_config_params
from luminoth.utils.predicting import PredictorNetwork
from luminoth.utils.vis import vis_objects

IMAGE_FORMATS = ["jpg", "jpeg", "png", "tif"]
VIDEO_FORMATS = ["mov", "mp4", "avi"]  # TODO: check if more formats work
LUMI_CSV_COLUMNS = ["image_id", "xmin", "xmax", "ymin", "ymax", "label", "prob"]

def get_file_type(filename):
    extension = filename.split(".")[-1].lower()
    if extension in IMAGE_FORMATS:
        return "image"
    elif extension in VIDEO_FORMATS:
        return "video"

def resolve_files(path_or_dir):
    """Returns the file paths for `path_or_dir`.

    Args:
        path_or_dir: String or list of strings for the paths or directories to
            run predictions in. For directories, will return all the files
            within.

    Returns:
        List of strings with the full path for each file.
    """
    if not isinstance(path_or_dir, tuple):
        path_or_dir = (path_or_dir,)

    paths = []
    for entry in path_or_dir:
        if tf.gfile.IsDirectory(entry):
            paths.extend(
                [
                    os.path.join(entry, f)
                    for f in tf.gfile.ListDirectory(entry)
                    if get_file_type(f) in ("image", "video")
                ]
            )
        elif get_file_type(entry) in ("image", "video"):
            if not tf.gfile.Exists(entry):
                click.echo("Input {} not found, skipping.".format(entry))
                continue
            paths.append(entry)

    return paths

def filter_classes(objects, only_classes=None, ignore_classes=None):
    if ignore_classes:
        objects = [o for o in objects if o["label"] not in ignore_classes]

    if only_classes:
        objects = [o for o in objects if o["label"] in only_classes]

    return objects

def filter_probabilities(objects, min_prob=None, max_prob=None):
    if min_prob:
        objects = [o for o in objects if o["prob"] > min_prob]

    if max_prob:
        objects = [o for o in objects if o["prob"] <= max_prob]

    return objects

def bbs_pixel_apart(obj, objects, pixel_distance):
    repeated_indices = []
    for index, each_obj in enumerate(objects):
        set_index_flags = 0
        unique_differences = np.unique(np.fabs(np.subtract(each_obj, obj))).tolist()
        for i in unique_differences:
            if i <= pixel_distance:
                set_index_flags += 1
        if set_index_flags == len(unique_differences):
            repeated_indices.append(index)
    return repeated_indices

def filter_close_bbs(predictions, pixel_distance):
    # Save a prediction by suppressing the class with
    # lowest probability for the same bounding box
    objects = [prediction["bbox"] for prediction in predictions]
    labels = [prediction["label"] for prediction in predictions]
    probs = [prediction["prob"] for prediction in predictions]

    predictions = [None] * len(objects)
    assert len(objects) == len(labels) == len(probs)
    count = 0
    for obj, label, prob in zip(objects, labels, probs):
        repeated_indices = bbs_pixel_apart(obj, objects, pixel_distance)
        if len(repeated_indices) > 0:
            repeated_probs = [probs[i] for i in repeated_indices]
            repeated_probs.append(prob)
            repeated_indices.append(count)
            max_prob = max(repeated_probs)
            assert len(repeated_probs) == len(repeated_indices)
            prob_index = [
                index
                for index, prob in zip(repeated_indices, repeated_probs)
                if prob == max_prob
            ][0]
            d = {
                "bbox": objects[prob_index],
                "label": labels[prob_index],
                "prob": round(max_prob, 4),
            }
            predictions[prob_index] = d
        else:
            if objects.count(obj) == 1:
                d = {"bbox": obj, "label": label, "prob": round(prob, 4)}
                predictions[count] = d
            elif objects.count(obj) > 1:
                prob_repeated_objs = [
                    [i, probs[i]] for i, value in enumerate(objects) if value == obj
                ]
                repeated_indices = [i for (i, _) in prob_repeated_objs]
                repeated_probs = [j for (_, j) in prob_repeated_objs]
                max_prob = max(repeated_probs)
                prob_index = [
                    index
                    for index, prob in zip(repeated_indices, repeated_probs)
                    if prob == max_prob
                ][0]
                d = {
                    "bbox": obj,
                    "label": labels[prob_index],
                    "prob": round(max_prob, 4),
                }
                predictions[prob_index] = d
        count += 1
    predictions = list(filter(None, predictions))
    predictions = sorted(predictions, key=lambda x: x["prob"], reverse=True)

    return predictions

def rename_labels(predictions, new_labels):
    objects = [prediction["bbox"] for prediction in predictions]
    labels = [prediction["label"] for prediction in predictions]
    new_labels = [new_labels[label] for label in labels]
    probs = [prediction["prob"] for prediction in predictions]
    predictions = [None] * len(objects)
    predictions = sorted(
        [
            {
                "bbox": obj,
                "label": label,
                "prob": round(prob, 4),
            }
            for obj, label, prob in zip(objects, new_labels, probs)
        ],
        key=lambda x: x["prob"],
        reverse=True,
    )
    return predictions

def run_image_through_network(
    network,
    image,
    only_classes=None,
    ignore_classes=None,
    save_path=None,
    min_prob=None,
    max_prob=None,
    pixel_distance=0,
    new_labels=None,
):
    objects = network.predict_image(image)

    # Filter the results according to the user input.
    objects = filter_classes(
        objects, only_classes=only_classes, ignore_classes=ignore_classes
    )

    # Filter the results according to the user input.
    objects = filter_probabilities(objects, min_prob=min_prob, max_prob=max_prob)

    objects = filter_close_bbs(objects, pixel_distance)

    if new_labels is not None:
        objects = rename_labels(objects, new_labels)

    # Save predicted image.
    if save_path:
        image = cv2.cvtColor(vis_objects(np.array(image), objects), cv2.COLOR_BGR2RGB)
        cv2.imwrite(save_path, image)

    click.echo(" done.")
    return objects

def predict_image(
    network,
    path,
    only_classes=None,
    ignore_classes=None,
    save_path=None,
    min_prob=None,
    max_prob=None,
    pixel_distance=0,
    new_labels=None,
):
    click.echo("Predicting {}...".format(path), nl=False)
    extension = path.split(".")[-1]
    basename = os.path.basename(path)

    # Convert tif to a png acceptable by tensorflow in next steps below
    # Tried jpg creates all zeros on uint16 data -also jpg is lossy compression
    if extension == "tif":
        image = Image.open(path)
        image = cv2.cvtColor(np.array(image), cv2.COLOR_GRAY2BGR)
        tempname = basename.replace("." + extension, "." + "png")
        path = os.path.join(tempfile.mkdtemp(prefix="lumi"), tempname)
        cv2.imwrite(path, image)
    # Open and read the image to predict.
    with tf.gfile.Open(path, "rb") as f:
        try:
            image = Image.open(f).convert("RGB")
        except (tf.errors.OutOfRangeError, OSError) as e:
            click.echo()
            click.echo("Error while processing {}: {}".format(path, e))
            return

    # Run image through the network.
    return run_image_through_network(
        network,
        image,
        only_classes,
        ignore_classes,
        save_path,
        min_prob,
        max_prob,
        pixel_distance,
        new_labels,
    )

def predict_video(
    network,
    path,
    only_classes=None,
    ignore_classes=None,
    save_path=None,
    min_prob=None,
    max_prob=None,
    pixel_distance=0,
    new_labels=None,
):
    if save_path:
        # We hardcode the video output to mp4 for the time being.
        save_path = os.path.splitext(save_path)[0] + ".mp4"
        try:
            writer = skvideo.io.FFmpegWriter(save_path)
        except AssertionError as e:
            tf.logging.error(e)
            tf.logging.error("Please install ffmpeg before making video predictions.")
            exit()
    else:
        click.echo(
            "Video not being saved. Note that for the time being, no JSON "
            "output is being generated. Did you mean to specify `--save-path`?"
        )

    num_of_frames = int(skvideo.io.ffprobe(path)["video"]["@nb_frames"])

    video_progress_bar = click.progressbar(
        skvideo.io.vreader(path),
        length=num_of_frames,
        label="Predicting {}".format(path),
    )

    objects_per_frame = []
    with video_progress_bar as bar:
        try:
            start_time = time.time()
            for idx, frame in enumerate(bar):
                # Run image through network.
                objects = network.predict_image(frame)

                # Filter the results according to the user input.
                objects = filter_classes(
                    objects, only_classes=only_classes, ignore_classes=ignore_classes
                )

                objects = filter_probabilities(
                    objects, min_prob=min_prob, max_prob=max_prob
                )

                objects = filter_close_bbs(objects, pixel_distance)
                if new_labels is not None:
                    objects = rename_labels(objects, new_labels)

                objects_per_frame.append({"frame": idx, "objects": objects})

                # Draw the image and write it to the video file.
                if save_path:
                    image = vis_objects(frame, objects)
                    writer.writeFrame(image)

            stop_time = time.time()
            click.echo("fps: {0:.1f}".format(num_of_frames / (stop_time - start_time)))
        except RuntimeError as e:
            click.echo()  # Error prints next to progress bar otherwise.
            click.echo("Error while processing {}: {}".format(path, e))
            if save_path:
                click.echo(
                    "Partially processed video file saved in {}".format(save_path)
                )

    if save_path:
        writer.close()

    return objects_per_frame

def write_xlsx(csv_path, spacing, class_labels_percentage):
    folder_path = os.path.dirname(csv_path)
    workbook = xlsxwriter.Workbook(csv_path.replace(".csv", ".xlsx"))
    worksheet = workbook.add_worksheet("sheet1")

    worksheet.set_column("A:A", 15)
    worksheet.set_column("B:B", 10)
    temp_folder = os.path.join(folder_path, "predict_temp_bbs")
    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)
    else:
        print("Path {} already exists, might be overwriting data".format(temp_folder))
    df = pd.read_csv(csv_path)
    rowy = 0
    for label, frac in class_labels_percentage.items():
        subset_df = df[df["label"] == label].sample(frac=frac)
        for index, row in subset_df.iterrows():
            for i in range(len(row)):
                worksheet.write(rowy * spacing, i, row[i])
            image = cv2.imread(
                row["image_id"], cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR
            )
            if len(image.shape) == 3:
                image = image[row.ymin : row.ymax, row.xmin : row.xmax, :]
            else:
                image = image[row.ymin : row.ymax, row.xmin : row.xmax]
            temp_image = os.path.join(temp_folder, "temp_{}.png".format(rowy))
            cv2.imwrite(temp_image, image)
            worksheet.insert_image(
                rowy * spacing, i + 1, temp_image, {"x_scale": 0.3, "y_scale": 0.3}
            )
            rowy += 1

    workbook.close()

def get_key(new_labels, val):
    for key, value in new_labels.items():
        if val == value:
            return key

def predict_function(
    path_or_dir,
    config_files,
    checkpoint,
    override_params,
    output_path,
    save_media_to,
    min_prob,
    max_prob,
    max_detections,
    only_class,
    ignore_class,
    debug,
    xlsx_spacing,
    classes_json,
    pixel_distance,
    new_labels,
):
    class_labels_percentage = {}
    if classes_json is not None:
        with open(classes_json, "r") as f:
            class_labels_percentage = json.load(f)

    if new_labels is not None:
        with open(new_labels, "r") as f:
            new_labels = json.load(f)
    if debug:
        tf.logging.set_verbosity(tf.logging.DEBUG)
    else:
        tf.logging.set_verbosity(tf.logging.ERROR)

    if only_class and ignore_class:
        click.echo("Only one of `only-class` or `ignore-class` may be specified.")
        return

    # Process the input and get the actual files to predict.
    files = resolve_files(path_or_dir)
    if not files:
        error = "No files to predict found. Accepted formats are: {}.".format(
            ", ".join(IMAGE_FORMATS + VIDEO_FORMATS)
        )
        click.echo(error)
        return
    else:
        click.echo("Found {} files to predict.".format(len(files)))

    # Create `save_media_to` if specified and it doesn't exist.
    if save_media_to:
        tf.gfile.MakeDirs(save_media_to)

    # Resolve the config to use and initialize the model.
    if checkpoint:
        config = get_checkpoint_config(checkpoint)
    elif config_files:
        config = get_config(config_files)
    else:
        click.echo("Neither checkpoint not config specified, assuming `accurate`.")
        config = get_checkpoint_config("accurate")

    if override_params:
        config = override_config_params(config, override_params)
    # Filter bounding boxes according to `min_prob` and `max_detections`.
    if config.model.type == "fasterrcnn":
        if config.model.network.with_rcnn:
            config.model.rcnn.proposals.total_max_detections = max_detections
        else:
            config.model.rpn.proposals.post_nms_top_n = max_detections
        config.model.rcnn.proposals.min_prob_threshold = min_prob
    elif config.model.type == "ssd":
        config.model.proposals.total_max_detections = max_detections
        config.model.proposals.min_prob_threshold = min_prob
    else:
        raise ValueError("Model type '{}' not supported".format(config.model.type))

    # Instantiate the model indicated by the config.
    network = PredictorNetwork(config)
    # Iterate over files and run the model on each.
    df = pd.DataFrame(columns=LUMI_CSV_COLUMNS)

    for file in files:
        # Get the media output path, if media storage is requested.
        save_path = (
            os.path.join(save_media_to, "pred_{}".format(os.path.basename(file)))
            if save_media_to
            else None
        )

        file_type = get_file_type(file)
        predictor = predict_image if file_type == "image" else predict_video

        objects = predictor(
            network,
            file,
            only_classes=only_class,
            ignore_classes=ignore_class,
            save_path=save_path,
            min_prob=min_prob,
            max_prob=max_prob,
            pixel_distance=pixel_distance,
            new_labels=new_labels,
        )

        # TODO: Not writing csv for video files for now.
        unique_classes = []
        if objects is not None and file_type == "image":
            for obj in objects:
                if new_labels is not None:
                    label_name = get_key(new_labels, obj["label"])
                else:
                    label_name = obj["label"]
                unique_classes.append(label_name)
                df = df.append(
                    {
                        "image_id": file,
                        "xmin": obj["bbox"][0],
                        "xmax": obj["bbox"][2],
                        "ymin": obj["bbox"][1],
                        "ymax": obj["bbox"][3],
                        "label": label_name,
                        "prob": obj["prob"],
                    },
                    ignore_index=True,
                )

    # Build the `Formatter` based on the outputs, which automatically writes
    # the formatted output to all the requested output files.
    if output_path == "-":
        output = sys.stdout
        pd.set_option("display.max_colwidth", -1)
        output.write(df.to_string())
        output.close()
    else:
        sys.stdout.write(output_path.replace(".csv", ".txt"))
        df.to_csv(output_path)
        if class_labels_percentage == {}:
            unique_classes = list(set(unique_classes))
            class_labels_percentage = {
                unique_class: 1.0 for unique_class in unique_classes
            }
        if debug:
            write_xlsx(output_path, xlsx_spacing, class_labels_percentage)

@click.command(help="Obtain a model's predictions.")
@click.argument("path-or-dir", nargs=-1)
@click.option(
    "config_files", "--config", "-c", multiple=True, help="Config to use."
)  # noqa
@click.option("--checkpoint", help="Checkpoint to use.")
@click.option(
    "override_params",
    "--override",
    "-o",
    multiple=True,
    help="Override model config params.",
)  # noqa
@click.option(
    "output_path",
    "--output",
    "-f",
    default="-",
    help="Output file with the predictions (for example, csv bounding boxes) containing image_id,xmin,ymin,xmax,ymax,label",
)  # noqa
@click.option("--save-media-to", "-d", help="Directory to store media to.")
@click.option(
    "--min-prob",
    default=0.5,
    type=float,
    help="When drawing, only draw bounding boxes with probability larger than.",
)  # noqa
@click.option(
    "--max-prob",
    default=1.0,
    type=float,
    help="When drawing, only draw bounding boxes with probability lesser than.",
)  # noqa
@click.option(
    "--max-detections",
    default=100,
    type=int,
    help="Maximum number of detections per image.",
)  # noqa
@click.option(
    "--only-class",
    "-k",
    default=None,
    multiple=True,
    help="Class to include when predicting.",
)  # noqa
@click.option(
    "--ignore-class",
    "-K",
    default=None,
    multiple=True,
    help="Class to ignore when predicting.",
)  # noqa
@click.option("--debug", is_flag=True, help="Set debug level logging.")
@click.option(
    "--xlsx-spacing",
    default=2,
    type=int,
    help="When inserting images in xlsx, space between rows",
)  # noqa
@click.option(
    "--classes-json",
    required=False,
    help="path to a json file containing dictionary of class labels as keys and the float between 0 to 1 representing fraction of the rows/objects for the class to be saved in the xlsx as values",
)  # noqa
@click.option(
    "--pixel-distance",
    default=0,
    type=int,
    required=False,
    help="If 2 bounding boxes are pixel-distance apart, then keep the one with highest confidence/probability and remove the other",
)  # noqa
@click.option(
    "--new-labels",
    type=str,
    required=False,
    help="path to a json file containing dictionary of class labels as keys and the new label to replace with as value",
)  # noqa
def predict(
    path_or_dir,
    config_files,
    checkpoint,
    override_params,
    output_path,
    save_media_to,
    min_prob,
    max_prob,
    max_detections,
    only_class,
    ignore_class,
    debug,
    xlsx_spacing,
    classes_json,
    pixel_distance,
    new_labels,
):
    """Obtain a model's predictions.

    Receives either `config_files` or `checkpoint` in order to load the correct
    model. Afterwards, runs the model through the inputs specified by
    `path-or-dir`, returning predictions according to the format specified by
    `output`.

    Additional model behavior may be modified with `min-prob`, `only-class` and
    `ignore-class`.
    """
    # Read class labels as a list
    predict_function(
        path_or_dir,
        config_files,
        checkpoint,
        override_params,
        output_path,
        save_media_to,
        min_prob,
        max_prob,
        max_detections,
        only_class,
        ignore_class,
        debug,
        xlsx_spacing,
        classes_json,
        pixel_distance,
        new_labels,
    )

max_stars_repo_name: czbiohub/luminoth

max_issues_repo_name: czbiohub/luminoth-uv-imaging

max_forks_repo_name: czbiohub/luminoth

reason: import numpy


text:
import matplotlib.pyplot as plt
import numpy as np
import tikzplotlib

def moving_average(a, n=3) :
    """Compute a moving average for smoothing the curves"""
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

save_data = np.load('blend_point_goal1_trpo_test0.npz')

save_theta_rev_cost = save_data['theta']
save_context = save_data['context']
save_rev_cost_im = save_data['revcost']

rew_indx = 0
cost_indx = 1

last_index = save_context.shape[0]

norm_theta_rew = np.array([ np.linalg.norm(save_theta_rev_cost[t,:, rew_indx] - np.array([1.0,0])) for t in range(1,last_index)])
norm_theta_cost = np.array([ np.linalg.norm(save_theta_rev_cost[t,:, cost_indx] - np.array([0,1.0])) for t in range(1,last_index)])

curBis = 25000
plt.figure()
plt.plot(norm_theta_rew[:curBis], color='b', linewidth=3, label=r'$||\theta_{*,\mathrm{reward}}- \hat{\theta}_{t,\mathrm{reward}}||_2$')
plt.plot(norm_theta_cost[:curBis], color='g', linewidth=3, label=r'$||\theta_{*,\mathrm{cost}}- \hat{\theta}_{t,\mathrm{cost}}||_2$')
# plt.plot(time_step, est_rew, color='r', linewidth=3, label='Estimated reward')
plt.xlabel(r'Environment interacts')
plt.ylabel(r'$||\theta_{*,}- \hat{\theta}_{t,}||_2$')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig('difftheta.png', transparent=True)
tikzplotlib.save('difftheta.tex')

plt.show()
exit()
est_rew = np.array([ np.dot(save_context[t,:], save_theta_rev_cost[-1,:, rew_indx]) \
                        for t in range(1,last_index)])
est_cost = np.array([ np.dot(save_context[t,:], save_theta_rev_cost[-1,:, cost_indx]) \
                        for t in range(1,last_index)])

# theta_id = np.array([[1.0,0],[0,1.0]])
est_rew_id = np.array([ np.dot(save_context[t,:], np.array([1.0,0])) \
                        for t in range(1,last_index)])
est_cost_id = np.array([ np.dot(save_context[t,:], np.array([0,1.0])) \
                        for t in range(1,last_index)])

mean_val_r = np.mean(est_rew - est_rew_id)
std_dev_r = np.std(est_rew - est_rew_id)

mean_val_c = np.mean(est_cost - est_cost_id)
std_dev_c = np.std(est_cost - est_cost_id)

print ('Mean rew : {}, std dev rew : {}'.format(mean_val_r, std_dev_r))
print ('Mean cost : {}, std dev cost : {}'.format(mean_val_c, std_dev_c))

# exit()

time_step = [ i for i in range(1,last_index)]
window_avg = 1
cut = range(3296700,3297700)
est_rew = moving_average(est_rew, window_avg)[cut]
est_cost = moving_average(est_cost, window_avg)[cut]
im_rew = moving_average(save_rev_cost_im[1:last_index,rew_indx], window_avg)[cut]
im_cost = moving_average(save_rev_cost_im[1:last_index,cost_indx], window_avg)[cut]
time_step = moving_average(time_step, window_avg)[cut]
est_rew_id = moving_average(est_rew_id, window_avg)[cut]
est_cost_id = moving_average(est_cost_id, window_avg)[cut]

mean_val_r = np.mean(est_rew - est_rew_id)
std_dev_r = np.std(est_rew - est_rew_id)

mean_val_c = np.mean(est_cost - est_cost_id)
std_dev_c = np.std(est_cost - est_cost_id)

time_step = np.array([i for i in range(time_step.shape[0])])

plt.figure()
plt.plot(time_step, im_rew, color='b', linewidth=3, label='Immediate reward')
plt.plot(time_step, est_rew_id, color='g', linewidth=3, label='Ideal reward')
plt.plot(time_step, np.abs(est_rew_id - im_rew), linewidth=3)
# plt.plot(time_step, est_rew, color='r', linewidth=3, label='Estimated reward')
plt.xlabel('Environment interacts (t)')
plt.ylabel('Reward')
plt.legend()
plt.grid(True)
plt.tight_layout()
tikzplotlib.save('rew.tex')

plt.figure()
plt.scatter(time_step, est_rew_id - im_rew, color='m', marker='s', s=4)
plt.plot(time_step, [ mean_val_r for i in range(time_step.shape[0])], color='g', linewidth=3)
# plt.fill_between(time_step, [ mean_val_r - 3*std_dev_r for i in range(time_step.shape[0])], [ mean_val_r + 3*std_dev_r for i in range(time_step.shape[0])],
# 					facecolor='grey', edgecolor='darkgrey', linewidth=3)
# plt.plot(time_step, est_rew, color='r', linewidth=3, label='Estimated reward')
plt.xlabel('Environment interacts (t)')
plt.ylabel('Difference Reward')
plt.legend()
plt.grid(True)
plt.tight_layout()
tikzplotlib.save('diff_rew.tex')

plt.figure()
plt.plot(time_step, im_cost, color='b', linewidth=3, label='Immediate cost')
plt.plot(time_step, est_cost_id, color='g', linewidth=3, label='Ideal reward')
# plt.plot(time_step, est_cost, color='r', linewidth=3, label='Estimate cost')
plt.xlabel('Cost')
plt.ylabel('Environment interacts (t)')
plt.legend()
plt.grid(True)
plt.tight_layout()
tikzplotlib.save('cost.tex')

plt.figure()
plt.scatter(time_step, est_cost_id - im_cost, color='m', marker='s', s=4)
plt.plot(time_step, [ mean_val_c for i in range(time_step.shape[0])], color='g', linewidth=3)
# plt.fill_between(time_step, [ mean_val_c - 3*std_dev_c for i in range(time_step.shape[0])], [ mean_val_c + 3*std_dev_c for i in range(time_step.shape[0])],
# 					facecolor='grey', edgecolor='darkgrey', linewidth=3)
# plt.plot(time_step, est_rew, color='r', linewidth=3, label='Estimated reward')
plt.xlabel('Environment interacts (t)')
plt.ylabel('Difference cost')
plt.legend()
plt.grid(True)
plt.tight_layout()
tikzplotlib.save('diff_cost.tex')

# plt.figure()
# plt.plot(time_step, save_theta_rev_cost[-1,:, rew_indx], color='b', linewidth=3, label='Theta reward')
# plt.xlabel('Environment interacts (t)')
# plt.ylabel('Reward')
# plt.legend()
# plt.grid(True)
# plt.tight_layout()

# plt.figure()
# plt.plot(time_step, save_theta_rev_cost[-1,:, cost_indx], color='b', linewidth=3, label='Theta reward')
# plt.xlabel('Environment interacts (t)')
# plt.ylabel('Reward')
# plt.legend()
# plt.grid(True)
# plt.tight_layout()

plt.show()

max_stars_repo_name: parhamgohari/blending-controllers

max_issues_repo_name: parhamgohari/blending-controllers

max_forks_repo_name: parhamgohari/blending-controllers


text:
import requests
from PIL import Image
from io import BytesIO
import binascii
import numpy as np
import scipy
import scipy.misc
import scipy.cluster
from fucntools import lru_cache

NUM_CLUSTERS = 5

@lru_cache(None)
def getColor(link: str) -> str:
    response = requests.get(link)
    image = Image.open(BytesIO(response.content))
    image = image.resize((100, 100))
    ar = np.asarray(image)
    shape = ar.shape
    ar = ar.reshape(np.product(shape[:2]), shape[2]).astype(float)
    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
    vecs, dist = scipy.cluster.vq.vq(ar, codes)
    counts, bins = np.histogram(vecs, len(codes))
    index_max = np.argmax(counts)
    peak = codes[index_max]
    h = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii').lstrip('#')
    rgb = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
    rgb = f'rgb({rgb[0]},{rgb[1]},{rgb[2]})'
    return rgb

max_stars_repo_name: gabrycina/spotify-clone

max_issues_repo_name: gabrycina/spotify-clone

max_forks_repo_name: gabrycina/spotify-clone

reason: import numpy,import scipy


text:
#    Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
from __future__ import print_function
import numpy as np
from laed.utils import Pack
from laed.dataset.dataloader_bases import DataLoader

# Stanford Multi Domain
class SMDDataLoader(DataLoader):
    def __init__(self, name, data, config):
        super(SMDDataLoader, self).__init__(name, fix_batch=config.fix_batch)
        self.name = name
        self.max_utt_size = config.max_utt_len
        self.data = self.flatten_dialog(data, config.backward_size)
        self.data_size = len(self.data)
        if config.fix_batch:
            all_ctx_lens = [len(d.context) for d in self.data]
            self.indexes = list(np.argsort(all_ctx_lens))[::-1]
        else:
            self.indexes = list(range(len(self.data)))

    def flatten_dialog(self, data, backward_size):
        results = []
        for dialog in data:
            for i in range(1, len(dialog)):
                e_id = i
                s_id = max(0, e_id - backward_size)
                response = dialog[i].copy()
                response['utt'] = self.pad_to(self.max_utt_size, response.utt, do_pad=False)
                contexts = []
                for turn in dialog[s_id:e_id]:
                    turn['utt'] = self.pad_to(self.max_utt_size, turn.utt, do_pad=False)
                    contexts.append(turn)
                results.append(Pack(context=contexts, response=response))
        return results

    def _prepare_batch(self, selected_index):
        rows = [self.data[idx] for idx in selected_index]
        # input_context, context_lens, floors, topics, a_profiles, b_Profiles, outputs, output_lens
        context_lens, context_utts, out_utts, out_lens = [], [], [], []
        metas = []
        for row in rows:
            ctx = row.context
            resp = row.response

            out_utt = resp.utt
            context_lens.append(len(ctx))
            context_utts.append([turn.utt for turn in ctx])

            out_utt = out_utt
            out_utts.append(out_utt)
            out_lens.append(len(out_utt))
            metas.append(resp.meta)

        vec_context_lens = np.array(context_lens)
        vec_context = np.zeros((self.batch_size, np.max(vec_context_lens),
                                self.max_utt_size), dtype=np.int32)
        vec_outs = np.zeros((self.batch_size, np.max(out_lens)), dtype=np.int32)
        vec_out_lens = np.array(out_lens)

        for b_id in range(self.batch_size):
            vec_outs[b_id, 0:vec_out_lens[b_id]] = out_utts[b_id]
            # fill the context tensor
            new_array = np.empty((vec_context_lens[b_id], self.max_utt_size))
            new_array.fill(0)
            for i, row in enumerate(context_utts[b_id]):
                for j, ele in enumerate(row):
                    new_array[i, j] = ele
            vec_context[b_id, 0:vec_context_lens[b_id], :] = new_array

        return Pack(contexts=vec_context, context_lens=vec_context_lens,
                    outputs=vec_outs, output_lens=vec_out_lens,
                    metas=metas)

class SMDDialogSkipLoader(DataLoader):
    def __init__(self, name, data, config):
        super(SMDDialogSkipLoader, self).__init__(name, fix_batch=config.fix_batch)
        self.name = name
        self.max_utt_size = config.max_utt_len
        self.data = self.flatten_dialog(data, config.backward_size)
        self.data_size = len(self.data)
        if config.fix_batch:
            all_ctx_lens = [len(d.context) for d in self.data]
            self.indexes = list(np.argsort(all_ctx_lens))[::-1]
        else:
            self.indexes = list(range(len(self.data)))

    def flatten_dialog(self, data, backward_size):
        results = []
        for dialog in data:
            for i in range(1, len(dialog)-1):
                e_id = i
                s_id = max(0, e_id - backward_size)

                response = dialog[i]
                prev = dialog[i - 1]
                next = dialog[i + 1]

                response['utt'] = self.pad_to(self.max_utt_size, response.utt, do_pad=False)
                prev['utt'] = self.pad_to(self.max_utt_size, prev.utt, do_pad=False)
                next['utt'] = self.pad_to(self.max_utt_size, next.utt, do_pad=False)

                contexts = []
                for turn in dialog[s_id:e_id]:
                    turn['utt'] = self.pad_to(self.max_utt_size, turn.utt, do_pad=False)
                    contexts.append(turn)

                results.append(Pack(context=contexts, response=response,
                                    prev_resp=prev, next_resp=next))
        return results

    def _prepare_batch(self, selected_index):
        rows = [self.data[idx] for idx in selected_index]

        context_lens, context_utts, out_utts, out_lens = [], [], [], []
        prev_utts, prev_lens = [], []
        next_utts, next_lens = [], []
        metas = []
        for row in rows:
            ctx = row.context
            resp = row.response

            out_utt = resp.utt
            context_lens.append(len(ctx))
            context_utts.append([turn.utt for turn in ctx])

            out_utt = out_utt
            out_utts.append(out_utt)
            out_lens.append(len(out_utt))
            metas.append(resp.meta)

            prev_utts.append(row.prev_resp.utt)
            prev_lens.append(len(row.prev_resp.utt))

            next_utts.append(row.next_resp.utt)
            next_lens.append(len(row.next_resp.utt))

        vec_context_lens = np.array(context_lens)
        vec_context = np.zeros((self.batch_size, np.max(vec_context_lens),
                                self.max_utt_size), dtype=np.int32)
        vec_outs = np.zeros((self.batch_size, np.max(out_lens)), dtype=np.int32)
        vec_prevs = np.zeros((self.batch_size, np.max(prev_lens)), dtype=np.int32)
        vec_nexts = np.zeros((self.batch_size, np.max(next_lens)),dtype=np.int32)
        vec_out_lens = np.array(out_lens)
        vec_prev_lens = np.array(prev_lens)
        vec_next_lens = np.array(next_lens)

        for b_id in range(self.batch_size):
            vec_outs[b_id, 0:vec_out_lens[b_id]] = out_utts[b_id]
            vec_prevs[b_id, 0:vec_prev_lens[b_id]] = prev_utts[b_id]
            vec_nexts[b_id, 0:vec_next_lens[b_id]] = next_utts[b_id]

            # fill the context tensor
            new_array = np.empty((vec_context_lens[b_id], self.max_utt_size))
            new_array.fill(0)
            for i, row in enumerate(context_utts[b_id]):
                for j, ele in enumerate(row):
                    new_array[i, j] = ele
            vec_context[b_id, 0:vec_context_lens[b_id], :] = new_array

        return Pack(contexts=vec_context, context_lens=vec_context_lens,
                    outputs=vec_outs, output_lens=vec_out_lens,
                    metas=metas, prevs=vec_prevs, prev_lens=vec_prev_lens,
                    nexts=vec_nexts, next_lens=vec_next_lens)

# Daily Dialog
class DailyDialogSkipLoader(DataLoader):
    def __init__(self, name, data, config):
        super(DailyDialogSkipLoader, self).__init__(name, fix_batch=config.fix_batch)
        self.name = name
        self.max_utt_size = config.max_utt_len
        self.data = self.flatten_dialog(data, config.backward_size)
        self.data_size = len(self.data)
        if config.fix_batch:
            all_ctx_lens = [len(d.context) for d in self.data]
            self.indexes = list(np.argsort(all_ctx_lens))[::-1]
        else:
            self.indexes = list(range(len(self.data)))

    def flatten_dialog(self, data, backward_size):
        results = []
        for dialog in data:
            for i in range(1, len(dialog)-1):
                e_id = i
                s_id = max(0, e_id - backward_size)

                response = dialog[i]
                prev = dialog[i - 1]
                next = dialog[i + 1]

                response['utt'] = self.pad_to(self.max_utt_size,response.utt, do_pad=False)
                prev['utt'] = self.pad_to(self.max_utt_size, prev.utt, do_pad=False)
                next['utt'] = self.pad_to(self.max_utt_size, next.utt, do_pad=False)

                contexts = []
                for turn in dialog[s_id:e_id]:
                    turn['utt'] = self.pad_to(self.max_utt_size, turn.utt, do_pad=False)
                    contexts.append(turn)

                results.append(Pack(context=contexts, response=response,
                                    prev_resp=prev, next_resp=next))
        return results

    def _prepare_batch(self, selected_index):
        rows = [self.data[idx] for idx in selected_index]

        context_lens, context_utts, out_utts, out_lens = [], [], [], []
        prev_utts, prev_lens = [], []
        next_utts, next_lens = [], []
        metas = []
        for row in rows:
            ctx = row.context
            resp = row.response

            out_utt = resp.utt
            context_lens.append(len(ctx))
            context_utts.append([turn.utt for turn in ctx])

            out_utt = out_utt
            out_utts.append(out_utt)
            out_lens.append(len(out_utt))
            metas.append(resp.meta)

            prev_utts.append(row.prev_resp.utt)
            prev_lens.append(len(row.prev_resp.utt))

            next_utts.append(row.next_resp.utt)
            next_lens.append(len(row.next_resp.utt))

        vec_context_lens = np.array(context_lens)
        vec_context = np.zeros((self.batch_size, np.max(vec_context_lens),
                                self.max_utt_size), dtype=np.int32)
        vec_outs = np.zeros((self.batch_size, np.max(out_lens)), dtype=np.int32)
        vec_prevs = np.zeros((self.batch_size, np.max(prev_lens)), dtype=np.int32)
        vec_nexts = np.zeros((self.batch_size, np.max(next_lens)),dtype=np.int32)
        vec_out_lens = np.array(out_lens)
        vec_prev_lens = np.array(prev_lens)
        vec_next_lens = np.array(next_lens)

        for b_id in range(self.batch_size):
            vec_outs[b_id, 0:vec_out_lens[b_id]] = out_utts[b_id]
            vec_prevs[b_id, 0:vec_prev_lens[b_id]] = prev_utts[b_id]
            vec_nexts[b_id, 0:vec_next_lens[b_id]] = next_utts[b_id]

            # fill the context tensor
            new_array = np.empty((vec_context_lens[b_id], self.max_utt_size))
            new_array.fill(0)
            for i, row in enumerate(context_utts[b_id]):
                for j, ele in enumerate(row):
                    new_array[i, j] = ele
            vec_context[b_id, 0:vec_context_lens[b_id], :] = new_array

        return Pack(contexts=vec_context, context_lens=vec_context_lens,
                    outputs=vec_outs, output_lens=vec_out_lens,
                    metas=metas, prevs=vec_prevs, prev_lens=vec_prev_lens,
                    nexts=vec_nexts, next_lens=vec_next_lens)

# PTB
class PTBDataLoader(DataLoader):

    def __init__(self, name, data, config):
        super(PTBDataLoader, self).__init__(name, fix_batch=config.fix_batch)
        self.max_utt_size = config.max_utt_len
        self.data = self.pad_data(data)
        self.data_size = len(self.data)
        all_lens = [len(line.utt) for line in self.data]
        print("Max len %d and min len %d and avg len %f" % (np.max(all_lens),
                                                            np.min(all_lens),
                                                            float(np.mean(all_lens))))
        if config.fix_batch:
            self.indexes = list(np.argsort(all_lens))
        else:
            self.indexes = list(range(len(self.data)))

    def pad_data(self, data):
        for l in data:
            l['utt'] = self.pad_to(self.max_utt_size, l.utt, do_pad=False)
        return data

    def _prepare_batch(self, selected_index):
        rows = [self.data[idx] for idx in selected_index]
        input_lens = np.array([len(row.utt) for row in rows], dtype=np.int32)
        max_len = np.max(input_lens)
        inputs = np.zeros((self.batch_size, max_len), dtype=np.int32)
        for idx, row in enumerate(rows):
            inputs[idx, 0:input_lens[idx]] = row.utt

        return Pack(outputs=inputs, output_lens=input_lens, metas=[None]*len(rows))


text:
from librovers import *  # import bindings.
import random
import numpy as np

"""
A stealthy POI that blinks out occasionally.
"""
class StealthyPOI(rovers.IPOI):
    def __init__(self, value, obs_radius, constraintPolicy, stealth_mastery=0.3):
        super().__init__(value, obs_radius)
        # we will use the stealth combined with a constraint defined in the lib
        self.constraintPolicy = constraintPolicy
        self.stealth_mastery = stealth_mastery  # 0.0 = rookie, 1.0 = super stealthy
        self.visible = False

    # Use a library defined or custom constraint policy with stealth
    def constraint_satisfied(self, entity_pack):
        if not self.visible:
            return False    # "you can't see me"

        return self.constraintPolicy.is_satisfied(entity_pack)

    # tick() is called at every time step (tick) by the library.
    # blink based on a coin toss and stealth mastery
    def tick(self):
        if random.random() < self.stealth_mastery:
            self.visible = False
        else:
            self.visible = True

"""
Custom constraint:
POIs with this constrait can only be observed \
after all other POIs have been observed.
"""
class LastPOIConstraint(rovers.IConstraint):
    def is_satisfied(self, entity_pack):
        for poi in entity_pack.entities:
            if not poi.observed():
                return False

        return True

# aliasing some types to reduce typing
Dense = rovers.Lidar[rovers.Density]        # lidar with density composition
Close = rovers.Lidar[rovers.Closest]        # lidar for closest rover/poi
Discrete = thyme.spaces.Discrete            # Discrete action space
Difference = rovers.rewards.Difference      # Difference reward

agents = [
    # create agent with difference reward
    rovers.Rover[Dense, Discrete, Difference](1.0, Dense(90)),
    # create rover with close lidar and global reward
    rovers.Rover[Close, Discrete](2.0, Close(90)),
    rovers.Drone()  # drone with no policy specifications (all defaults)
]

pois = [
    # 3 agents must observe
    rovers.POI[rovers.CountConstraint](3),
    # Our custom POI constraint. The POI has a value of 10 and obs_radius of 5.0.
    # mvp, can be observed when all other POIs are observed
    rovers.POI[LastPOIConstraint](10, 5.0, LastPOIConstraint()),
    # 5 agents of a certain type must observe
    rovers.POI[rovers.TypeConstraint](5),
    # Stealthy POI! Has a value of 100.
    # super stealthy with 97% mastery, but needs only 1 spotter!
    StealthyPOI(100, 3.0, rovers.CountConstraint(1), .97)
]

# Environment with rovers and pois placed in the corners. Defaults to random initialization if unspecified.
Env = rovers.Environment[rovers.CornersInit]
# create an environment with our rovers and pois:
env = Env(rovers.CornersInit(10.0), agents, pois)
states, rewards = env.reset()

# print sample state
print("Sample environment state (each row corresponds to the state of a rover): ")
for state in states:
    print(state.transpose())

max_stars_repo_name: gaurav-dixitv/rovers

max_issues_repo_name: gaurav-dixitv/rovers

max_forks_repo_name: gaurav-dixitv/rovers


text:
import torch
import numpy as np

def make_experiment_reproducible(random_seed: int):
    torch.manual_seed(random_seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(random_seed)


text:
# Simulate the bandits recommendations on Salis preds
#
# The pipeline includes the following steps:
# - data pre-processing
# - prediction (GPR)
# - batch UCB recommendation
#

# %%
# direct to proper path
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
    sys.path.append(module_path)

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
from matplotlib import cm, rcParams
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import seaborn as sns

import itertools
from collections import defaultdict
import math
import json
# import xarray as xr

from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import PairwiseKernel, DotProduct, RBF
from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics import r2_score, mean_squared_error, make_scorer
from sklearn.model_selection import KFold
from sklearn.manifold import TSNE

from src.embedding import Embedding
from src.environment import Rewards_env
from src.evaluations import evaluate, plot_eva
from src.regression import *
from src.kernels_for_GPK import *
from src.data_generating import generate_data
from src.batch_ucb import *
import src.config
import warnings
from platform import python_version
print(python_version())

# folder_path = '../data/'
# raw = 'n'
# create df in required form
result_path = '../data/Results_Salis.csv'
whole_size = 4096

if not os.path.exists(result_path):
    data_path = '../data/Comparison_Data/Model_Comparisons.csv'
    data_df = pd.read_csv(data_path, header= 0)

    # # Data pre-processing
    #
    # Our data pre-processing involved the following options:
    # - a. In each round, substract the mean of every data points by the reference AVERAGE, and then add 100 (to make the values positive).
    # - b. Take log (base e) transformation for each data point.
    # - c. Apply z-score normalisation.
    #     - c.1 on each round, so that the mean and variance of each replicate of data in each round is zero and one after normalisation.
    #     - c.2 on all data, so that the mean and variance of each replicate of all data is zero and one after normalisation.
    # - d. Apply min-max normalisation.
    #     - d.1 on each round
    #     - d.2 on all data
    # - e. Apply ratio normalisation. In each round, each data points is devided by the mean of refernce AVERAGE, so that in each round, the reference labels are almost 1.
    #     - e.1 on each round
    #     - e.2 on all data
    #
    # In Round 1 (Bandit-1), we adopt *bc1*. We have observed that the reference sequences give differerent TIR values in each round. Thus in Round 2-3 (Bandit-3), we substructed the mean first and adopted *abc1*.
    #
    #
    # The source code of data generating approaches is defined in src/data_generating.py.

    # round1='bc1'
    # round23 = 'abc1'

    # corresponding to bc2 (since there is round, do not need to run a, and replace c1 to c2)

    log_salis = np.log(data_df['TIR_Salis'])
    data_df['TIR_Salis_zscoreNorm'] = (log_salis - log_salis.mean())/log_salis.std()
    print(data_df.sort_values(by = ['TIR_Salis_zscoreNorm']))
    print('TIR_Salis_zscoreNorm mean: ', data_df['TIR_Salis_zscoreNorm'].mean())
    print('TIR_Salis_zscoreNorm std: ', data_df['TIR_Salis_zscoreNorm'].std())

    # plt.hist(df['TIR_Salis_zscoreNorm'])
    # plt.savefig('log_TIR_Salis_zscoreNorm_hist.png')

    df = pd.DataFrame(columns=['Name','Group','Plate','Round','RBS','RBS6','Rep1','Rep2', 'Rep3', 'Rep4','Rep5','Rep6','AVERAGE', 'STD'])
    df[['RBS', 'RBS6', 'AVERAGE']] = data_df[['RBS_sequence', 'RBS_Core','TIR_Salis_zscoreNorm']]
    for i in range(whole_size):
        df.loc[i,'Name'] = i
        df.loc[i,'Round'] = 10 # bigger than design round
        df.loc[i,'STD'] = 0.3 # average std in previous data
        for j in range(1, 7):
            df.loc[i, 'Rep' + str(j)] = np.random.normal(df.loc[i, 'AVERAGE'], df.loc[i, 'STD'])

    df.to_csv(result_path, index=False)
    print('Save result file to {}'.format(result_path))
else:
    print('Load result file from {}'.format(result_path))
    df = pd.read_csv(result_path, header = 0)

# ## Prediction & Recommendation
# The prediction code is mainly located in *src.regression.py*, the recommendation code is in $src.batch\_ucb.py$.
# To predict, the *src.kernels\_for\_GPK.py* is called to calculate the kernel functions.
# When we call the GP_BUCB function, the prediction (GPR) is firstly called and recommendation is conducted based on the recommendation.
#
# The settings are specified as in the next cell. To generate the recommendation result for round n, change the parameter *design_round = n*.

# setting

rec_size = 90 # in each round, we recommend 90 RBS sequences
l = 6 # maximum kmer as 6
s = 1 # maximum shift as 1
alpha = 2 # GPR noise parameter, get from cross validation
sigma_0 = 1 # signal for kernel matrix
kernel = 'WD_Kernel_Shift' # weighted degree kernel with shift
embedding = 'label' # turns strings into categories first and used for kernel
kernel_norm_flag = True # whether to apply kernel normalisation
centering_flag = True # whether to apply kernel centering
unit_norm_flag = True # whether to apply unit norm for kernel
kernel_over_all_flag = True  # we keep the setting the same as our last round
# if design_round == 1:  # kernel normalisation over what
#     kernel_over_all_flag = False
#     df = df_round1
# else:
#     kernel_over_all_flag = True
#     df = df_round23

n_repeat = 100
total_round = 5

all_recs = []
# save_folder_path = './sim_results'
save_folder_path = '/home/v-mezhang/blob/Solaris/sim_results/gpbucb'
print('save folder path: ', save_folder_path)
if not os.path.exists(save_folder_path):
    os.makedirs(save_folder_path)

with open(config.SAVED_IDX_SEQ_PATH, 'rb') as handle:
    idx_seq = pickle.load(handle)

idx_seq_dict = idx_seq['idx_seq_dict']

for i in range(80, n_repeat):
    rec_dfs = []

    df['Round'] = total_round
    recs = []
    for design_round in range(total_round):
        # UCB hyperparameter
        if design_round == total_round - 1: # last round
            beta = 0
        else:
            beta = 2

        # Debug: the bandit rec finds the best ones at the beginning, but with decreased performance. I guess the reason is we set beta = 2, for exploration. Let me try to set beta = 0 for bandit-i (where I >= 1)
        # if design_round <=1:
        #     beta = 2
        # else:
        #     beta = 0

        if design_round == 0:
            # random sample
            print('Design round {}: randomly generate {} recommendations.'.format(design_round, rec_size))

            rec_idxs = np.random.choice(range(whole_size), size = rec_size, replace=False)
            # rec first rec size
            # rec_idxs = range((0 + i) * rec_size, (1+i)* rec_size)
            # print(rec_idxs)
            rec_rbs_list = [df.loc[i, 'RBS'] for i in rec_idxs]
            rec_rbs6_list = [df.loc[i, 'RBS'][7:13] for i in rec_idxs]

            # rec worst averages
            # rec_rbs_list = list(df.sort_values(by = ['AVERAGE'])[:rec_size]['RBS'])
            # rec_rbs6_list = list(df.sort_values(by = ['AVERAGE'])[:rec_size]['RBS6'])

            # print(rec_rbs_list)
            rec_df = pd.DataFrame(columns=['idx', 'RBS','RBS6','AVERAGE', 'pred mean', 'pred std', 'ucb', 'lcb', 'Group'])
            rec_df['RBS'] = rec_rbs_list
            rec_df['RBS6']  = rec_rbs6_list
            rec_df['Group'] = 'Random'
            for j, rbs in rec_df.iterrows():
                rec_df.loc[j, 'idx'] = idx_seq_dict[rbs['RBS']]
            rec_df = rec_df.set_index('idx')
        else:
            print('Design round {}: '.format(design_round))
            # Top_n_ucb
            gpbucb = GP_BUCB(df[df['Round'] < design_round], kernel_name=kernel, l=l, s=s,
                            sigma_0=sigma_0,
                            embedding=embedding, alpha=alpha, rec_size=rec_size, beta=beta,
                            kernel_norm_flag=kernel_norm_flag, centering_flag = centering_flag,
                            unit_norm_flag=unit_norm_flag, kernel_over_all_flag = kernel_over_all_flag)

            rec_df = gpbucb.run_experiment()
            rec_df['Group'] = 'Bandit-' + str(design_round-1)
            rec_rbs_list = list(rec_df['RBS'])

        for j in range(whole_size):
            if df.loc[j, 'RBS'] in rec_rbs_list:
                df.loc[j, 'Round'] = design_round

        rec_df['Round'] = design_round
        print(rec_df)
        rec_dfs.append(rec_df)
        recs.append(rec_rbs_list)
    rec_dfs = pd.concat(rec_dfs) # , ignore_index=True
    rec_dfs = rec_dfs.merge(df[['RBS', 'AVERAGE']], how='left', on = 'RBS')
    rec_dfs = rec_dfs.rename(columns = {'AVERAGE_y': 'AVERAGE'}).drop(columns = ['AVERAGE_x'])
    print(rec_dfs)
    rec_dfs.to_csv(os.path.join(save_folder_path, 'recs_' + str(i) + '_' + str(rec_size) + '.csv'))
    all_recs.append(recs)

    np.save('all_recs_'+ str(i) + '_' + str(rec_size) + '.npy', all_recs)

max_stars_repo_name: mholowko/Solaris

max_issues_repo_name: mholowko/Solaris

max_forks_repo_name: mholowko/Solaris


text:
import numpy as np
import pytest

from cara import models
from cara import data

def test_piecewiseconstantfunction_wrongarguments():
    # number of values should be 1+number of transition times
    pytest.raises(ValueError, models.PiecewiseConstant, (0, 1), (0, 0))
    pytest.raises(ValueError, models.PiecewiseConstant, (0,), (0, 0))
    # two transition times cannot be equal
    pytest.raises(ValueError, models.PiecewiseConstant, (0, 2, 2), (0, 0))
    # unsorted transition times are not allowed
    pytest.raises(ValueError, models.PiecewiseConstant, (2, 0), (0, 0))

    # If vectors, must all be same length.
    with pytest.raises(ValueError, match="All values must have the same shape"):
        models.PiecewiseConstant(
            (0, 8, 16), (np.array([5, 7]), np.array([8, 9, 10])),
        )

@pytest.mark.parametrize(
    "time, expected_value",
    [
        [10, 5],
        [20.5, 8],
        [8, 2],
        [0, 2],
        [24, 8],
        [-1, 2],
        [25, 8],
    ],
)
def test_piecewiseconstant(time, expected_value):
    transition_times = (0, 8, 16, 24)
    values = (2, 5, 8)
    fun = models.PiecewiseConstant(transition_times, values)
    assert fun.value(time) == expected_value

def test_piecewiseconstant_interp():
    transition_times = (0, 8, 16, 24)
    values = (2, 5, 8)
    refined_fun = models.PiecewiseConstant(transition_times, values).refine(refine_factor=2)
    assert refined_fun.transition_times == (0, 4, 8, 12, 16, 20, 24)
    assert refined_fun.values == (2, 3.5, 5, 6.5, 8, 8)

def test_piecewiseconstant_interp_vectorised():
    transition_times = (0, 8, 16, 24)
    values = (np.array([2, 3]), np.array([5, 7]), np.array([8, 9]))
    refined_fun = models.PiecewiseConstant(transition_times, values).refine(refine_factor=2)
    assert refined_fun.transition_times == (0, 4, 8, 12, 16, 20, 24)
    np.testing.assert_almost_equal(
        refined_fun.values, ((2, 3), (3.5, 5), (5, 7), (6.5, 8), (8, 9), (8, 9)),
    )

def test_constantfunction():
    transition_times = (0, 24)
    values = (20,)
    fun = models.PiecewiseConstant(transition_times, values)
    for t in [0, 1, 8, 10, 16, 20.1, 24]:
        assert (fun.value(t) == 20)

@pytest.mark.parametrize(
    "time",
    [0, 1, 8, 10, 16, 20.1, 24],
)
def test_piecewiseconstant_vs_interval(time):
    transition_times = (0, 8, 16, 24)
    values = (0, 1, 0)
    fun = models.PiecewiseConstant(transition_times, values)
    interval = models.SpecificInterval(present_times=[(8,16)])
    assert interval.transition_times() == fun.interval().transition_times()
    assert fun.interval().triggered(time) == interval.triggered(time)

def test_piecewiseconstant_transition_times():
    outside_temp = data.GenevaTemperatures['Jan']
    assert set(outside_temp.transition_times) == outside_temp.interval().transition_times()

max_stars_repo_name: pk-scs/cara

max_issues_repo_name: pk-scs/cara

max_forks_repo_name: pk-scs/cara


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 14 14:21:49 2018

@author: hendrawahyu
"""

import numpy as np
from PIL import Image, ImageFilter

# =============================================================================
# The image of my written number has to be formatted in the same way as the images form
# the MNIST database. If the images don’t match, it will try to predict something else.
# The MNIST website provides the following information:
# – Images are normalized to fit in a 20×20 pixel box while preserving their aspect ratio.
# – Images are centered in a 28×28 image.
# – Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black).
# Param: thresh_image - a binary image where background is white and character is black
# Output: return 28 x 28 template with centered characters
# =============================================================================
def prepare_character(bin_img):
    height = bin_img.shape[1]
    width  = bin_img.shape[0]
    newImage = Image.new('L', (28, 28), (255))                          #creates white canvas of 28x28 pixels
    new_img = Image.fromarray(bin_img)
    if width > height:
        nheight = int(round((20.0/width*height), 0))                    #resize
        if(nheight == 0):
            nheight = 1
        elif (nheight < 10):
            new_img = new_img.filter(ImageFilter.SHARPEN)
            offset = ((28 - height)//2, (28 - width) // 2)
        else:
            new_img = new_img.resize((20, nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
            wtop = int(round(((28 - nheight)/2),0))
            offset = (4, wtop)
        newImage.paste(new_img, offset)
    else:
        nwidth = int(round((20.0/width*height), 0))                     #resize
        if(nwidth == 0):
            nwidth = 1
        elif (nwidth < 10):
            new_img = new_img.filter(ImageFilter.SHARPEN)
            offset = ((28 - height) // 2, (28 - width) // 2)
        else:
            new_img = new_img.resize((nwidth, 20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
            wleft = int(round(((28 - nwidth)/2),0))
            offset = (wleft, 4)
        newImage.paste(new_img, offset)
    # Normalize pixel values to 0 and 1 (a MUST for TensorFlow)
    new_img = np.array(newImage)
    return new_img

max_stars_repo_name: godzmaru/PlantAnalysis

max_issues_repo_name: godzmaru/PlantAnalysis

max_forks_repo_name: godzmaru/PlantAnalysis


text:
if '__file__' in globals():
    import os
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import math

import numpy as np
import matplotlib.pyplot as plt

from dezero import datasets
from dezero import models
from dezero import optimizers
from dezero import functions as F

np.random.seed(0)
x, t = datasets.get_spiral(train=True)
print(x.shape)
print(t.shape)

print(x[10], t[10])
print(x[110], t[110])

max_epoch = 300
batch_size = 30
hidden_size = 10
lr = 1.0

model = models.MLP((hidden_size, 3))
optimizer = optimizers.MomentumSGD(lr).setup(model)

data_size = len(x)
max_iter = math.ceil(data_size / batch_size)

for epoch in range(max_epoch):
    index = np.random.permutation(data_size)
    sum_loss = 0

    for i in range(max_iter):
        batch_index = index[i * batch_size:(i + 1) * batch_size]
        batch_x = x[batch_index]
        batch_t = t[batch_index]

        y = model(batch_x)
        loss = F.softmax_cross_entropy(y, batch_t)
        model.cleargrads()
        loss.backward()
        optimizer.update()
        sum_loss += float(loss.data) * len(batch_t)

    avg_loss = sum_loss / data_size
    print(f'epoch {epoch + 1}, loss {avg_loss:.2f}')

for i in range(3):
    plt.scatter(x[t==i][:,0], x[t==i][:,1])
plt.show()

max_stars_repo_name: teijeong/deeplearning-from-scratch

max_issues_repo_name: teijeong/deeplearning-from-scratch

max_forks_repo_name: teijeong/deeplearning-from-scratch


text:
import platform

import numpy as np
from Cython.Build import cythonize
from setuptools import find_packages, Extension, setup

def read(path):
    with open(path, 'r') as f:
        return f.read()

long_description = read('README.md')

include_dirs = ['fbgbp/src', np.get_include()]
extra_compile_args = [
    '-Wno-unused-variable',
    '-Wno-unused-function',
    '-O3',
    '-std=c++11',
]
extra_link_args = []
if platform.system().lower() == 'darwin':
    extra_compile_args.append('-stdlib=libc++')
    extra_link_args.append('-stdlib=libc++')
to_cythonize = [
    Extension(
        'fbgbp.binary_belief_propagation', [
            'fbgbp/binary_belief_propagation.pyx',
            'fbgbp/src/binary_belief_propagation.cpp',
        ],
        include_dirs=include_dirs,
        extra_compile_args=extra_compile_args,
        extra_link_args=extra_link_args,
        language='c++',
    ),
    Extension(
        'fbgbp.binary_grid_belief_propagation', [
            'fbgbp/binary_grid_belief_propagation.pyx',
            'fbgbp/src/binary_belief_propagation.cpp',
        ],
        include_dirs=include_dirs,
        extra_compile_args=extra_compile_args,
        extra_link_args=extra_link_args,
        language='c++',
    ),
]

requirements = read('requirements.txt').strip().split('\n')
setup(
    name='fbgbp',
    version='0.2.1',
    url='https://github.com/Lioscro/fbgbp',
    author='Kyung Hoi (Joseph) Min',
    author_email='phoenixter96@gmail.com',
    description='Optimized belief propagation on a grid MRF with binary states.',  # noqa
    long_description=long_description,
    long_description_content_type='text/markdown',
    keywords='belief-propagation markov-random-field',
    python_requires='>=3.6',
    license='MIT',
    packages=find_packages(exclude=('tests', 'docs')),
    zip_safe=False,
    include_package_data=True,
    install_requires=requirements,
    ext_modules=cythonize(
        to_cythonize,
        language_level='3',
        compiler_directives={'embedsignature': True}
    ),
    classifiers=[
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Cython',
    ],
)

max_stars_repo_name: Lioscro/fbgbp

max_issues_repo_name: Lioscro/fbgbp

max_forks_repo_name: Lioscro/fbgbp


text:
# -*- coding: utf-8 -*-

import numpy as np, tensorflow as tf, pandas as pd, arviz as az, seaborn as sns, tensorflow_probability as tfp
from matplotlib import pyplot as plt, dates as mdates
tfd, tfb = tfp.distributions, tfp.bijectors
tf.config.optimizer.set_jit(True)

raw_data = pd.read_csv("data/challenger_data.csv")
raw_data["Date"] = pd.to_datetime(raw_data["Date"], infer_datetime_format=True)

# pop last row -> drop missing -> change dtype
challenger = raw_data.drop(raw_data.tail(1).index).dropna().astype({"Damage Incident": 'int32'})
challenger.plot.scatter(x = "Temperature", y = "Damage Incident")

challenger.plot.scatter(x = "Date", y = "Temperature", c = "Damage Incident", cmap = plt.cm.get_cmap('RdBu', 2))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.gcf().autofmt_xdate()

dam = tf.cast(challenger["Damage Incident"], "float32")
temp = tf.cast(challenger["Temperature"], "float32")
var_name = ["alpha", "beta"]

@tfd.JointDistributionCoroutineAutoBatched
def mdl_batch():
	alpha = yield tfd.Normal(loc = 0., scale = 1000., name="alpha")
	beta = yield tfd.Normal(loc = 0., scale = 1000., name="beta")
	prob = 1./(1. + tf.exp(beta * temp + alpha))
	dam = yield tfd.Bernoulli(probs = prob, name="damage")

# a helper function in McMC chain
def trace_fn(current_state, kernel_results):
	mdr = kernel_results.inner_results.inner_results
	return mdr.target_log_prob, mdr.leapfrogs_taken, mdr.has_divergence, mdr.energy, mdr.log_accept_ratio

@tf.function(autograph = False, experimental_compile = True) # speed up a lot the McMC sampling
def run_mcmc( # pass numeric arguments as Tensors whenever possible
	init_state, unconstraining_bijectors,
	num_steps = 50000, burnin = 10000,
	num_leapfrog_steps = 3, step_size = .5
):
	kernel0 = tfp.mcmc.NoUTurnSampler(
		target_log_prob_fn = lambda *args: mdl_batch.log_prob(damage=dam, *args),
		step_size = step_size
	)
	kernel1 = tfp.mcmc.TransformedTransitionKernel(
		inner_kernel= kernel0,
		bijector = unconstraining_bijectors
	)
	kernel2 = tfp.mcmc.DualAveragingStepSizeAdaptation( # pkr = previous kernel results
		inner_kernel = kernel1,
		num_adaptation_steps = int(0.8*burnin),
		step_size_setter_fn = lambda pkr, new_step_size: pkr._replace(inner_results = pkr.inner_results._replace(step_size=new_step_size)),
		step_size_getter_fn = lambda pkr: pkr.inner_results.step_size,
		log_accept_prob_getter_fn = lambda pkr: pkr.inner_results.log_accept_ratio
	)
	# tf.get_logger().setLevel("ERROR") # multiple chains
	return tfp.mcmc.sample_chain( # ATTENTION: 2 values to unpack
		num_results = num_steps,
		num_burnin_steps = burnin,
		current_state = init_state,
		kernel = kernel2,
		trace_fn = trace_fn
	)

nchain = 4
init_state = [mdl_batch.sample(nchain)._asdict()[_] for _ in var_name]
# Since HMC operates over unconstrained space, we need to transform the samples so they live in real-space.
# α ≈ 100×ß, so apply bijector to 100× the unconstrained α to get back to the original problem space
unconstraining_bijectors = [tfb.Scale(100.), tfb.Identity()]
samples, sampler_stat = run_mcmc(init_state, unconstraining_bijectors)

#%% using the pymc3 naming convention, with log_likelihood instead of lp so that ArviZ can compute loo and waic
sample_stats_name = ['log_likelihood', 'tree_size', 'diverging', 'energy', 'mean_tree_accept']

sample_stats = {k: v.numpy().T for k, v in zip(sample_stats_name, sampler_stat)}
posterior = {k: np.swapaxes(v.numpy(), 1, 0) for k, v in zip(var_name, samples)}
az_trace = az.from_dict(posterior=posterior, sample_stats=sample_stats)

az.summary(az_trace)
az.plot_trace(az_trace)

max_stars_repo_path: orig TFP code forked/TFPchap2ex4.py

max_issues_repo_path: orig TFP code forked/TFPchap2ex4.py

max_forks_repo_path: orig TFP code forked/TFPchap2ex4.py


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: InfoGAN-mnist.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>

import numpy as np
import tensorflow as tf
import os, sys
import cv2
import argparse

from tensorpack import *
from tensorpack.utils.viz import *
import tensorpack.tfutils.symbolic_functions as symbf
from GAN import GANTrainer, build_GAN_losses

BATCH = 128

class Model(ModelDesc):
    def _get_input_vars(self):
        return [InputVar(tf.float32, (None, 28, 28), 'input') ]

    def generator(self, z):
        l = FullyConnected('fc0', z, 1024, nl=BNReLU)
        l = FullyConnected('fc1', l, 128 * 7 * 7, nl=BNReLU)
        l = tf.reshape(l, [-1, 7, 7, 128])
        l = Deconv2D('deconv1', l, [14, 14, 64], 4, 2, nl=BNReLU)
        l = Deconv2D('deconv2', l, [28, 28, 1], 4, 2, nl=tf.identity)
        l = tf.nn.tanh(l, name='gen')
        return l

    def discriminator(self, imgs):
        """ return a (b, 1) logits"""
        with argscope(Conv2D, nl=tf.identity, kernel_shape=4, stride=2), \
                argscope(LeakyReLU, alpha=0.2):
            l = (LinearWrap(imgs)
                .Conv2D('conv0', 64)
                .LeakyReLU()
                .Conv2D('conv1', 128)
                .BatchNorm('bn1').LeakyReLU()
                .FullyConnected('fc1', 1024, nl=tf.identity)
                .BatchNorm('bn2').LeakyReLU()())

            logits = FullyConnected('fct', l, 1, nl=tf.identity)
            encoder = (LinearWrap(l)
                    .FullyConnected('fce1', 128, nl=tf.identity)
                    .BatchNorm('bne').LeakyReLU()
                    .FullyConnected('fce-out', 10, nl=tf.identity)())
        return logits, encoder

    def _build_graph(self, input_vars):
        image_pos = input_vars[0]
        image_pos = tf.expand_dims(image_pos * 2.0 - 1, -1)

        prior_prob = tf.constant([0.1] * 10, name='prior_prob')
        # assume first 10 is categorical
        ids = tf.multinomial(tf.zeros([BATCH, 10]), num_samples=1)[:,0]
        zc = tf.one_hot(ids, 10, name='zc_train')
        zc = tf.placeholder_with_default(zc, [None, 10], name='zc')

        z = tf.random_uniform(tf.pack([tf.shape(zc)[0], 90]), -1, 1, name='z_train')
        z = tf.placeholder_with_default(z, [None, 90], name='z')
        z = tf.concat(1, [zc, z], name='fullz')

        with argscope([Conv2D, Deconv2D, FullyConnected],
                W_init=tf.truncated_normal_initializer(stddev=0.02)):
            with tf.variable_scope('gen'):
                image_gen = self.generator(z)
                tf.image_summary('gen', image_gen, max_images=30)
            with tf.variable_scope('discrim'):
                vecpos, _ = self.discriminator(image_pos)
            with tf.variable_scope('discrim', reuse=True):
                vecneg, dist_param = self.discriminator(image_gen)
                logprob = tf.nn.log_softmax(dist_param) # log prob of each category

        # Q(c|x) = Q(zc | image_gen)
        log_qc_given_x = tf.reduce_sum(logprob * zc, 1, name='logQc_x') # bx1
        log_qc = tf.reduce_sum(prior_prob * zc, 1, name='logQc')
        Elog_qc_given_x = tf.reduce_mean(log_qc_given_x, name='ElogQc_x')
        Hc = tf.reduce_mean(-log_qc, name='Hc')
        MIloss = tf.mul(Hc + Elog_qc_given_x, -1.0, name='neg_MI')

        self.g_loss, self.d_loss = build_GAN_losses(vecpos, vecneg)
        self.g_loss = tf.add(self.g_loss, MIloss, name='total_g_loss')
        self.d_loss = tf.add(self.d_loss, MIloss, name='total_d_loss')
        summary.add_moving_summary(MIloss, self.g_loss, self.d_loss, Hc, Elog_qc_given_x)

        all_vars = tf.trainable_variables()
        self.g_vars = [v for v in all_vars if v.name.startswith('gen/')]
        self.d_vars = [v for v in all_vars if v.name.startswith('discrim/')]

def get_data():
    ds = ConcatData([dataset.Mnist('train'), dataset.Mnist('test')])
    ds = BatchData(ds, BATCH)
    return ds

def get_config():
    logger.auto_set_dir()
    dataset = get_data()
    lr = symbf.get_scalar_var('learning_rate', 2e-4, summary=True)
    return TrainConfig(
        dataset=dataset,
        optimizer=tf.train.AdamOptimizer(lr, beta1=0.5, epsilon=1e-3),
        callbacks=Callbacks([
            StatPrinter(), ModelSaver(),
        ]),
        session_config=get_default_sess_config(0.5),
        model=Model(),
        step_per_epoch=500,
        max_epoch=100,
    )

def sample(model_path):
    pred = OfflinePredictor(PredictConfig(
       session_init=get_model_loader(model_path),
       model=Model(),
       input_names=['zc'],
       output_names=['gen/gen']))

    eye = []
    for k in np.eye(10):
        eye = eye + [k] * 10
    inputs = np.asarray(eye)
    while True:
        o = pred([inputs])
        o = (o[0] + 1) * 128.0
        viz = next(build_patch_list(o, nr_row=10, nr_col=10))
        viz = cv2.resize(viz, (800, 800))
        interactive_imshow(viz)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu', help='comma separated list of GPU(s) to use.')
    parser.add_argument('--load', help='load model')
    parser.add_argument('--sample', action='store_true', help='visualize the space of the 10 latent codes')
    args = parser.parse_args()
    if args.gpu:
        os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
    if args.sample:
        sample(args.load)
    else:
        config = get_config()
        if args.load:
            config.session_init = SaverRestore(args.load)
        GANTrainer(config).train()

max_stars_repo_name: laceyg/ternarynet

max_issues_repo_name: laceyg/ternarynet

max_forks_repo_name: laceyg/ternarynet


text:
import numpy as np
import numpy.linalg as la
import scipy.linalg as sla
import matplotlib.pyplot as plt

P33 = np.array([[0.5, 0.5, 0.0],
                [0.0, 0.0, 1.0],
                [1.0, 0.0, 0.0]])
P44 = np.array([1])

P22 = sla.block_diag(P33, P44)

P11 = np.array([[0.4, 0.0, 0.0],
                [0.0, 0.3, 0.6],
                [0.0, 0.6, 0.2]])
P12 = np.array([[0.3, 0.0, 0.0, 0.3],
                [0.0, 0.0, 0.0, 0.1],
                [0.2, 0.0, 0.0, 0.0]])
P21 = np.zeros([4, 3])

P = np.block([[P11, P12],
              [P21, P22]])

Pss = la.matrix_power(P, 1000)
fig, ax = plt.subplots()
ax.pcolormesh(Pss, edgecolor='w')
ax.invert_yaxis()
ax.set_aspect('equal')

max_stars_repo_name: BenGravell/optimal-control-course

max_issues_repo_name: BenGravell/optimal-control-course

max_forks_repo_name: BenGravell/optimal-control-course