repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
yucoian/OpenQA | [
"3316c1d4e4c57881a32453069d0ea23bf2fe6f5e"
]
| [
"main.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Main OpenQA training and testing script.\"\"\"\n\nimport argparse\nimport torch\nimport numpy as np\nimport json\nimport os\nimport sys\nimport subprocess\nimport logging\nimport random\n\nimport regex as re\n\nsys_dir = '/data/disk2/private/linyankai/OpenQA'\nsys.path.append(sys_dir)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='4'\nfrom src.reader import utils, vector, config, data\nfrom src.reader import DocReader\nfrom src import DATA_DIR as DRQA_DATA\nfrom src.retriever.utils import normalize\nfrom src.reader.data import Dictionary\n\n\nfrom src import tokenizers\nfrom multiprocessing.util import Finalize\ntokenizers.set_default('corenlp_classpath', sys_dir+'/data/corenlp/*')\nPROCESS_TOK = None\n\n\n\nlogger = logging.getLogger()\n\n\n# ------------------------------------------------------------------------------\n# Training arguments.\n# ------------------------------------------------------------------------------\n\n\n# Defaults\nDATA_DIR = os.path.join(DRQA_DATA, 'datasets')\nMODEL_DIR = 'models' \nEMBED_DIR = sys_dir+'/data/embeddings/' \n\ndef str2bool(v):\n return v.lower() in ('yes', 'true', 't', '1', 'y')\n\n\ndef add_train_args(parser):\n \"\"\"Adds commandline arguments pertaining to training a model. These\n are different from the arguments dictating the model architecture.\n \"\"\"\n parser.register('type', 'bool', str2bool)\n\n # Runtime environment\n runtime = parser.add_argument_group('Environment')\n runtime.add_argument('--dataset', type=str, default=\"searchqa\",\n help='Dataset: searchqa, quasart or unftriviaqa')\n\n runtime.add_argument('--mode', type=str, default=\"all\",\n help='Train_mode: all, reader or selector')\n runtime.add_argument('--no-cuda', type='bool', default=False,\n help='Train on CPU, even if GPUs are available.')\n runtime.add_argument('--gpu', type=int, default=-1,\n help='Run on a specific GPU')\n runtime.add_argument('--data-workers', type=int, default=1,\n help='Number of subprocesses for data loading')\n runtime.add_argument('--parallel', type='bool', default=False,\n help='Use DataParallel on all available GPUs')\n runtime.add_argument('--random-seed', type=int, default=1012,\n help=('Random seed for all numpy/torch/cuda '\n 'operations (for reproducibility)'))\n runtime.add_argument('--num-epochs', type=int, default=20,\n help='Train data iterations')\n runtime.add_argument('--batch-size', type=int, default=128,\n help='Batch size for training')\n runtime.add_argument('--test-batch-size', type=int, default=64,\n help='Batch size during validation/testing')\n\n # Files\n files = parser.add_argument_group('Filesystem')\n files.add_argument('--model-dir', type=str, default=MODEL_DIR,\n help='Directory for saved models/checkpoints/logs')\n files.add_argument('--model-name', type=str, default='SQuAD.ckpt_tmp',\n help='Unique model identifier (.mdl, .txt, .checkpoint)')\n files.add_argument('--data-dir', type=str, default=DATA_DIR,\n help='Directory of training/validation data')\n files.add_argument('--embed-dir', type=str, default=EMBED_DIR,\n help='Directory of pre-trained embedding files')\n files.add_argument('--embedding-file', type=str,\n default='glove.840B.300d.txt',\n help='Space-separated pretrained embeddings file')\n\n # Saving + loading\n save_load = parser.add_argument_group('Saving/Loading')\n save_load.add_argument('--checkpoint', type='bool', default=False,\n help='Save model + optimizer state after each epoch')\n save_load.add_argument('--pretrained', type=str, default= None, #'models/SQuAD.ckpt.mdl',#'data/reader/multitask.mdl\n help='Path to a pretrained model to warm-start with')\n save_load.add_argument('--expand-dictionary', type='bool', default=False,\n help='Expand dictionary of pretrained model to ' +\n 'include training/dev words of new data')\n # Data preprocessing\n preprocess = parser.add_argument_group('Preprocessing')\n preprocess.add_argument('--uncased-question', type='bool', default=False,\n help='Question words will be lower-cased')\n preprocess.add_argument('--uncased-doc', type='bool', default=False,\n help='Document words will be lower-cased')\n preprocess.add_argument('--restrict-vocab', type='bool', default=True,\n help='Only use pre-trained words in embedding_file')\n\n # General\n general = parser.add_argument_group('General')\n general.add_argument('--official-eval', type='bool', default=True,\n help='Validate with official SQuAD eval')\n general.add_argument('--valid-metric', type=str, default='exact_match',\n help='If using official evaluation: f1; else: exact_match')\n general.add_argument('--display-iter', type=int, default=25,\n help='Log state after every <display_iter> epochs')\n general.add_argument('--sort-by-len', type='bool', default=True,\n help='Sort batches by length for speed')\n\n\ndef set_defaults(args):\n \"\"\"Make sure the commandline arguments are initialized properly.\"\"\"\n # Check critical files exist\n if args.embedding_file:\n args.embedding_file = os.path.join(args.embed_dir, args.embedding_file)\n if not os.path.isfile(args.embedding_file):\n raise IOError('No such file: %s' % args.embedding_file)\n\n # Set model directory\n subprocess.call(['mkdir', '-p', args.model_dir])\n\n # Set model name\n if not args.model_name:\n import uuid\n import time\n args.model_name = time.strftime(\"%Y%m%d-\") + str(uuid.uuid4())[:8]\n\n # Set log + model file names\n args.log_file = os.path.join(args.model_dir, args.model_name + '.txt')\n args.model_file = os.path.join(args.model_dir, args.model_name + '.mdl')\n\n # Embeddings options\n if args.embedding_file:\n with open(args.embedding_file) as f:\n dim = len(f.readline().strip().split(' ')) - 1\n args.embedding_dim = dim\n elif not args.embedding_dim:\n raise RuntimeError('Either embedding_file or embedding_dim '\n 'needs to be specified.')\n\n # Make sure tune_partial and fix_embeddings are consistent.\n if args.tune_partial > 0 and args.fix_embeddings:\n logger.warning('WARN: fix_embeddings set to False as tune_partial > 0.')\n args.fix_embeddings = False\n\n # Make sure fix_embeddings and embedding_file are consistent\n if args.fix_embeddings:\n if not (args.embedding_file or args.pretrained):\n logger.warning('WARN: fix_embeddings set to False '\n 'as embeddings are random.')\n args.fix_embeddings = False\n return args\n\n\n# ------------------------------------------------------------------------------\n# Initalization from scratch.\n# ------------------------------------------------------------------------------\n\n\ndef init_from_scratch(args, train_docs):\n \"\"\"New model, new data, new dictionary.\"\"\"\n # Create a feature dict out of the annotations in the data\n logger.info('-' * 100)\n logger.info('Generate features')\n feature_dict = utils.build_feature_dict(args)\n logger.info('Num features = %d' % len(feature_dict))\n logger.info(feature_dict)\n\n # Build a dictionary from the data questions + words (train/dev splits)\n logger.info('-' * 100)\n logger.info('Build dictionary')\n word_dict = utils.build_word_dict_docs(args, train_docs)\n\n logger.info('Num words = %d' % len(word_dict))\n\n # Initialize model\n model = DocReader(config.get_model_args(args), word_dict, feature_dict)\n\n # Load pretrained embeddings for words in dictionary\n if args.embedding_file:\n model.load_embeddings(word_dict.tokens(), args.embedding_file)\n\n return model\n\n\n# ------------------------------------------------------------------------------\n# Train loop.\n# ------------------------------------------------------------------------------\n\ndef train(args, data_loader, model, global_stats, exs_with_doc, docs_by_question):\n \"\"\"Run through one epoch of model training with the provided data loader.\"\"\"\n # Initialize meters + timers\n train_loss = utils.AverageMeter()\n epoch_time = utils.Timer()\n # Run one epoch\n update_step = 0\n for idx, ex_with_doc in enumerate(data_loader):\n ex = ex_with_doc[0]\n batch_size, question, ex_id = ex[0].size(0), ex[3], ex[-1]\n if (idx not in HasAnswer_Map):\n HasAnswer_list = []\n for idx_doc in range(0, vector.num_docs):\n HasAnswer = []\n for i in range(batch_size):\n HasAnswer.append(has_answer(args, exs_with_doc[ex_id[i]]['answer'], docs_by_question[ex_id[i]][idx_doc%len(docs_by_question[ex_id[i]])][\"document\"]))\n HasAnswer_list.append(HasAnswer)\n HasAnswer_Map[idx] = HasAnswer_list\n else:\n HasAnswer_list = HasAnswer_Map[idx]\n\n weights = []\n for idx_doc in range(0, vector.num_docs):\n weights.append(1)\n weights = torch.Tensor(weights)\n idx_random = torch.multinomial(weights, int(vector.num_docs))\n\n HasAnswer_list_sample = []\n ex_with_doc_sample = []\n for idx_doc in idx_random:\n HasAnswer_list_sample.append(HasAnswer_list[idx_doc])\n ex_with_doc_sample.append(ex_with_doc[idx_doc])\n\n l_list_doc = []\n r_list_doc = []\n for idx_doc in idx_random:\n l_list = []\n r_list = []\n for i in range(batch_size):\n if HasAnswer_list[idx_doc][i][0]:\n l_list.append(HasAnswer_list[idx_doc][i][1])\n else:\n l_list.append((-1,-1))\n l_list_doc.append(l_list)\n r_list_doc.append(r_list)\n pred_s_list_doc = []\n pred_e_list_doc = []\n tmp_top_n = 1\n for idx_doc in idx_random:\n ex = ex_with_doc[idx_doc]\n pred_s, pred_e, pred_score = model.predict(ex,top_n = tmp_top_n)\n pred_s_list = []\n pred_e_list = []\n for i in range(batch_size):\n pred_s_list.append(pred_s[i].tolist())\n pred_e_list.append(pred_e[i].tolist())\n pred_s_list_doc.append(torch.LongTensor(pred_s_list))\n pred_e_list_doc.append(torch.LongTensor(pred_e_list))\n\n train_loss.update(*model.update_with_doc(update_step, ex_with_doc_sample, pred_s_list_doc, pred_e_list_doc, tmp_top_n, l_list_doc,r_list_doc,HasAnswer_list_sample))\n update_step = (update_step + 1) % 4\n if idx % args.display_iter == 0:\n logger.info('train: Epoch = %d | iter = %d/%d | ' %\n (global_stats['epoch'], idx, len(data_loader)) +\n 'loss = %.2f | elapsed time = %.2f (s)' %\n (train_loss.avg, global_stats['timer'].time()))\n train_loss.reset()\n if (idx%200==199):\n validate_unofficial_with_doc(args, data_loader, model, global_stats, exs_with_doc, docs_by_question, 'train')\n logger.info('train: Epoch %d done. Time for epoch = %.2f (s)' %\n (global_stats['epoch'], epoch_time.time()))\n\n # Checkpoint\n if args.checkpoint:\n model.checkpoint(args.model_file + '.checkpoint',\n global_stats['epoch'] + 1)\n\nHasAnswer_Map = {}\ndef pretrain_selector(args, data_loader, model, global_stats, exs_with_doc, docs_by_question):\n \"\"\"Run through one epoch of model training with the provided data loader.\"\"\"\n # Initialize meters + timers\n train_loss = utils.AverageMeter()\n epoch_time = utils.Timer()\n # Run one epoch\n tot_ans = 0\n tot_num = 0\n global HasAnswer_Map\n for idx, ex_with_doc in enumerate(data_loader):\n ex = ex_with_doc[0]\n batch_size, question, ex_id = ex[0].size(0), ex[3], ex[-1]\n if (idx not in HasAnswer_Map):\n HasAnswer_list = []\n for idx_doc in range(0, vector.num_docs):\n HasAnswer = []\n for i in range(batch_size):\n has_a, a_l = has_answer(args, exs_with_doc[ex_id[i]]['answer'], docs_by_question[ex_id[i]][idx_doc%len(docs_by_question[ex_id[i]])][\"document\"])\n HasAnswer.append(has_a)\n HasAnswer_list.append(HasAnswer)\n #HasAnswer_list = torch.LongTensor(HasAnswer_list)\n HasAnswer_Map[idx] = HasAnswer_list\n else:\n HasAnswer_list = HasAnswer_Map[idx]\n for idx_doc in range(0, vector.num_docs):\n for i in range(batch_size):\n tot_ans+=HasAnswer_list[idx_doc][i]\n tot_num+=1\n\n weights = []\n for idx_doc in range(0, vector.num_docs):\n weights.append(1)\n weights = torch.Tensor(weights)\n idx_random = torch.multinomial(weights, int(vector.num_docs))\n\n HasAnswer_list_sample = []\n ex_with_doc_sample = []\n for idx_doc in idx_random:\n HasAnswer_list_sample.append(HasAnswer_list[idx_doc])\n ex_with_doc_sample.append(ex_with_doc[idx_doc])\n HasAnswer_list_sample = torch.LongTensor(HasAnswer_list_sample)\n\n train_loss.update(*model.pretrain_selector(ex_with_doc_sample, HasAnswer_list_sample))\n #train_loss.update(*model.pretrain_ranker(ex_with_doc, HasAnswer_list))\n if idx % args.display_iter == 0:\n logger.info('train: Epoch = %d | iter = %d/%d | ' %\n (global_stats['epoch'], idx, len(data_loader)) +\n 'loss = %.2f | elapsed time = %.2f (s)' %\n (train_loss.avg, global_stats['timer'].time()))\n logger.info(\"tot_ans:\\t%d\\t%d\\t%f\", tot_ans, tot_num, tot_ans*1.0/tot_num)\n train_loss.reset()\n logger.info(\"tot_ans:\\t%d\\t%d\", tot_ans, tot_num)\n logger.info('train: Epoch %d done. Time for epoch = %.2f (s)' %\n (global_stats['epoch'], epoch_time.time()))\n\ndef pretrain_reader(args, data_loader, model, global_stats, exs_with_doc, docs_by_question):\n \"\"\"Run through one epoch of model training with the provided data loader.\"\"\"\n # Initialize meters + timers\n train_loss = utils.AverageMeter()\n epoch_time = utils.Timer()\n logger.info(\"pretrain_reader\")\n # Run one epoch\n global HasAnswer_Map\n count_ans = 0\n count_tot = 0\n for idx, ex_with_doc in enumerate(data_loader):\n #logger.info(idx)\n ex = ex_with_doc[0]\n batch_size, question, ex_id = ex[0].size(0), ex[3], ex[-1]\n if (idx not in HasAnswer_Map):\n HasAnswer_list = []\n for idx_doc in range(0, vector.num_docs):\n HasAnswer = []\n for i in range(batch_size):\n HasAnswer.append(has_answer(args,exs_with_doc[ex_id[i]]['answer'], docs_by_question[ex_id[i]][idx_doc%len(docs_by_question[ex_id[i]])][\"document\"]))\n HasAnswer_list.append(HasAnswer)\n HasAnswer_Map[idx] = HasAnswer_list\n else:\n HasAnswer_list = HasAnswer_Map[idx]\n \n for idx_doc in range(0, vector.num_docs):\n l_list = []\n r_list = []\n pred_s, pred_e, pred_score = model.predict(ex_with_doc[idx_doc],top_n = 1)\n for i in range(batch_size):\n if HasAnswer_list[idx_doc][i][0]:\n count_ans+=len(HasAnswer_list[idx_doc][i][1])\n count_tot+=1\n l_list.append(HasAnswer_list[idx_doc][i][1])\n else:\n l_list.append([(int(pred_s[i][0]),int(pred_e[i][0]))])\n train_loss.update(*model.update(ex_with_doc[idx_doc], l_list, r_list, HasAnswer_list[idx_doc])) \n if idx % args.display_iter == 0:\n logger.info('train: Epoch = %d | iter = %d/%d | ' %\n (global_stats['epoch'], idx, len(data_loader)) +\n 'loss = %.2f | elapsed time = %.2f (s)' %\n (train_loss.avg, global_stats['timer'].time()))\n train_loss.reset()\n logger.info(\"%d\\t%d\\t%f\", count_ans, count_tot, 1.0*count_ans/(count_tot+1))\n logger.info('train: Epoch %d done. Time for epoch = %.2f (s)' %\n (global_stats['epoch'], epoch_time.time()))\n\ndef has_answer(args, answer, t):\n global PROCESS_TOK\n text = []\n for i in range(len(t)):\n text.append(t[i].lower())\n res_list = []\n if (args.dataset == \"CuratedTrec\"):\n try:\n ans_regex = re.compile(\"(%s)\"%answer[0], flags=re.IGNORECASE + re.UNICODE)\n except:\n return False, res_list\n paragraph = \" \".join(text)\n answer_new = ans_regex.findall(paragraph)\n for a in answer_new:\n single_answer = normalize(a[0])\n single_answer = PROCESS_TOK.tokenize(single_answer)\n single_answer = single_answer.words(uncased=True)\n for i in range(0, len(text) - len(single_answer) + 1):\n if single_answer == text[i: i + len(single_answer)]:\n res_list.append((i, i+len(single_answer)-1))\n else:\n for a in answer:\n single_answer = \" \".join(a).lower()\n single_answer = normalize(single_answer)\n single_answer = PROCESS_TOK.tokenize(single_answer)\n single_answer = single_answer.words(uncased=True)\n for i in range(0, len(text) - len(single_answer) + 1):\n if single_answer == text[i: i + len(single_answer)]:\n res_list.append((i, i+len(single_answer)-1))\n if (len(res_list)>0):\n return True, res_list\n else:\n return False, res_list\n\n\ndef set_sim(answer, prediction):\n\n ground_truths = []\n for a in answer:\n ground_truths.append(\" \".join([w for w in a]))\n\n res = utils.metric_max_over_ground_truths(\n utils.f1_score, prediction, ground_truths)\n return res\n\n\n# ------------------------------------------------------------------------------\n# Validation loops. Includes both \"unofficial\" and \"official\" functions that\n# use different metrics and implementations.\n# ------------------------------------------------------------------------------\n\n\n\n\ndef validate_unofficial_with_doc(args, data_loader, model, global_stats, exs_with_doc, docs_by_question, mode):\n \"\"\"Run one full unofficial validation with docs.\n Unofficial = doesn't use SQuAD script.\n \"\"\"\n eval_time = utils.Timer()\n f1 = utils.AverageMeter()\n exact_match = utils.AverageMeter()\n\n out_set = set({33,42,45,70,39})\n logger.info(\"validate_unofficial_with_doc\")\n # Run through examples\n\n examples = 0 \n aa = [0.0 for i in range(vector.num_docs)]\n bb = [0.0 for i in range(vector.num_docs)]\n aa_sum = 0.0\n display_num = 10\n for idx, ex_with_doc in enumerate(data_loader):\n ex = ex_with_doc[0]\n batch_size, question, ex_id = ex[0].size(0), ex[3], ex[-1]\n scores_doc_num = model.predict_with_doc(ex_with_doc)\n scores = [{} for i in range(batch_size)]\n\n tot_sum = [0.0 for i in range(batch_size)]\n tot_sum1 = [0.0 for i in range(batch_size)]\n neg_sum = [0.0 for i in range(batch_size)]\n min_sum = [[] for i in range(batch_size)]\n min_sum1 =[[] for i in range(batch_size)]\n \n for idx_doc in range(0, vector.num_docs):\n ex = ex_with_doc[idx_doc]\n pred_s, pred_e, pred_score = model.predict(ex,top_n = 10)\n for i in range(batch_size):\n doc_text = docs_by_question[ex_id[i]][idx_doc%len(docs_by_question[ex_id[i]])][\"document\"]\n has_answer_t = has_answer(args, exs_with_doc[ex_id[i]]['answer'], doc_text)\n\n for k in range(10):\n try:\n prediction = []\n for j in range(pred_s[i][k], pred_e[i][k]+1):\n prediction.append(doc_text[j])\n prediction = \" \".join(prediction).lower()\n if (prediction not in scores[i]):\n scores[i][prediction] = 0\n scores[i][prediction] += pred_score[i][k]*scores_doc_num[i][idx_doc]\n except:\n pass\n for i in range(batch_size):\n _, indices = scores_doc_num[i].sort(0, descending = True)\n for j in range(0, display_num):\n idx_doc = indices[j]\n doc_text = docs_by_question[ex_id[i]][idx_doc%len(docs_by_question[ex_id[i]])][\"document\"]\n if (has_answer(args, exs_with_doc[ex_id[i]]['answer'], doc_text)[0]):\n\n aa[j]= aa[j] + 1\n bb[j]= bb[j]+1\n\n for i in range(batch_size):\n \n best_score = 0\n prediction = \"\"\n for key in scores[i]:\n if (scores[i][key]>best_score):\n best_score = scores[i][key]\n prediction = key\n \n # Compute metrics\n ground_truths = []\n answer = exs_with_doc[ex_id[i]]['answer']\n if (args.dataset == \"CuratedTrec\"):\n ground_truths = answer\n else:\n for a in answer:\n ground_truths.append(\" \".join([w for w in a]))\n #logger.info(prediction)\n #logger.info(ground_truths)\n exact_match.update(utils.metric_max_over_ground_truths(\n utils.exact_match_score, prediction, ground_truths))\n f1.update(utils.metric_max_over_ground_truths(\n utils.f1_score, prediction, ground_truths))\n a = sorted(scores[i].items(), key=lambda d: d[1], reverse = True) \n\n examples += batch_size\n if (mode==\"train\" and examples>=1000):\n break\n try:\n for j in range(0, display_num):\n if (j>0):\n aa[j]= aa[j]+aa[j-1]\n bb[j]= bb[j]+bb[j-1]\n logger.info(aa[j]/bb[j])\n except:\n pass\n logger.info('%s valid official with doc: Epoch = %d | EM = %.2f | ' %\n (mode, global_stats['epoch'], exact_match.avg * 100) +\n 'F1 = %.2f | examples = %d | valid time = %.2f (s)' %\n (f1.avg * 100, examples, eval_time.time()))\n\n return {'exact_match': exact_match.avg * 100, 'f1': f1.avg * 100}\n\n\ndef eval_accuracies(pred_s, target_s, pred_e, target_e):\n \"\"\"An unofficial evalutation helper.\n Compute exact start/end/complete match accuracies for a batch.\n \"\"\"\n # Convert 1D tensors to lists of lists (compatibility)\n if torch.is_tensor(target_s):\n target_s = [[e] for e in target_s]\n target_e = [[e] for e in target_e]\n\n # Compute accuracies from targets\n batch_size = len(pred_s)\n start = utils.AverageMeter()\n end = utils.AverageMeter()\n em = utils.AverageMeter()\n for i in range(batch_size):\n # Start matches\n if pred_s[i] in target_s[i]:\n start.update(1)\n else:\n start.update(0)\n\n # End matches\n if pred_e[i] in target_e[i]:\n end.update(1)\n else:\n end.update(0)\n\n # Both start and end match\n if any([1 for _s, _e in zip(target_s[i], target_e[i])\n if _s == pred_s[i] and _e == pred_e[i]]):\n em.update(1)\n else:\n em.update(0)\n return start.avg * 100, end.avg * 100, em.avg * 100\n\n\n# ------------------------------------------------------------------------------\n# Main.\n# ------------------------------------------------------------------------------\n\n\ndef read_data(filename, keys):\n res = []\n step = 0\n for line in open(filename):\n data = json.loads(line)\n if ('squad' in filename or 'webquestions' in filename):\n answer = [tokenize_text(a).words() for a in data['answer']]\n else:\n if ('CuratedTrec' in filename):\n answer = data['answer']\n else:\n answer = [tokenize_text(a).words() for a in data['answers']]\n question = \" \".join(tokenize_text(data['question']).words())\n res.append({\"answer\":answer, \"question\":question})\n step+=1\n return res\n \n\ndef tokenize_text(text):\n global PROCESS_TOK\n return PROCESS_TOK.tokenize(text)\n\ndef main(args):\n # --------------------------------------------------------------------------\n # TOK\n global PROCESS_TOK\n tok_class = tokenizers.get_class(\"corenlp\")\n tok_opts = {}\n PROCESS_TOK = tok_class(**tok_opts)\n Finalize(PROCESS_TOK, PROCESS_TOK.shutdown, exitpriority=100)\n\n # DATA\n logger.info('-' * 100)\n logger.info('Load data files')\n dataset = args.dataset#'quasart'#'searchqa'#'unftriviaqa'#'squad'#\n filename_train_docs = sys_dir+\"/data/datasets/\"+dataset+\"/train.json\" \n filename_dev_docs = sys_dir+\"/data/datasets/\"+dataset+\"/dev.json\" \n filename_test_docs = sys_dir+\"/data/datasets/\"+dataset+\"/test.json\" \n train_docs, train_questions = utils.load_data_with_doc(args, filename_train_docs)\n logger.info(len(train_docs))\n filename_train = sys_dir+\"/data/datasets/\"+dataset+\"/train.txt\" \n filename_dev = sys_dir+\"/data/datasets/\"+dataset+\"/dev.txt\" \n train_exs_with_doc = read_data(filename_train, train_questions)\n\n logger.info('Num train examples = %d' % len(train_exs_with_doc))\n\n dev_docs, dev_questions = utils.load_data_with_doc(args, filename_dev_docs)\n logger.info(len(dev_docs))\n dev_exs_with_doc = read_data(filename_dev, dev_questions)\n logger.info('Num dev examples = %d' % len(dev_exs_with_doc))\n\n test_docs, test_questions = utils.load_data_with_doc(args, filename_test_docs)\n logger.info(len(test_docs))\n test_exs_with_doc = read_data(sys_dir+\"/data/datasets/\"+dataset+\"/test.txt\", test_questions)\n logger.info('Num dev examples = %d' % len(test_exs_with_doc))\n \n # --------------------------------------------------------------------------\n # MODEL\n logger.info('-' * 100)\n start_epoch = 0\n if args.checkpoint and os.path.isfile(args.model_file + '.checkpoint'):\n # Just resume training, no modifications.\n logger.info('Found a checkpoint...')\n checkpoint_file = args.model_file + '.checkpoint'\n model, start_epoch = DocReader.load_checkpoint(checkpoint_file)\n #model = DocReader.load(checkpoint_file, args)\n start_epoch = 0\n else:\n # Training starts fresh. But the model state is either pretrained or\n # newly (randomly) initialized.\n if args.pretrained:\n logger.info('Using pretrained model...')\n model = DocReader.load(args.pretrained, args)\n if args.expand_dictionary:\n logger.info('Expanding dictionary for new data...')\n # Add words in training + dev examples\n words = utils.load_words(args, train_exs + dev_exs)\n added = model.expand_dictionary(words)\n # Load pretrained embeddings for added words\n if args.embedding_file:\n model.load_embeddings(added, args.embedding_file)\n\n else:\n logger.info('Training model from scratch...')\n model = init_from_scratch(args, train_docs)#, train_exs, dev_exs)\n\n # Set up optimizer\n model.init_optimizer()\n\n # Use the GPU?\n if args.cuda:\n model.cuda()\n\n # Use multiple GPUs?\n if args.parallel:\n model.parallelize()\n\n # --------------------------------------------------------------------------\n # DATA ITERATORS\n # Two datasets: train and dev. If we sort by length it's faster.\n logger.info('-' * 100)\n logger.info('Make data loaders')\n\n\n train_dataset_with_doc = data.ReaderDataset_with_Doc(train_exs_with_doc, model, train_docs, single_answer=True)\n train_sampler_with_doc = torch.utils.data.sampler.SequentialSampler(train_dataset_with_doc)\n train_loader_with_doc = torch.utils.data.DataLoader(\n train_dataset_with_doc,\n batch_size=args.batch_size,\n sampler=train_sampler_with_doc,\n num_workers=args.data_workers,\n collate_fn=vector.batchify_with_docs,\n pin_memory=args.cuda,\n )\n\n dev_dataset_with_doc = data.ReaderDataset_with_Doc(dev_exs_with_doc, model, dev_docs, single_answer=False)\n dev_sampler_with_doc = torch.utils.data.sampler.SequentialSampler(dev_dataset_with_doc)\n dev_loader_with_doc = torch.utils.data.DataLoader(\n dev_dataset_with_doc,\n batch_size=args.test_batch_size,\n sampler=dev_sampler_with_doc,\n num_workers=args.data_workers,\n collate_fn=vector.batchify_with_docs,\n pin_memory=args.cuda,\n )\n\n test_dataset_with_doc = data.ReaderDataset_with_Doc(test_exs_with_doc, model, test_docs, single_answer=False)\n test_sampler_with_doc = torch.utils.data.sampler.SequentialSampler(test_dataset_with_doc)\n test_loader_with_doc = torch.utils.data.DataLoader(\n test_dataset_with_doc,\n batch_size=args.test_batch_size,\n sampler=test_sampler_with_doc,\n num_workers=args.data_workers,\n collate_fn=vector.batchify_with_docs,\n pin_memory=args.cuda,\n )\n\n # -------------------------------------------------------------------------\n # PRINT CONFIG\n logger.info('-' * 100)\n logger.info('CONFIG:\\n%s' %\n json.dumps(vars(args), indent=4, sort_keys=True))\n\n # --------------------------------------------------------------------------\n # TRAIN/VALID LOOP\n logger.info('-' * 100)\n logger.info('Starting training...')\n stats = {'timer': utils.Timer(), 'epoch': 0, 'best_valid': 0}\n\n \n for epoch in range(start_epoch, args.num_epochs):\n stats['epoch'] = epoch\n\n # Train\n if (args.mode == 'all'):\n train(args, train_loader_with_doc, model, stats, train_exs_with_doc, train_docs)\n if (args.mode == 'reader'):\n pretrain_reader(args, train_loader_with_doc, model, stats, train_exs_with_doc, train_docs)\n if (args.mode == 'selector'):\n pretrain_ranker(args, train_loader_with_doc, model, stats, train_exs_with_doc, train_docs)\n \n result = validate_unofficial_with_doc(args, dev_loader_with_doc, model, stats, dev_exs_with_doc, dev_docs, 'dev')\n validate_unofficial_with_doc(args, train_loader_with_doc, model, stats, train_exs_with_doc, train_docs, 'train')\n if (dataset=='webquestions' or dataset=='CuratedTrec'):\n result = validate_unofficial_with_doc(args, test_loader_with_doc, model, stats, test_exs_with_doc, test_docs, 'test')\n else:\n validate_unofficial_with_doc(args, test_loader_with_doc, model, stats, test_exs_with_doc, test_docs, 'test')\n if result[args.valid_metric] > stats['best_valid']:\n logger.info('Best valid: %s = %.2f (epoch %d, %d updates)' %\n (args.valid_metric, result[args.valid_metric],\n stats['epoch'], model.updates))\n model.save(args.model_file)\n stats['best_valid'] = result[args.valid_metric]\n\ndef split_doc(doc):\n \"\"\"Given a doc, split it into chunks (by paragraph).\"\"\"\n GROUP_LENGTH = 0\n curr = []\n curr_len = 0\n for split in regex.split(r'\\n+', doc):\n split = split.strip()\n if len(split) == 0:\n continue\n # Maybe group paragraphs together until we hit a length limit\n if len(curr) > 0 and curr_len + len(split) > GROUP_LENGTH:\n yield ' '.join(curr)\n curr = []\n curr_len = 0\n curr.append(split)\n curr_len += len(split)\n if len(curr) > 0:\n yield ' '.join(curr)\n\n\nif __name__ == '__main__':\n # Parse cmdline args and setup environment\n parser = argparse.ArgumentParser(\n 'DrQA Document Reader',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n add_train_args(parser)\n config.add_model_args(parser)\n args = parser.parse_args()\n set_defaults(args)\n\n # Set cuda\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n if args.cuda:\n torch.cuda.set_device(args.gpu)\n\n # Set random state\n np.random.seed(args.random_seed)\n torch.manual_seed(args.random_seed)\n if args.cuda:\n torch.cuda.manual_seed(args.random_seed)\n\n # Set logging\n logger.setLevel(logging.INFO)\n fmt = logging.Formatter('%(asctime)s: [ %(message)s ]',\n '%m/%d/%Y %I:%M:%S %p')\n console = logging.StreamHandler()\n console.setFormatter(fmt)\n logger.addHandler(console)\n if args.log_file:\n if args.checkpoint:\n logfile = logging.FileHandler(args.log_file, 'a')\n else:\n logfile = logging.FileHandler(args.log_file, 'w')\n logfile.setFormatter(fmt)\n logger.addHandler(logfile)\n logger.info('COMMAND: %s' % ' '.join(sys.argv))\n\n # Run!\n main(args)\n"
]
| [
[
"torch.cuda.manual_seed",
"torch.is_tensor",
"numpy.random.seed",
"torch.manual_seed",
"torch.utils.data.sampler.SequentialSampler",
"torch.cuda.set_device",
"torch.cuda.is_available",
"torch.LongTensor",
"torch.utils.data.DataLoader",
"torch.Tensor"
]
]
|
Himanshirocks/EmbodiedQA | [
"3b93d453f5397108c08b2feeffa9ef21be91fd8d"
]
| [
"data/question-gen/engine.py"
]
| [
"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport csv\nimport random\nimport argparse\nimport operator\nimport numpy as np\nimport os, sys, json\nfrom tqdm import tqdm\nfrom scipy import spatial\nfrom numpy.random import choice\nfrom random import shuffle\n\nfrom house_parse import HouseParse\nfrom question_string_builder import QuestionStringBuilder\n\nfrom nltk.stem import WordNetLemmatizer\n\nrandom.seed(0)\nnp.random.seed(0)\n\nclass roomEntity():\n translations = {\n 'toilet': 'bathroom',\n 'guest room': 'bedroom',\n 'child room': 'bedroom',\n }\n\n def __init__(self, name, bbox, meta):\n self.name = list(\n set([\n self.translations[str(x)]\n if str(x) in self.translations else str(x) for x in name\n ]))\n self.bbox = bbox\n self.meta = meta\n self.type = 'room'\n\n self.name.sort(key=str.lower)\n self.entities = self.objects = []\n\n def addObject(self, object_ent):\n self.objects.append(object_ent)\n\n def isValid(self):\n return len(self.objects) != 0\n\n\nclass objectEntity():\n translations = {\n 'bread': 'food',\n 'hanging_kitchen_cabinet': 'kitchen_cabinet',\n 'teapot': 'kettle',\n 'coffee_kettle': 'kettle',\n 'range_hood_with_cabinet': 'range_hood',\n 'dining_table': 'table',\n 'coffee_table': 'table',\n 'game_table': 'table',\n 'office_chair': 'chair',\n 'bench_chair': 'chair',\n 'chair_set': 'chair',\n 'armchair': 'chair',\n 'fishbowl': 'fish_tank/bowl',\n 'fish_tank': 'fish_tank/bowl',\n 'single_bed': 'bed',\n 'double_bed': 'bed',\n 'baby_bed': 'bed'\n }\n\n def __init__(self, name, bbox, meta, obj_id=False):\n if name in self.translations: self.name = self.translations[name]\n else: self.name = name\n self.bbox = bbox\n self.meta = meta\n self.type = 'object'\n self.id = obj_id\n\n self.entities = self.rooms = []\n\n def addRoom(self, room_ent):\n self.rooms.append(room_ent)\n\n def isValid(self):\n return len(self.rooms) != 0\n\n\nclass Engine():\n '''\n Templates and functional forms.\n '''\n\n template_defs = {\n 'location': [\n 'filter.objects', 'unique.objects', 'blacklist.location',\n 'query.room'\n ],\n 'count': [\n 'filter.rooms', 'unique.rooms', 'filter.objects',\n 'blacklist.count', 'query.count'\n ],\n 'room_count': ['filter.rooms', 'query.room_count'],\n 'global_object_count':\n ['filter.objects', 'blacklist.count', 'query.global_object_count'],\n 'room_object_count':\n ['filter.objects', 'blacklist.exist', 'query.room_object_count'],\n 'exist': [\n 'filter.rooms', 'unique.rooms', 'filter.objects',\n 'blacklist.exist', 'query.exist'\n ],\n 'exist_logical': [\n 'filter.rooms', 'unique.rooms', 'filter.objects',\n 'blacklist.exist', 'query.logical'\n ],\n 'color':\n ['filter.objects', 'unique.objects', 'blacklist.color', 'query.color'],\n 'color_room': [\n 'filter.rooms', 'unique.rooms', 'filter.objects', 'unique.objects',\n 'blacklist.color_room', 'query.color_room'\n ],\n 'relate': [\n 'filter.objects', 'unique.objects', 'blacklist.relate', 'relate',\n 'query.object'\n ],\n 'relate_room': [\n 'filter.rooms', 'unique.rooms', 'filter.objects', 'unique.objects',\n 'blacklist.relate', 'relate', 'query.object_room'\n ],\n 'dist_compare': [\n 'filter.rooms', 'unique.rooms', 'filter.objects', 'unique.objects',\n 'blacklist.dist_compare', 'distance', 'query.compare'\n ]\n }\n\n templates = {\n 'location':\n 'what room <AUX> the <OBJ> located in?',\n 'count':\n 'how many <OBJ-plural> are in the <ROOM>?',\n 'room_count':\n 'how many <ROOM-plural> are in the house?',\n 'room_object_count':\n 'how many rooms in the house have <OBJ-plural> in them?',\n 'global_object_count':\n 'how many <OBJ-plural> are there in all <ROOM-plural> across the house?',\n 'exist':\n '<AUX> there <ARTICLE> <OBJ> in the <ROOM>?',\n 'exist_logic':\n '<AUX> there <ARTICLE> <OBJ1> <LOGIC> <ARTICLE> <OBJ2> in the <ROOM>?',\n 'color':\n 'what color <AUX> the <OBJ>?',\n 'color_room':\n 'what color <AUX> the <OBJ> in the <ROOM>?',\n # prepositions of place\n 'above':\n 'what is above the <OBJ>?',\n 'on':\n 'what is on the <OBJ>?',\n 'below':\n 'what is below the <OBJ>?',\n 'under':\n 'what is under the <OBJ>?',\n 'next_to':\n 'what is next to the <OBJ>?',\n 'above_room':\n 'what is above the <OBJ> in the <ROOM>?',\n 'on_room':\n 'what is on the <OBJ> in the <ROOM>?',\n 'below_room':\n 'what is below the <OBJ> in the <ROOM>?',\n 'under_room':\n 'what is under the <OBJ> in the <ROOM>?',\n 'next_to_room':\n 'what is next to the <OBJ> in the <ROOM>?',\n # object distance comparisons\n 'closer_room':\n 'is the <OBJ> closer to the <OBJ> than to the <OBJ> in the <ROOM>?',\n 'farther_room':\n 'is the <OBJ> farther from the <OBJ> than from the <OBJ> in the <ROOM>?'\n }\n\n blacklist_objects = {\n 'location': [\n 'column', 'door', 'kitchen_cabinet', 'kitchen_set',\n 'hanging_kitchen_cabinet', 'switch', 'range_hood_with_cabinet',\n 'game_table', 'headstone', 'pillow', 'range_oven_with_hood',\n 'glass', 'roof', 'cart', 'window', 'headphones_on_stand', 'coffin',\n 'book', 'toy', 'workplace', 'range_hood', 'trinket', 'ceiling_fan',\n 'beer', 'books', 'magazines', 'shelving', 'partition',\n 'containers', 'container', 'grill', 'stationary_container',\n 'bottle', 'outdoor_seating', 'stand', 'place_setting', 'arch',\n 'household_appliance', 'pet', 'person', 'chandelier', 'decoration'\n ],\n 'count': [\n 'container', 'containers', 'stationary_container', 'switch',\n 'place_setting', 'workplace', 'grill', 'shelving', 'person', 'pet',\n 'chandelier', 'household_appliance', 'decoration', 'trinket',\n 'kitchen_set', 'headstone', 'arch', 'ceiling_fan', 'glass', 'roof',\n 'outdoor_seating', 'stand', 'kitchen_cabinet', 'coffin', 'beer',\n 'book', 'books'\n ],\n 'exist': [\n 'container', 'containers', 'stationary_container', 'decoration',\n 'trinket', 'place_setting', 'workplace', 'grill', 'switch',\n 'window', 'door', 'column', 'person', 'pet', 'chandelier',\n 'household_appliance', 'ceiling_fan', 'arch', 'book', 'books',\n 'glass', 'roof', 'shelving', 'outdoor_seating', 'stand',\n 'kitchen_cabinet', 'kitchen_set', 'coffin', 'headstone', 'beer'\n ],\n 'color': [\n 'container', 'containers', 'stationary_container', 'candle',\n 'coffee_table', 'column', 'door', 'floor_lamp', 'mirror', 'person',\n 'rug', 'sofa', 'stairs', 'outdoor_seating', 'kitchen_cabinet',\n 'kitchen_set', 'switch', 'storage_bench', 'table_lamp', 'vase',\n 'candle', 'roof', 'stand', 'beer', 'chair', 'chandelier',\n 'coffee_table', 'column', 'trinket', 'grill', 'book', 'books',\n 'curtain', 'desk', 'door', 'floor_lamp', 'hanger', 'workplace',\n 'glass', 'headstone', 'kitchen_set', 'mirror', 'plant', 'shelving',\n 'place_setting', 'ceiling_fan', 'stairs', 'storage_bench',\n 'switch', 'table_lamp', 'vase', 'decoration', 'coffin',\n 'wardrobe_cabinet', 'window', 'pet', 'cup', 'arch',\n 'household_appliance'\n ],\n 'color_room': [\n 'column', 'door', 'kitchen_cabinet', 'kitchen_set', 'mirror',\n 'household_appliance', 'decoration', 'place_setting', 'book',\n 'person', 'stairs', 'switch', 'pet', 'chandelier', 'container',\n 'containers', 'stationary_container', 'trinket', 'coffin', 'books',\n 'ceiling_fan', 'workplace', 'glass', 'grill', 'roof', 'shelving',\n 'outdoor_seating', 'stand', 'headstone', 'arch', 'beer'\n ],\n 'relate': [\n 'office_chair', 'column', 'door', 'switch', 'partition',\n 'household_appliance', 'decoration', 'place_setting', 'book',\n 'person', 'pet', 'chandelier', 'container', 'containers',\n 'stationary_container', 'trinket', 'stand', 'kitchen_set', 'arch',\n 'books', 'ceiling_fan', 'workplace', 'glass', 'grill', 'roof',\n 'shelving', 'outdoor_seating', 'kitchen_cabinet', 'coffin',\n 'headstone', 'beer'\n ],\n 'dist_compare': [\n 'column', 'door', 'switch', 'person', 'household_appliance',\n 'decoration', 'trinket', 'place_setting', 'coffin', 'book'\n 'cup', 'chandelier', 'arch', 'pet', 'container', 'containers',\n 'stationary_container', 'shelving', 'stand', 'kitchen_set',\n 'books', 'ceiling_fan', 'workplace', 'glass', 'grill', 'roof',\n 'outdoor_seating', 'kitchen_cabinet', 'headstone', 'beer'\n ]\n }\n\n blacklist_rooms = [\n 'loggia', 'storage', 'guest room', 'hallway', 'wardrobe', 'hall',\n 'boiler room', 'terrace', 'room', 'entryway', 'aeration', 'lobby',\n 'office', 'freight elevator', 'passenger elevator'\n ]\n\n use_threshold_size = True\n use_blacklist = True\n\n def __init__(\n self,\n debug=False,\n object_counts_by_room_file=\"data/obj_counts_by_room.json\"\n ):\n self.template_fns = {\n 'filter': self.filter,\n 'unique': self.unique,\n 'query': self.query,\n 'relate': self.relate,\n 'distance': self.distance,\n 'blacklist': self.blacklist,\n 'thresholdSize': self.thresholdSize\n }\n\n self.query_fns = {\n 'query_room': self.queryRoom,\n 'query_count': self.queryCount,\n 'query_room_count': self.queryRoomCounts,\n 'query_global_object_count': self.queryGlobalObjectCounts,\n 'query_room_object_count': self.queryRoomObjectCounts,\n 'query_exist': self.queryExist,\n 'query_logical': self.queryLogical,\n 'query_color': self.queryColor,\n 'query_color_room': self.queryColorRoom,\n 'query_object': self.queryObject,\n 'query_object_room': self.queryObjectRoom,\n 'query_compare': self.queryCompare\n }\n\n self.debug = debug\n self.ent_queue = None\n self.q_str_builder = QuestionStringBuilder()\n self.q_obj_builder = self.questionObjectBuilder\n\n # update\n if os.path.isfile(object_counts_by_room_file) == True:\n self.global_obj_by_room = json.load(\n open(object_counts_by_room_file, 'r'))\n self.negative_exists = {}\n else:\n print('Not loading data/obj_counts_by_room.json')\n\n # load colors\n self.env_obj_color_map = json.load(open('data/obj_colors.json', 'r'))\n\n def cacheHouse(self, Hp):\n self.house = Hp\n\n self.entities = {'rooms': [], 'objects': []}\n\n for i in self.house.rooms:\n room = roomEntity(i['type'], i['bbox'], i)\n for j in room.meta['nodes']:\n obj = objectEntity(\n self.house.objects['0_' + str(j)]['fine_class'],\n self.house.objects['0_' + str(j)]['bbox'],\n self.house.objects['0_' + str(j)],\n obj_id='0_' + str(j))\n room.addObject(obj)\n obj.addRoom(room)\n\n self.entities['objects'].append(obj)\n\n self.entities['rooms'].append(room)\n\n self.isValid()\n\n def isValid(self):\n # print('checking validity...')\n for i in self.entities['rooms']:\n if i.isValid() == False and self.debug == True:\n print('ERROR', i.meta)\n continue\n\n for i in self.entities['objects']:\n if i.isValid() == False and self.debug == True:\n print('ERROR', i.meta)\n continue\n\n def clearQueue(self):\n self.ent_queue = None\n\n def executeFn(self, template):\n for i in template:\n if '.' in i:\n _ = i.split('.')\n fn = _[0]\n param = _[1]\n else:\n fn = i\n param = None\n\n res = self.template_fns[fn](param)\n\n if isinstance(res, dict):\n return res\n else:\n # return unique questions only\n return list({x['question']: x for x in res}.values())\n\n def thresholdSize(self, *args):\n def getSize(bbox):\n try:\n return (bbox['max'][0] - bbox['min'][0]) * (\n bbox['max'][1] - bbox['min'][1]) * (\n bbox['max'][2] - bbox['min'][2])\n except:\n return np.prod(bbox['radii']) * 8\n\n assert self.ent_queue != None\n assert self.ent_queue['type'] == 'objects'\n\n ent = self.ent_queue\n sizes = [getSize(x.bbox) for x in ent['elements']]\n idx = [i for i, v in enumerate(sizes) if v < 0.0005]\n\n for i in idx[::-1]:\n del ent['elements'][i]\n\n self.ent_queue = ent\n return self.ent_queue\n\n def blacklist(self, *args):\n assert self.ent_queue != None\n\n ent = self.ent_queue\n\n if ent['type'] == 'objects':\n template = args[0]\n\n names = [x.name for x in ent['elements']]\n idx = [\n i for i, v in enumerate(names)\n if v in self.blacklist_objects[template]\n ]\n for i in idx[::-1]:\n del ent['elements'][i]\n elif ent['type'] == 'rooms':\n names = [x.name for x in ent['elements']]\n idx = [\n i for i, v in enumerate([\n any([k for k in x if k in self.blacklist_rooms])\n for x in names\n ]) if v == True\n ]\n for i in idx[::-1]:\n del ent['elements'][i]\n\n self.ent_queue = ent\n return self.ent_queue\n\n def filter(self, *args):\n # if ent_queue is empty, execute on parent env entitites\n if self.ent_queue == None:\n self.ent_queue = {\n 'type': args[0],\n 'elements': self.entities[args[0]]\n }\n else:\n ent = self.ent_queue\n assert args[0] != ent['type']\n\n ent = {\n 'type':\n args[0],\n 'elements':\n [z for y in [x.entities for x in ent['elements']] for z in y]\n }\n self.ent_queue = ent\n\n # remove blacklisted rooms\n if self.ent_queue['type'] == 'rooms' and self.use_blacklist == True:\n self.ent_queue = self.blacklist()\n\n if self.ent_queue['type'] == 'objects' and self.use_threshold_size == True:\n self.ent_queue = self.thresholdSize()\n\n return self.ent_queue\n\n def unique(self, *args):\n assert self.ent_queue != None\n ent = self.ent_queue\n\n # unique based on room+object tuple\n if args[0] == 'combo':\n # self.ent_queue contains a list of objects\n names = [\n x.name + \" IN \" + \"_\".join(x.rooms[0].name)\n for x in ent['elements']\n ]\n\n idx = [\n i for i, v in enumerate([names.count(x) for x in names]) if v != 1\n ]\n for i in idx[::-1]:\n del ent['elements'][i]\n\n self.ent_queue = ent\n return self.ent_queue\n\n # unique based on either rooms or objects (only)\n names = [x.name for x in ent['elements']]\n idx = [\n i for i, v in enumerate([names.count(x) for x in names]) if v != 1\n ]\n\n for i in idx[::-1]:\n del ent['elements'][i]\n\n names = [x.name for x in ent['elements']]\n self.ent_queue = ent\n return self.ent_queue\n\n def query(self, *args):\n assert self.ent_queue != None\n ent = self.ent_queue\n\n return self.query_fns['query_' + args[0]](ent)\n\n def relate(self, *args):\n ent = self.ent_queue\n if len(ent['elements']) == 0:\n return ent\n\n if ent['type'] == 'objects':\n h_threshold, v_threshold = 0.05, 0.05\n elif ent['type'] == 'rooms':\n h_threshold, v_threshold = 5.0, 5.0\n nearby_object_pairs = self.house.getNearbyPairs(\n ent['elements'], hthreshold=h_threshold, vthreshold=v_threshold)\n\n self.ent_queue['elements'] = []\n for prep in ['on', 'next_to']:\n for el in nearby_object_pairs[prep]:\n if len([\n x for x in nearby_object_pairs[prep]\n if x[0].name == el[0].name\n ]) > 1:\n continue\n\n if prep == 'on':\n if el[2] > v_threshold / 1000.0:\n preps = [('above', 1), ('under', 0)]\n else:\n preps = [('on', 1), ('below', 0)]\n elif prep == 'next_to':\n preps = [('next_to', 0), ('next_to', 1)]\n\n self.ent_queue['elements'].append([el, preps])\n\n return self.ent_queue\n\n # only works with objectEntities for now\n def distance(self, *args):\n ent = self.ent_queue\n if ent['type'] == 'objects':\n h_low_threshold, h_high_threshold = 0.2, 2.0\n pairwise_distances = self.house.getAllPairwiseDistances(\n ent['elements'])\n\n # self.ent_queue['elements'] = []\n updated_ent_queue = {'type': ent['type'], 'elements': []}\n for i in ent['elements']:\n sub_list = [\n x for x in pairwise_distances\n if x[0].meta['id'] == i.meta['id']\n or x[1].meta['id'] == i.meta['id']\n ]\n sub_list = [\n x for x in sub_list if x[0].rooms[0].name == x[1].rooms[0].name\n ]\n far = [x for x in sub_list if x[2] >= h_high_threshold]\n close = [x for x in sub_list if x[2] <= h_low_threshold]\n if len(far) == 0 or len(close) == 0:\n continue\n for j in far:\n far_ent = 1 if j[0].name == i.name else 0\n for k in close:\n close_ent = 1 if k[0].name == i.name else 0\n updated_ent_queue['elements'].append(\n [k[close_ent], i, j[far_ent], 'closer'])\n updated_ent_queue['elements'].append(\n [j[far_ent], i, k[close_ent], 'farther'])\n\n self.ent_queue = updated_ent_queue\n return self.ent_queue\n\n def queryRoom(self, ent):\n qns = []\n for i in ent['elements']:\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryRoom. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryRoom. room has no name.', i.name,\n i.rooms[0].name)\n continue\n if \"_\".join(i.rooms[0].name[0].split()) not in self.blacklist_rooms:\n qns.append(self.q_obj_builder('location', [i], i.rooms[0].name[0]))\n return qns\n\n def queryCount(self, ent):\n qns = []\n for i in ent['elements']:\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryCount. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryCount. room has no name.', i.name,\n i.rooms[0].name)\n continue\n\n count = len([x for x in i.rooms[0].objects if x.name == i.name])\n if count <= 5:\n qns.append(\n self.q_obj_builder(\n 'count',\n [x for x in i.rooms[0].objects\n if x.name == i.name], count))\n return qns\n\n def queryRoomCounts(self, ent):\n qns = []\n rooms_done = set()\n\n # print [i.name for i in ent['elements']]\n exp_rooms = [\n name for room_ent in ent['elements'] for name in room_ent.name\n ]\n for i in ent['elements']:\n if i.name == []:\n if self.debug == True:\n print('exception in queryRoomCount. room has no name.',\n i.name, i.name)\n continue\n\n for room_name in i.name:\n if room_name in rooms_done: continue\n count = exp_rooms.count(room_name)\n # so that the correct room name is displayed in the question string\n i.name[0] = room_name\n if count < 5:\n qns.append(\n self.q_obj_builder('room_count', [\n room_ent for room_ent in ent['elements']\n if room_name in room_ent.name\n ], count))\n rooms_done.add(room_name)\n # count = len([x for x in ent['elements'] if len(x.name) == 1 and x.name[0] == i.name[0]])\n\n return qns\n\n def queryRoomObjectCounts(self, ent):\n qns = []\n obj_to_room_names, obj_to_room_bbox = dict(), dict()\n for i in ent['elements']:\n # we should also include objects appearing in rooms\n # with multiple or no names (agent can walk through them)\n\n obj_name = i.name\n obj_room_bbox = i.rooms[0].meta['bbox']\n\n if len(i.rooms[0].name) == 0: room_name_for_obj = \"none\"\n elif len(i.rooms[0].name) > 1:\n room_name_for_obj = \" \".join(i.rooms[0].name)\n else:\n room_name_for_obj = i.rooms[0].name[0]\n\n # update the room info for the obj. this update should be done only\n # if we have found an instance of the object in a new room (check using bbox dict)\n if obj_name not in obj_to_room_bbox:\n obj_to_room_bbox[obj_name] = []\n if obj_name not in obj_to_room_names:\n obj_to_room_names[obj_name] = []\n\n if obj_room_bbox not in obj_to_room_bbox[obj_name]:\n obj_to_room_bbox[obj_name].append(obj_room_bbox)\n obj_to_room_names[obj_name].append(room_name_for_obj)\n\n for obj_name in obj_to_room_names:\n ans = len(obj_to_room_names[obj_name])\n gt_bboxes = obj_to_room_bbox[obj_name]\n if ans <= 5:\n qns.append(\n self.q_obj_builder(\n # abusing notation here : the bbox entry for the \"dummy\"\n # object entity is actually a list of bbox entries of the\n # rooms where this object occurs in the house\n 'room_object_count',\n [objectEntity(obj_name, gt_bboxes, {})],\n ans))\n\n return qns\n\n def queryGlobalObjectCounts(self, ent):\n qns = []\n room_wise_dist = dict()\n rooms = []\n\n for i in ent['elements']:\n # Ignore objects which occur in rooms with no name or multiple names\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryCount. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryCount. room has no name.', i.name,\n i.rooms[0].name)\n continue\n\n room_name_for_obj = i.rooms[0].name[0]\n\n rooms.append(i.rooms[0])\n\n if room_name_for_obj not in room_wise_dist:\n room_wise_dist[room_name_for_obj] = []\n entities_in_room = room_wise_dist[room_name_for_obj]\n entities_in_room.append(i)\n room_wise_dist[room_name_for_obj] = entities_in_room\n\n for room_name in room_wise_dist:\n if room_name in self.blacklist_rooms: continue\n obj_entities = room_wise_dist[room_name]\n obj_names = [obj.name for obj in obj_entities]\n\n objs_done = set()\n for obj_entity in obj_entities:\n if obj_entity.name in objs_done: continue\n ans = obj_names.count(obj_entity.name)\n if ans <= 5:\n qns.append(\n self.q_obj_builder('global_object_count', [obj_entity],\n ans))\n objs_done.add(obj_entity.name)\n\n return qns\n\n def queryExist(self, ent):\n qns = []\n for i in ent['elements']:\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryExist. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryExist. room has no name.', i.name,\n i.rooms[0].name)\n continue\n\n qns.append(\n self.q_obj_builder(\n 'exist', [i], 'yes', q_type='exist_positive'))\n\n # generate list of object names in i.rooms[0].name in current env\n obj_present = [\n x.name for x in ent['elements']\n if len(x.rooms[0].name) != 0\n and x.rooms[0].name[0] == i.rooms[0].name[0]\n ]\n if i.rooms[0].name[0] not in self.negative_exists:\n self.negative_exists[i.rooms[0].name[0]] = []\n\n # generate list of object names for i.rooms[0].name not in i.rooms[0].name in current env\n obj_not_present = [\n x for x in self.global_obj_by_room[i.rooms[0].name[0]]\n if x[0] not in obj_present\n and x[0] not in self.negative_exists[i.rooms[0].name[0]]\n ]\n\n # create object entity and generate a no question\n if len(obj_not_present) == 0:\n continue\n\n self.negative_exists[i.rooms[0].name[0]].append(\n obj_not_present[0][0])\n sampled_obj = objectEntity(obj_not_present[0][0], {}, {})\n sampled_obj.addRoom(i.rooms[0])\n qns.append(\n self.q_obj_builder(\n 'exist', [sampled_obj], 'no', q_type='exist_negative'))\n\n return qns\n\n def queryLogical(self, ent):\n qns = []\n rooms_done = set()\n\n # the entities queue contains a list of object entities\n for i in ent['elements']:\n # ignore objects with (1) multiple and (2) no room names\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print(\n 'exception in queryLogical. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryLogical. room has no name.',\n i.name, i.rooms[0].name)\n continue\n\n if i.rooms[0].name[0] in rooms_done: continue\n # get list of all objects present in the same as room as the current object\n # note that as we iterate throgh the ent queue, all the objects in the same room\n # will generate identical list -- so we save the rooms processed in the room_done set\n\n # For example : if the first obj is a bed inside a bedroom, and this bedroom has\n # a total of 5 objects= : ['chair', 'bed', 'chair', 'dressing_table', 'curtains']\n # Then, whenever any of these objects is encountered in the loop (for i in ent['elements'])\n # we will end up generating the same list as shown\n local_list = [(x, x.name) for x in ent['elements']\n if len(x.rooms[0].name) == 1\n and x.rooms[0].name[0] == i.rooms[0].name[0]]\n local_objects_list_ = [obj for (obj, _) in local_list]\n local_object_names_list = [name for (_, name) in local_list]\n\n # get list of objects which are not present in the room where i resides.\n # this list is also pruned based on frequency\n # again, this list will be identical for all objects in the same room\n objs_not_present = [\n x[0] for x in self.global_obj_by_room[i.rooms[0].name[0]]\n if x[0] not in local_object_names_list\n ]\n\n both_present, both_absent, only_one_present = [], [], []\n # print (\"Room : %s\" % i.rooms[0].name)\n\n # populate objects for yes answer questions\n for i_idx in range(len(local_object_names_list)):\n for j_idx in range(i_idx + 1, len(local_object_names_list)):\n if local_object_names_list[\n i_idx] == local_object_names_list[j_idx]:\n continue\n both_present.append((local_object_names_list[i_idx],\n local_object_names_list[j_idx]))\n\n # populate objects for no answer questions -- part 1\n for i_idx in range(len(objs_not_present)):\n for j_idx in range(i_idx + 1, len(objs_not_present)):\n if objs_not_present[i_idx] == objs_not_present[j_idx]:\n continue\n both_absent.append((objs_not_present[i_idx],\n objs_not_present[j_idx]))\n\n # populate objects for no answer questions -- part 2\n for obj1 in local_object_names_list:\n for obj2 in objs_not_present:\n only_one_present.append((obj1, obj2))\n\n # generate a question for each object pairs in the 3 lists\n shuffle(both_present)\n shuffle(both_absent)\n shuffle(only_one_present)\n num_yes = num_no = len(both_present)\n only_one_present, both_absent = only_one_present[:int(\n num_no - num_no / 2)], both_absent[:int(num_no / 2)]\n\n for (obj1, obj2) in both_present:\n obj1_entity, obj2_entity = objectEntity(obj1, {},\n {}), objectEntity(\n obj2, {}, {})\n obj1_entity.rooms.append(i.rooms[0])\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'yes',\n 'exist_logical_positive'))\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'yes',\n 'exist_logical_or_positive_1'))\n for (obj1, obj2) in both_absent:\n obj1_entity, obj2_entity = objectEntity(obj1, {},\n {}), objectEntity(\n obj2, {}, {})\n obj1_entity.rooms.append(\n i.rooms[0]\n ) # this is not technically correct, just so that q_string_builder works\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'no',\n 'exist_logical_negative_1'))\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'no',\n 'exist_logical_or_negative'))\n\n for (obj1, obj2) in only_one_present:\n obj1_entity, obj2_entity = objectEntity(obj1, {},\n {}), objectEntity(\n obj2, {}, {})\n obj1_entity.rooms.append(i.rooms[0])\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'no',\n 'exist_logical_negative_2'))\n qns.append(\n self.q_obj_builder('exist_logic',\n [(obj1_entity, obj2_entity)], 'yes',\n 'exist_logical_or_positive_2'))\n\n # mark room as done\n rooms_done.add(i.rooms[0].name[0])\n\n return qns\n\n def queryColor(self, ent):\n qns = []\n for i in ent['elements']:\n if self.house.id + '.' + i.id in self.env_obj_color_map:\n color = self.env_obj_color_map[self.house.id + '.' + i.id]\n qns.append(\n self.q_obj_builder('color', [i], color))\n else:\n # no color\n continue\n return qns\n\n def queryColorRoom(self, ent):\n qns = []\n for i in ent['elements']:\n if len(i.rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryExist. room has multiple names.',\n i.rooms[0].name)\n continue\n elif i.rooms[0].name == []:\n if self.debug == True:\n print('exception in queryExist. room has no name.', i.name,\n i.rooms[0].name)\n continue\n\n if self.house.id + '.' + i.id in self.env_obj_color_map:\n color = self.env_obj_color_map[self.house.id + '.' + i.id]\n qns.append(\n self.q_obj_builder('color_room', [i], color))\n else:\n # no color\n continue\n return qns\n\n def queryObject(self, ent):\n qns = []\n for i in ent['elements']:\n el = i[0]\n preps = i[1]\n for prep_mod in preps:\n if el[prep_mod[1] ^ 1].name not in self.blacklist_objects['relate']:\n qns.append(\n self.q_obj_builder(prep_mod[0], [el[prep_mod[1]]],\n el[prep_mod[1] ^ 1].name))\n return qns\n\n def queryObjectRoom(self, ent):\n qns = []\n for i in ent['elements']:\n el = i[0]\n preps = i[1]\n if len(el[0].rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryExist. room has multiple names.',\n el[0].rooms[0].name)\n continue\n elif el[0].rooms[0].name == []:\n if self.debug == True:\n print('exception in queryExist. room has no name.',\n el[0].name, el[0].rooms[0].name)\n continue\n for prep_mod in preps:\n if el[prep_mod[1] ^ 1].name not in self.blacklist_objects['relate']:\n qns.append(\n self.q_obj_builder(prep_mod[0] + '_room',\n [el[prep_mod[1]]],\n el[prep_mod[1] ^ 1].name))\n return qns\n\n def queryCompare(self, ent):\n qns = []\n for i in ent['elements']:\n if len(i[0].rooms[0].name) > 1:\n if self.debug == True:\n print('exception in queryExist. room has multiple names.',\n i[0].rooms[0].name)\n continue\n elif i[0].rooms[0].name == []:\n if self.debug == True:\n print('exception in queryExist. room has no name.',\n i[0].name, i[0].rooms[0].name)\n continue\n qns.append(\n self.q_obj_builder(i[3] + '_room', i[:3], 'yes',\n 'dist_compare_positive'))\n qns.append(\n self.q_obj_builder(i[3] + '_room', i[:3][::-1], 'no',\n 'dist_compare_negative'))\n return qns\n\n def questionObjectBuilder(self, template, q_ent, a_str, q_type=None):\n if q_type == None:\n q_type = template\n\n q_str = self.templates[template]\n bbox = []\n\n if template == 'room_count':\n # if this condition holds, the question type is 'room_count' and the q_ent[0] is a room entity\n q_str = self.q_str_builder.prepareString(q_str, '',\n q_ent[0].name[0])\n return {\n 'question':\n q_str,\n 'answer':\n a_str,\n 'type':\n q_type,\n 'meta': {},\n 'bbox': [{\n 'type': x.type,\n 'box': x.bbox,\n 'name': x.name,\n 'target': True\n } for x in q_ent]\n }\n\n if template == 'room_object_count':\n q_str = self.q_str_builder.prepareString(q_str, q_ent[0].name, '')\n return {\n 'question':\n q_str,\n 'answer':\n a_str,\n 'type':\n q_type,\n 'meta': {},\n 'bbox': [{\n 'type': x.type,\n 'box': x.bbox,\n 'name': x.name,\n 'target': True\n } for x in q_ent]\n }\n\n if template == 'global_object_count':\n # if (len(q_ent) == 1) and (not isinstance(q_ent[0], tuple)) and (q_ent[0].type == 'object'):\n # if this condition holds, the question type is 'global_object_count' and the q_ent[0] is an obj entity\n q_str = self.q_str_builder.prepareString(q_str, q_ent[0].name,\n q_ent[0].rooms[0].name[0])\n return {\n 'question': q_str,\n 'answer': a_str,\n 'type': q_type,\n 'meta': {},\n 'bbox': [{}]\n }\n\n for ent in q_ent:\n # if ent is a tuple, it means exist_logic questions\n if isinstance(ent, tuple):\n if 'or' in q_type:\n q_str = self.q_str_builder.prepareStringForLogic(\n q_str, ent[0].name, ent[1].name,\n ent[0].rooms[0].name[0], \"or\")\n else:\n q_str = self.q_str_builder.prepareStringForLogic(\n q_str, ent[0].name, ent[1].name,\n ent[0].rooms[0].name[0], \"and\")\n return {\n 'question':\n q_str,\n 'answer':\n a_str,\n 'type':\n q_type,\n 'meta': {},\n 'bbox': [{\n 'type': ent[0].rooms[0].type,\n 'box': ent[0].rooms[0].bbox,\n 'name': ent[0].rooms[0].name,\n 'target': True\n }]\n }\n\n bbox.append({\n 'type': ent.type,\n 'box': ent.bbox,\n 'name': ent.name,\n 'target': True\n })\n if not isinstance(ent, tuple) and len(ent.rooms[0].name) != 0:\n q_str = self.q_str_builder.prepareString(\n q_str, ent.name, ent.rooms[0].name[0])\n else:\n q_str = self.q_str_builder.prepareString(q_str, ent.name, '')\n\n if not isinstance(ent, tuple):\n if len(ent.rooms[0].name) == 0:\n name = []\n else:\n name = ent.rooms[0].name\n bbox.append({\n 'type': ent.rooms[0].type,\n 'box': ent.rooms[0].bbox,\n 'name': name,\n 'target': False\n })\n\n if 'mat' in q_ent[0].meta:\n mat = q_ent[0].meta['mat']\n else:\n mat = {}\n\n return {\n 'question': q_str,\n 'answer': a_str,\n 'type': q_type,\n 'meta': mat,\n 'bbox': bbox\n }\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-inputJson\",\n help=\"Environments list\",\n default=\n \"data/envs.json\"\n )\n parser.add_argument(\n \"-outputJson\",\n help=\"Json file to save questions list\",\n default=\"data/working/questions.json\")\n parser.add_argument(\n \"-dataDir\",\n help=\"Directory that has the SUNCG dataset\",\n default=\"/path/to/suncg/\")\n parser.add_argument(\n \"-numEnvs\", help=\"No. of environments to read\", default=False)\n args = parser.parse_args()\n\n data = json.load(open(args.inputJson, 'r'))\n house_ids = list(data.keys())\n num_envs = len(house_ids)\n if args.numEnvs != False:\n num_envs = int(args.numEnvs)\n\n Hp = HouseParse(dataDir=args.dataDir)\n E = Engine()\n\n # SAVE QUESTIONS TO A JSON FILE\n #\n # -- STARTS HERE\n\n idx, all_qns = 1, []\n empty_envs = []\n for i in tqdm(range(num_envs)):\n Hp.parse(house_ids[i])\n num_qns_for_house = 0\n for j in E.template_defs:\n if j == 'global_object_count': continue\n E.cacheHouse(Hp)\n qns = E.executeFn(E.template_defs[j])\n num_qns_for_house += len(qns)\n E.clearQueue()\n\n for k in qns:\n k['id'] = idx\n k['house'] = house_ids[i]\n idx += 1\n\n all_qns.append(k)\n\n if num_qns_for_house == 0: empty_envs.append(house_ids[i])\n\n print(\"Houses with no questions generated (if any) : %d\" % len(empty_envs))\n print(empty_envs)\n\n print('Writing to %s...' % args.outputJson)\n json.dump(all_qns, open(args.outputJson, 'w'))\n\n # -- ENDS HERE\n\n # TO GET ENVS WHICH CONTAIN INSTANCES OF A SPECIFIC OBJ TYPE\n #\n # -- STARTS HERE\n\n # envs_with_obj = dict()\n # for i in tqdm(range(num_envs)):\n # Hp.parse(house_ids[i])\n # E.cacheHouse(Hp)\n # if house_ids[i] not in envs_with_obj: envs_with_obj[house_ids[i]] = 0\n\n # res = E.executeFn(['filter.objects'])\n # for j in res['elements']:\n # if j.name == 'book':\n # envs_with_obj[house_ids[i]] += 1\n\n # E.clearQueue()\n # env_list = [env for env in envs_with_obj if envs_with_obj[env] != 0]\n # ans = len(env_list)\n # for env in env_list: print env\n # print (\"There are %d envs with 'tabel_and_chair' instances...\" % ans)\n\n # -- ENDS HERE\n\n # PRINT QUESTION COUNTS FOR ALL ENVS\n #\n # -- STARTS HERE\n\n # for i in range(num_envs):\n # Hp.parse(house_ids[i])\n # E.cacheHouse(Hp)\n # count = {}\n # for j in E.template_defs:\n # qns = E.executeFn(E.template_defs[j])\n # E.clearQueue()\n # for k in qns:\n # if k['type'] not in count:\n # count[k['type']] = []\n # count[k['type']].append(k)\n # total = 0\n # print('---| %s' % house_ids[i])\n # for j in count:\n # print('%30s: %5d' % (j, len(count[j])))\n # total += len(count[j])\n # print('%30s: %5d' % ('total', total))\n\n # -- ENDS HERE\n\n # TO GENERATE OBJECT COUNTS BY ROOM FOR ALL ENVS\n #\n # -- STARTS HERE\n\n # object_counts_by_room = {}\n # for i in tqdm(range(num_envs)):\n # Hp.parse(house_ids[i])\n # E.cacheHouse(Hp)\n\n # res = E.executeFn(['filter.rooms', 'filter.objects', 'blacklist.exist'])\n\n # for j in res['elements']:\n # for k in j.rooms[0].name:\n # if k not in object_counts_by_room:\n # object_counts_by_room[k] = {}\n # if j.name not in object_counts_by_room[k]:\n # object_counts_by_room[k][j.name] = 0\n # object_counts_by_room[k][j.name] += 1\n\n # E.clearQueue()\n # for i in object_counts_by_room:\n # object_counts_by_room[i] = sorted(\n # object_counts_by_room[i].items(), key=lambda x: x[1], reverse=True)\n # json.dump(object_counts_by_room, open('data/obj_counts_by_room.json', 'w'))\n\n # -- ENDS HERE\n\n # GATHERING GLOBAL STATISTICS BY QUESTION TYPE\n #\n # -- STARTS HERE\n\n # global_counts_by_q_type = {'total': []}\n # for i in range(num_envs):\n # Hp.parse(house_ids[i])\n # E.cacheHouse(Hp)\n # count = {}\n # for j in E.template_defs:\n # qns = E.executeFn(E.template_defs[j])\n # E.clearQueue()\n # for k in qns:\n # if k['type'] not in count:\n # count[k['type']] = []\n # count[k['type']].append(k)\n # total = 0\n # print('---| %s' % house_ids[i])\n # for j in count:\n # print('%30s: %5d' % (j, len(count[j])))\n # total += len(count[j])\n # if j not in global_counts_by_q_type:\n # global_counts_by_q_type[j] = []\n # global_counts_by_q_type[j].append(len(count[j]))\n # global_counts_by_q_type['total'].append(total)\n # print('%30s: %5d' % ('total', total))\n\n # print('---| GLOBAL STATS ACROSS %d ENVS' % len(global_counts_by_q_type['total']))\n # for i in global_counts_by_q_type:\n # print('%30s, mean: %.03f var: %.03f' % (i, np.array(global_counts_by_q_type[i]).mean(), np.array(global_counts_by_q_type[i]).std()))\n\n # -- ENDS HERE\n"
]
| [
[
"numpy.random.seed",
"numpy.prod"
]
]
|
TexTecGo/Student_Api | [
"9d065415f77357be2e2b24b138333ce4c38901cf"
]
| [
"func/predict_func.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/5/20 \n\n@author: susmote\n\"\"\"\nimport urllib\nimport requests\nimport urllib.request\nimport numpy as np\nfrom PIL import Image\nfrom sklearn.externals import joblib\nimport os\n\n\ndef verify(url, model):\n \"\"\"\n :param url: 验证码地址\n :param save: 是否保存临时文件到cache\n :return:\n \"\"\"\n i = 0\n file_list = os.listdir('cache/')\n for file in file_list:\n file_name = os.path.splitext(file)[0]\n if file_name != \".DS_Store\" and file_name != \"captcha\":\n if i == int(file_name):\n i = int(file_name)+1\n if i < int(file_name):\n i = int(file_name)\n print(i)\n session = requests.session()\n r = session.get(url)\n print(r)\n path = 'cache/'\n with open(path+ 'captcha.png', 'wb') as f:\n f.write(r.content)\n with open( path + '%s.png'%(i), 'wb') as f:\n f.write(r.content)\n image = Image.open( path +'captcha.png')\n x_size, y_size = image.size\n y_size -= 5\n\n # y from 1 to y_size-5\n # x from 4 to x_size-18\n piece = (x_size-24) / 8\n centers = [4+piece*(2*i+1) for i in range(4)]\n data = np.empty((4, 21 * 16), dtype=\"float32\")\n for i, center in enumerate(centers):\n single_pic = image.crop((center-(piece+2), 1, center+(piece+2), y_size))\n data[i, :] = np.asarray(single_pic, dtype=\"float32\").flatten() / 255.0\n clf = joblib.load(model)\n answers = clf.predict(data)\n answers = map(chr, map(lambda x: x + 48 if x <= 9 else x + 87 if x <= 23 else x + 88, map(int, answers)))\n return answers\n\n\n# def save_code():\n\n\n"
]
| [
[
"sklearn.externals.joblib.load",
"numpy.empty",
"numpy.asarray"
]
]
|
ornlneutronimaging/braggedgemodeling | [
"6bf49b008cae5707f3c950e4a4d574211f201976"
]
| [
"tests/test_texture_Fe.py"
]
| [
"#!/usr/bin/env python\n# Jiao Lin <[email protected]>\n\ninteractive = False\n\nimport os, numpy as np\nfrom bem import xscalc, diffraction, xtaloriprobmodel as xopm\nfrom bem.matter import bccFe\n\nthisdir = os.path.dirname(__file__)\n\ndef test_bccFe():\n lambdas = np.arange(0.05, 5, 0.01)\n T = 300\n texture_model = xopm.MarchDollase()\n calc = xscalc.XSCalculator(bccFe, T, texture_model, max_diffraction_index=5)\n xs_0 = calc.xs(lambdas)\n # r = 2, beta = 60.\n texture_model.r[(0,1,1)] = 2\n texture_model.beta[(0,1,1)] = 60./180.*np.pi\n xs_60 = calc.xs(lambdas)\n # r = 1.2, beta = 30\n texture_model.r[(0,1,1)] = 1.2\n texture_model.beta[(0,1,1)] = 30./180.*np.pi\n xs_30 = calc.xs(lambdas)\n # r = 1.2, beta = 30\n texture_model.r[(0,1,1)] = 1.2\n texture_model.beta[(0,1,1)] = 90./180.*np.pi\n xs_90 = calc.xs(lambdas)\n data = np.array([lambdas, xs_0, xs_30, xs_60, xs_90])\n # np.save(os.path.join(thisdir, 'expected', 'bccFe-texture-xs.npy'), data)\n expected = np.load(os.path.join(thisdir, 'expected', 'bccFe-texture-xs.npy'))\n assert np.isclose(data, expected).all()\n \n if interactive:\n from matplotlib import pyplot as plt\n plt.plot(lambdas, xs_0, label='r=1, isotropic')\n plt.plot(lambdas, xs_30, label='r=1.2, $\\\\beta=30^\\\\circ$')\n plt.plot(lambdas, xs_60, label='r=2.0, $\\\\beta=60^\\\\circ$')\n plt.plot(lambdas, xs_90, label='r=1.2, $\\\\beta=90^\\\\circ$')\n plt.legend(loc='upper left')\n plt.show()\n return\n\ndef main():\n global interactive\n interactive = True\n test_bccFe()\n return\n\nif __name__ == '__main__': main()\n\n# End of file\n"
]
| [
[
"numpy.array",
"numpy.isclose",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.show"
]
]
|
breedlun/clearplot | [
"3b2b40e393ca6d0ff66d482e74d936da7bd78a73"
]
| [
"doc/source/examples/no_axis_arrows/no_axis_arrows.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 18 15:04:55 2015\n\n@author: Ben\n\"\"\"\nimport clearplot.params\nimport clearplot.plot_functions as pf\nimport numpy as np\n\nclearplot.params.axis_arrow_bool = False\n\nx = np.arange(0,10,0.01)\ny = np.sqrt(x)\n\npf.plot('no_axis_arrows.png', x, y, \\\n x_label = ['\\sf{Volume\\;Change}', '\\%'], \\\n y_label = ['\\psi', 'GPa']);"
]
| [
[
"numpy.arange",
"numpy.sqrt"
]
]
|
HenryLee97/isl | [
"0eb357bd45c5ce3ab3ef060deb84707975049d37"
]
| [
"isl/loss/mlp.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MLPLossTrainer(nn.Module):\n\n def __init__(self, n_class: int, n_layers: int = 3, hidden_size: int = 20, last_sigmoid: bool = False) -> nn.Module:\n super(MLPLossTrainer, self).__init__()\n\n self.n_class = n_class\n self.sigmoid = last_sigmoid\n\n layers = [nn.Linear(2 * n_class, hidden_size), nn.ReLU()]\n for _ in range(n_layers - 2):\n layers.append(nn.Linear(hidden_size, hidden_size))\n layers.append(nn.ReLU())\n layers.append(nn.Linear(hidden_size, 1))\n self.layers = nn.Sequential(*layers)\n\n def forward(self, y_hat: torch.Tensor, y_star: torch.Tensor) -> torch.Tensor:\n y_star = F.one_hot(y_star, self.n_class)\n contat_logits = torch.cat([y_hat, y_star], dim=-1)\n loss_foreach_batch = self.layers(contat_logits)\n return torch.sigmoid(loss_foreach_batch) if self.sigmoid else loss_foreach_batch\n\n\nclass MLPLoss(MLPLossTrainer):\n\n def forward(self, y_hat: torch.Tensor, y_star: torch.Tensor) -> torch.Tensor:\n return super(MLPLoss, self).forward(y_hat, y_star).sum()\n"
]
| [
[
"torch.nn.Linear",
"torch.sigmoid",
"torch.cat",
"torch.nn.functional.one_hot",
"torch.nn.Sequential",
"torch.nn.ReLU"
]
]
|
adidinchuk/tf-neural-net | [
"e81db6fad7c31bf9f4e9981f77953dc2e23ca45a"
]
| [
"data.py"
]
| [
"'''\nBy adidinchuk. [email protected].\nhttps://github.com/adidinchuk/tf-neural-net\n'''\n\nimport hyperparams as hp\nimport numpy as np\n\n\ndef import_data(name, headers=False):\n\n file_name = hp.data_dir + '\\\\' + name\n\n with open(file_name) as fp:\n lines = fp.read().split(\"\\n\")\n\n iterator = iter(lines)\n if headers:\n next(iterator)\n\n data = [line.split(',') for line in iterator]\n return data\n\n\n# replace zeros in the data set with mean values\n# ! columns are expected to contain features ! #\ndef zero_to_mean(data):\n data = np.transpose(data)\n means = np.sum(data, axis=1) / np.count_nonzero(data, axis=1)\n for col in range(len(data)):\n data[col][data[col] == 0.] = means[col]\n data = np.transpose(data)\n return data\n\n\ndef expand_categorical_feature(feature):\n result = []\n translation = []\n for category in np.unique(feature):\n translation.append(category)\n result.append([1 if row == category else 0 for row in feature])\n return result, translation\n\n\ndef normalize(data):\n col_max = data.max(axis=0)\n col_min = data.min(axis=0)\n return (data - col_min) / (col_max - col_min)\n"
]
| [
[
"numpy.sum",
"numpy.count_nonzero",
"numpy.transpose",
"numpy.unique"
]
]
|
junmeng6025/aima-python | [
"ab2b15388ec69a4508db52c605225f65423b88df"
]
| [
"junmeng_gki21csp/utils.py"
]
| [
"\"\"\"Provides some utilities widely used by other modules\"\"\"\n\nimport bisect\nimport collections\nimport collections.abc\nimport heapq\nimport operator\nimport os.path\nimport random\nimport math\nimport functools\nfrom statistics import mean\n\nimport numpy as np\nfrom itertools import chain, combinations\n\n\n# ______________________________________________________________________________\n# Functions on Sequences and Iterables\n\n\ndef sequence(iterable):\n \"\"\"Converts iterable to sequence, if it is not already one.\"\"\"\n return (iterable if isinstance(iterable, collections.abc.Sequence)\n else tuple([iterable]))\n\n\ndef remove_all(item, seq):\n \"\"\"Return a copy of seq (or string) with all occurrences of item removed.\"\"\"\n if isinstance(seq, str):\n return seq.replace(item, '')\n elif isinstance(seq, set):\n rest = seq.copy()\n rest.remove(item)\n return rest\n else:\n return [x for x in seq if x != item]\n\n\ndef unique(seq):\n \"\"\"Remove duplicate elements from seq. Assumes hashable elements.\"\"\"\n return list(set(seq))\n\n\ndef count(seq):\n \"\"\"Count the number of items in sequence that are interpreted as true.\"\"\"\n return sum(map(bool, seq))\n\n\ndef multimap(items):\n \"\"\"Given (key, val) pairs, return {key: [val, ....], ...}.\"\"\"\n result = collections.defaultdict(list)\n for (key, val) in items:\n result[key].append(val)\n return dict(result)\n\n\ndef multimap_items(mmap):\n \"\"\"Yield all (key, val) pairs stored in the multimap.\"\"\"\n for (key, vals) in mmap.items():\n for val in vals:\n yield key, val\n\n\ndef product(numbers):\n \"\"\"Return the product of the numbers, e.g. product([2, 3, 10]) == 60\"\"\"\n result = 1\n for x in numbers:\n result *= x\n return result\n\n\ndef first(iterable, default=None):\n \"\"\"Return the first element of an iterable; or default.\"\"\"\n return next(iter(iterable), default)\n\n\ndef is_in(elt, seq):\n \"\"\"Similar to (elt in seq), but compares with 'is', not '=='.\"\"\"\n return any(x is elt for x in seq)\n\n\ndef mode(data):\n \"\"\"Return the most common data item. If there are ties, return any one of them.\"\"\"\n [(item, count)] = collections.Counter(data).most_common(1)\n return item\n\n\ndef powerset(iterable):\n \"\"\"powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\"\"\n s = list(iterable)\n return list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))[1:]\n\n\ndef extend(s, var, val):\n \"\"\"Copy dict s and extend it by setting var to val; return copy.\"\"\"\n s2 = s.copy()\n s2[var] = val\n return s2\n\n\n# ______________________________________________________________________________\n# argmin and argmax\n\nidentity = lambda x: x\n\nargmin = min\nargmax = max\n\n\ndef argmin_random_tie(seq, key=identity):\n \"\"\"Return a minimum element of seq; break ties at random.\"\"\"\n return argmin(shuffled(seq), key=key)\n\n\ndef argmax_random_tie(seq, key=identity):\n \"\"\"Return an element with highest fn(seq[i]) score; break ties at random.\"\"\"\n return argmax(shuffled(seq), key=key)\n\n\ndef shuffled(iterable):\n \"\"\"Randomly shuffle a copy of iterable.\"\"\"\n items = list(iterable)\n random.shuffle(items)\n return items\n\n\n# ______________________________________________________________________________\n# Statistical and mathematical functions\n\n\ndef histogram(values, mode=0, bin_function=None):\n \"\"\"Return a list of (value, count) pairs, summarizing the input values.\n Sorted by increasing value, or if mode=1, by decreasing count.\n If bin_function is given, map it over values first.\"\"\"\n if bin_function:\n values = map(bin_function, values)\n\n bins = {}\n for val in values:\n bins[val] = bins.get(val, 0) + 1\n\n if mode:\n return sorted(list(bins.items()), key=lambda x: (x[1], x[0]),\n reverse=True)\n else:\n return sorted(bins.items())\n\n\ndef dotproduct(X, Y):\n \"\"\"Return the sum of the element-wise product of vectors X and Y.\"\"\"\n return sum(x * y for x, y in zip(X, Y))\n\n\ndef element_wise_product(X, Y):\n \"\"\"Return vector as an element-wise product of vectors X and Y\"\"\"\n assert len(X) == len(Y)\n return [x * y for x, y in zip(X, Y)]\n\n\ndef matrix_multiplication(X_M, *Y_M):\n \"\"\"Return a matrix as a matrix-multiplication of X_M and arbitrary number of matrices *Y_M\"\"\"\n\n def _mat_mult(X_M, Y_M):\n \"\"\"Return a matrix as a matrix-multiplication of two matrices X_M and Y_M\n >>> matrix_multiplication([[1, 2, 3],\n [2, 3, 4]],\n [[3, 4],\n [1, 2],\n [1, 0]])\n [[8, 8],[13, 14]]\n \"\"\"\n assert len(X_M[0]) == len(Y_M)\n\n result = [[0 for i in range(len(Y_M[0]))] for j in range(len(X_M))]\n for i in range(len(X_M)):\n for j in range(len(Y_M[0])):\n for k in range(len(Y_M)):\n result[i][j] += X_M[i][k] * Y_M[k][j]\n return result\n\n result = X_M\n for Y in Y_M:\n result = _mat_mult(result, Y)\n\n return result\n\n\ndef vector_to_diagonal(v):\n \"\"\"Converts a vector to a diagonal matrix with vector elements\n as the diagonal elements of the matrix\"\"\"\n diag_matrix = [[0 for i in range(len(v))] for j in range(len(v))]\n for i in range(len(v)):\n diag_matrix[i][i] = v[i]\n\n return diag_matrix\n\n\ndef vector_add(a, b):\n \"\"\"Component-wise addition of two vectors.\"\"\"\n return tuple(map(operator.add, a, b))\n\n\ndef scalar_vector_product(X, Y):\n \"\"\"Return vector as a product of a scalar and a vector\"\"\"\n return [X * y for y in Y]\n\n\ndef scalar_matrix_product(X, Y):\n \"\"\"Return matrix as a product of a scalar and a matrix\"\"\"\n return [scalar_vector_product(X, y) for y in Y]\n\n\ndef inverse_matrix(X):\n \"\"\"Inverse a given square matrix of size 2x2\"\"\"\n assert len(X) == 2\n assert len(X[0]) == 2\n det = X[0][0] * X[1][1] - X[0][1] * X[1][0]\n assert det != 0\n inv_mat = scalar_matrix_product(1.0 / det, [[X[1][1], -X[0][1]], [-X[1][0], X[0][0]]])\n\n return inv_mat\n\n\ndef probability(p):\n \"\"\"Return true with probability p.\"\"\"\n return p > random.uniform(0.0, 1.0)\n\n\ndef weighted_sample_with_replacement(n, seq, weights):\n \"\"\"Pick n samples from seq at random, with replacement, with the\n probability of each element in proportion to its corresponding\n weight.\"\"\"\n sample = weighted_sampler(seq, weights)\n\n return [sample() for _ in range(n)]\n\n\ndef weighted_sampler(seq, weights):\n \"\"\"Return a random-sample function that picks from seq weighted by weights.\"\"\"\n totals = []\n for w in weights:\n totals.append(w + totals[-1] if totals else w)\n\n return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]\n\n\ndef weighted_choice(choices):\n \"\"\"A weighted version of random.choice\"\"\"\n # NOTE: Shoule be replaced by random.choices if we port to Python 3.6\n\n total = sum(w for _, w in choices)\n r = random.uniform(0, total)\n upto = 0\n for c, w in choices:\n if upto + w >= r:\n return c, w\n upto += w\n\n\ndef rounder(numbers, d=4):\n \"\"\"Round a single number, or sequence of numbers, to d decimal places.\"\"\"\n if isinstance(numbers, (int, float)):\n return round(numbers, d)\n else:\n constructor = type(numbers) # Can be list, set, tuple, etc.\n return constructor(rounder(n, d) for n in numbers)\n\n\ndef num_or_str(x): # TODO: rename as `atom`\n \"\"\"The argument is a string; convert to a number if\n possible, or strip it.\"\"\"\n try:\n return int(x)\n except ValueError:\n try:\n return float(x)\n except ValueError:\n return str(x).strip()\n\n\ndef euclidean_distance(X, Y):\n return math.sqrt(sum((x - y) ** 2 for x, y in zip(X, Y)))\n\n\ndef cross_entropy_loss(X, Y):\n n = len(X)\n return (-1.0 / n) * sum(x * math.log(y) + (1 - x) * math.log(1 - y) for x, y in zip(X, Y))\n\n\ndef rms_error(X, Y):\n return math.sqrt(ms_error(X, Y))\n\n\ndef ms_error(X, Y):\n return mean((x - y) ** 2 for x, y in zip(X, Y))\n\n\ndef mean_error(X, Y):\n return mean(abs(x - y) for x, y in zip(X, Y))\n\n\ndef manhattan_distance(X, Y):\n return sum(abs(x - y) for x, y in zip(X, Y))\n\n\ndef mean_boolean_error(X, Y):\n return mean(x != y for x, y in zip(X, Y))\n\n\ndef hamming_distance(X, Y):\n return sum(x != y for x, y in zip(X, Y))\n\n\ndef normalize(dist):\n \"\"\"Multiply each number by a constant such that the sum is 1.0\"\"\"\n if isinstance(dist, dict):\n total = sum(dist.values())\n for key in dist:\n dist[key] = dist[key] / total\n assert 0 <= dist[key] <= 1, \"Probabilities must be between 0 and 1.\"\n return dist\n total = sum(dist)\n return [(n / total) for n in dist]\n\n\ndef norm(X, n=2):\n \"\"\"Return the n-norm of vector X\"\"\"\n return sum([x ** n for x in X]) ** (1 / n)\n\n\ndef random_weights(min_value, max_value, num_weights):\n return [random.uniform(min_value, max_value) for _ in range(num_weights)]\n\n\ndef clip(x, lowest, highest):\n \"\"\"Return x clipped to the range [lowest..highest].\"\"\"\n return max(lowest, min(x, highest))\n\n\ndef sigmoid_derivative(value):\n return value * (1 - value)\n\n\ndef sigmoid(x):\n \"\"\"Return activation value of x with sigmoid function\"\"\"\n return 1 / (1 + math.exp(-x))\n\n\ndef relu_derivative(value):\n if value > 0:\n return 1\n else:\n return 0\n\n\ndef elu(x, alpha=0.01):\n if x > 0:\n return x\n else:\n return alpha * (math.exp(x) - 1)\n\n\ndef elu_derivative(value, alpha=0.01):\n if value > 0:\n return 1\n else:\n return alpha * math.exp(value)\n\n\ndef tanh(x):\n return np.tanh(x)\n\n\ndef tanh_derivative(value):\n return (1 - (value ** 2))\n\n\ndef leaky_relu(x, alpha=0.01):\n if x > 0:\n return x\n else:\n return alpha * x\n\n\ndef leaky_relu_derivative(value, alpha=0.01):\n if value > 0:\n return 1\n else:\n return alpha\n\n\ndef relu(x):\n return max(0, x)\n\n\ndef relu_derivative(value):\n if value > 0:\n return 1\n else:\n return 0\n\n\ndef step(x):\n \"\"\"Return activation value of x with sign function\"\"\"\n return 1 if x >= 0 else 0\n\n\ndef gaussian(mean, st_dev, x):\n \"\"\"Given the mean and standard deviation of a distribution, it returns the probability of x.\"\"\"\n return 1 / (math.sqrt(2 * math.pi) * st_dev) * math.e ** (-0.5 * (float(x - mean) / st_dev) ** 2)\n\n\ntry: # math.isclose was added in Python 3.5; but we might be in 3.4\n from math import isclose\nexcept ImportError:\n def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):\n \"\"\"Return true if numbers a and b are close to each other.\"\"\"\n return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)\n\n\ndef truncated_svd(X, num_val=2, max_iter=1000):\n \"\"\"Compute the first component of SVD.\"\"\"\n\n def normalize_vec(X, n=2):\n \"\"\"Normalize two parts (:m and m:) of the vector.\"\"\"\n X_m = X[:m]\n X_n = X[m:]\n norm_X_m = norm(X_m, n)\n Y_m = [x / norm_X_m for x in X_m]\n norm_X_n = norm(X_n, n)\n Y_n = [x / norm_X_n for x in X_n]\n return Y_m + Y_n\n\n def remove_component(X):\n \"\"\"Remove components of already obtained eigen vectors from X.\"\"\"\n X_m = X[:m]\n X_n = X[m:]\n for eivec in eivec_m:\n coeff = dotproduct(X_m, eivec)\n X_m = [x1 - coeff * x2 for x1, x2 in zip(X_m, eivec)]\n for eivec in eivec_n:\n coeff = dotproduct(X_n, eivec)\n X_n = [x1 - coeff * x2 for x1, x2 in zip(X_n, eivec)]\n return X_m + X_n\n\n m, n = len(X), len(X[0])\n A = [[0] * (n + m) for _ in range(n + m)]\n for i in range(m):\n for j in range(n):\n A[i][m + j] = A[m + j][i] = X[i][j]\n\n eivec_m = []\n eivec_n = []\n eivals = []\n\n for _ in range(num_val):\n X = [random.random() for _ in range(m + n)]\n X = remove_component(X)\n X = normalize_vec(X)\n\n for i in range(max_iter):\n old_X = X\n X = matrix_multiplication(A, [[x] for x in X])\n X = [x[0] for x in X]\n X = remove_component(X)\n X = normalize_vec(X)\n # check for convergence\n if norm([x1 - x2 for x1, x2 in zip(old_X, X)]) <= 1e-10:\n break\n\n projected_X = matrix_multiplication(A, [[x] for x in X])\n projected_X = [x[0] for x in projected_X]\n new_eigenvalue = norm(projected_X, 1) / norm(X, 1)\n ev_m = X[:m]\n ev_n = X[m:]\n if new_eigenvalue < 0:\n new_eigenvalue = -new_eigenvalue\n ev_m = [-ev_m_i for ev_m_i in ev_m]\n eivals.append(new_eigenvalue)\n eivec_m.append(ev_m)\n eivec_n.append(ev_n)\n return eivec_m, eivec_n, eivals\n\n\n# ______________________________________________________________________________\n# Grid Functions\n\n\norientations = EAST, NORTH, WEST, SOUTH = [(1, 0), (0, 1), (-1, 0), (0, -1)]\nturns = LEFT, RIGHT = (+1, -1)\n\n\ndef turn_heading(heading, inc, headings=orientations):\n return headings[(headings.index(heading) + inc) % len(headings)]\n\n\ndef turn_right(heading):\n return turn_heading(heading, RIGHT)\n\n\ndef turn_left(heading):\n return turn_heading(heading, LEFT)\n\n\ndef distance(a, b):\n \"\"\"The distance between two (x, y) points.\"\"\"\n xA, yA = a\n xB, yB = b\n return math.hypot((xA - xB), (yA - yB))\n\n\ndef distance_squared(a, b):\n \"\"\"The square of the distance between two (x, y) points.\"\"\"\n xA, yA = a\n xB, yB = b\n return (xA - xB) ** 2 + (yA - yB) ** 2\n\n\ndef vector_clip(vector, lowest, highest):\n \"\"\"Return vector, except if any element is less than the corresponding\n value of lowest or more than the corresponding value of highest, clip to\n those values.\"\"\"\n return type(vector)(map(clip, vector, lowest, highest))\n\n\n# ______________________________________________________________________________\n# Misc Functions\n\nclass injection():\n \"\"\"Dependency injection of temporary values for global functions/classes/etc.\n E.g., `with injection(DataBase=MockDataBase): ...`\"\"\"\n\n def __init__(self, **kwds):\n self.new = kwds\n\n def __enter__(self):\n self.old = {v: globals()[v] for v in self.new}\n globals().update(self.new)\n\n def __exit__(self, type, value, traceback):\n globals().update(self.old)\n\n\ndef memoize(fn, slot=None, maxsize=32):\n \"\"\"Memoize fn: make it remember the computed value for any argument list.\n If slot is specified, store result in that slot of first argument.\n If slot is false, use lru_cache for caching the values.\"\"\"\n if slot:\n def memoized_fn(obj, *args):\n if hasattr(obj, slot):\n return getattr(obj, slot)\n else:\n val = fn(obj, *args)\n setattr(obj, slot, val)\n return val\n else:\n @functools.lru_cache(maxsize=maxsize)\n def memoized_fn(*args):\n return fn(*args)\n\n return memoized_fn\n\n\ndef name(obj):\n \"\"\"Try to find some reasonable name for the object.\"\"\"\n return (getattr(obj, 'name', 0) or getattr(obj, '__name__', 0) or\n getattr(getattr(obj, '__class__', 0), '__name__', 0) or\n str(obj))\n\n\ndef isnumber(x):\n \"\"\"Is x a number?\"\"\"\n return hasattr(x, '__int__')\n\n\ndef issequence(x):\n \"\"\"Is x a sequence?\"\"\"\n return isinstance(x, collections.abc.Sequence)\n\n\ndef print_table(table, header=None, sep=' ', numfmt='{}'):\n \"\"\"Print a list of lists as a table, so that columns line up nicely.\n header, if specified, will be printed as the first row.\n numfmt is the format for all numbers; you might want e.g. '{:.2f}'.\n (If you want different formats in different columns,\n don't use print_table.) sep is the separator between columns.\"\"\"\n justs = ['rjust' if isnumber(x) else 'ljust' for x in table[0]]\n\n if header:\n table.insert(0, header)\n\n table = [[numfmt.format(x) if isnumber(x) else x for x in row]\n for row in table]\n\n sizes = list(map(lambda seq: max(map(len, seq)), list(zip(*[map(str, row) for row in table]))))\n\n for row in table:\n print(sep.join(getattr(str(x), j)(size) for (j, size, x) in zip(justs, sizes, row)))\n\n\ndef open_data(name, mode='r'):\n aima_root = os.path.dirname(__file__)\n aima_file = os.path.join(aima_root, *['aima-data', name])\n\n return open(aima_file, mode=mode)\n\n\ndef failure_test(algorithm, tests):\n \"\"\"Grades the given algorithm based on how many tests it passes.\n Most algorithms have arbitrary output on correct execution, which is difficult\n to check for correctness. On the other hand, a lot of algorithms output something\n particular on fail (for example, False, or None).\n tests is a list with each element in the form: (values, failure_output).\"\"\"\n from statistics import mean\n return mean(int(algorithm(x) != y) for x, y in tests)\n\n\n# ______________________________________________________________________________\n# Expressions\n\n# See https://docs.python.org/3/reference/expressions.html#operator-precedence\n# See https://docs.python.org/3/reference/datamodel.html#special-method-names\n\nclass Expr:\n \"\"\"A mathematical expression with an operator and 0 or more arguments.\n op is a str like '+' or 'sin'; args are Expressions.\n Expr('x') or Symbol('x') creates a symbol (a nullary Expr).\n Expr('-', x) creates a unary; Expr('+', x, 1) creates a binary.\"\"\"\n\n def __init__(self, op, *args):\n self.op = str(op)\n self.args = args\n\n # Operator overloads\n def __neg__(self):\n return Expr('-', self)\n\n def __pos__(self):\n return Expr('+', self)\n\n def __invert__(self):\n return Expr('~', self)\n\n def __add__(self, rhs):\n return Expr('+', self, rhs)\n\n def __sub__(self, rhs):\n return Expr('-', self, rhs)\n\n def __mul__(self, rhs):\n return Expr('*', self, rhs)\n\n def __pow__(self, rhs):\n return Expr('**', self, rhs)\n\n def __mod__(self, rhs):\n return Expr('%', self, rhs)\n\n def __and__(self, rhs):\n return Expr('&', self, rhs)\n\n def __xor__(self, rhs):\n return Expr('^', self, rhs)\n\n def __rshift__(self, rhs):\n return Expr('>>', self, rhs)\n\n def __lshift__(self, rhs):\n return Expr('<<', self, rhs)\n\n def __truediv__(self, rhs):\n return Expr('/', self, rhs)\n\n def __floordiv__(self, rhs):\n return Expr('//', self, rhs)\n\n def __matmul__(self, rhs):\n return Expr('@', self, rhs)\n\n def __or__(self, rhs):\n \"\"\"Allow both P | Q, and P |'==>'| Q.\"\"\"\n if isinstance(rhs, Expression):\n return Expr('|', self, rhs)\n else:\n return PartialExpr(rhs, self)\n\n # Reverse operator overloads\n def __radd__(self, lhs):\n return Expr('+', lhs, self)\n\n def __rsub__(self, lhs):\n return Expr('-', lhs, self)\n\n def __rmul__(self, lhs):\n return Expr('*', lhs, self)\n\n def __rdiv__(self, lhs):\n return Expr('/', lhs, self)\n\n def __rpow__(self, lhs):\n return Expr('**', lhs, self)\n\n def __rmod__(self, lhs):\n return Expr('%', lhs, self)\n\n def __rand__(self, lhs):\n return Expr('&', lhs, self)\n\n def __rxor__(self, lhs):\n return Expr('^', lhs, self)\n\n def __ror__(self, lhs):\n return Expr('|', lhs, self)\n\n def __rrshift__(self, lhs):\n return Expr('>>', lhs, self)\n\n def __rlshift__(self, lhs):\n return Expr('<<', lhs, self)\n\n def __rtruediv__(self, lhs):\n return Expr('/', lhs, self)\n\n def __rfloordiv__(self, lhs):\n return Expr('//', lhs, self)\n\n def __rmatmul__(self, lhs):\n return Expr('@', lhs, self)\n\n def __call__(self, *args):\n \"\"\"Call: if 'f' is a Symbol, then f(0) == Expr('f', 0).\"\"\"\n if self.args:\n raise ValueError('can only do a call for a Symbol, not an Expr')\n else:\n return Expr(self.op, *args)\n\n # Equality and repr\n def __eq__(self, other):\n \"\"\"x == y' evaluates to True or False; does not build an Expr.\"\"\"\n return (isinstance(other, Expr)\n and self.op == other.op\n and self.args == other.args)\n\n def __lt__(self, other):\n return (isinstance(other, Expr)\n and str(self) < str(other))\n\n def __hash__(self):\n return hash(self.op) ^ hash(self.args)\n\n def __repr__(self):\n op = self.op\n args = [str(arg) for arg in self.args]\n if op.isidentifier(): # f(x) or f(x, y)\n return '{}({})'.format(op, ', '.join(args)) if args else op\n elif len(args) == 1: # -x or -(x + 1)\n return op + args[0]\n else: # (x - y)\n opp = (' ' + op + ' ')\n return '(' + opp.join(args) + ')'\n\n\n# An 'Expression' is either an Expr or a Number.\n# Symbol is not an explicit type; it is any Expr with 0 args.\n\n\nNumber = (int, float, complex)\nExpression = (Expr, Number)\n\n\ndef Symbol(name):\n \"\"\"A Symbol is just an Expr with no args.\"\"\"\n return Expr(name)\n\n\ndef symbols(names):\n \"\"\"Return a tuple of Symbols; names is a comma/whitespace delimited str.\"\"\"\n return tuple(Symbol(name) for name in names.replace(',', ' ').split())\n\n\ndef subexpressions(x):\n \"\"\"Yield the subexpressions of an Expression (including x itself).\"\"\"\n yield x\n if isinstance(x, Expr):\n for arg in x.args:\n yield from subexpressions(arg)\n\n\ndef arity(expression):\n \"\"\"The number of sub-expressions in this expression.\"\"\"\n if isinstance(expression, Expr):\n return len(expression.args)\n else: # expression is a number\n return 0\n\n\n# For operators that are not defined in Python, we allow new InfixOps:\n\n\nclass PartialExpr:\n \"\"\"Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q.\"\"\"\n\n def __init__(self, op, lhs):\n self.op, self.lhs = op, lhs\n\n def __or__(self, rhs):\n return Expr(self.op, self.lhs, rhs)\n\n def __repr__(self):\n return \"PartialExpr('{}', {})\".format(self.op, self.lhs)\n\n\ndef expr(x):\n \"\"\"Shortcut to create an Expression. x is a str in which:\n - identifiers are automatically defined as Symbols.\n - ==> is treated as an infix |'==>'|, as are <== and <=>.\n If x is already an Expression, it is returned unchanged. Example:\n >>> expr('P & Q ==> Q')\n ((P & Q) ==> Q)\n \"\"\"\n if isinstance(x, str):\n return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol))\n else:\n return x\n\n\ninfix_ops = '==> <== <=>'.split()\n\n\ndef expr_handle_infix_ops(x):\n \"\"\"Given a str, return a new str with ==> replaced by |'==>'|, etc.\n >>> expr_handle_infix_ops('P ==> Q')\n \"P |'==>'| Q\"\n \"\"\"\n for op in infix_ops:\n x = x.replace(op, '|' + repr(op) + '|')\n return x\n\n\nclass defaultkeydict(collections.defaultdict):\n \"\"\"Like defaultdict, but the default_factory is a function of the key.\n >>> d = defaultkeydict(len); d['four']\n 4\n \"\"\"\n\n def __missing__(self, key):\n self[key] = result = self.default_factory(key)\n return result\n\n\nclass hashabledict(dict):\n \"\"\"Allows hashing by representing a dictionary as tuple of key:value pairs\n May cause problems as the hash value may change during runtime\n \"\"\"\n\n def __hash__(self):\n return 1\n\n\n# ______________________________________________________________________________\n# Queues: Stack, FIFOQueue, PriorityQueue\n# Stack and FIFOQueue are implemented as list and collection.deque\n# PriorityQueue is implemented here\n\n\nclass PriorityQueue:\n \"\"\"A Queue in which the minimum (or maximum) element (as determined by f and\n order) is returned first.\n If order is 'min', the item with minimum f(x) is\n returned first; if order is 'max', then it is the item with maximum f(x).\n Also supports dict-like lookup.\"\"\"\n\n def __init__(self, order='min', f=lambda x: x):\n self.heap = []\n\n if order == 'min':\n self.f = f\n elif order == 'max': # now item with max f(x)\n self.f = lambda x: -f(x) # will be popped first\n else:\n raise ValueError(\"order must be either 'min' or 'max'.\")\n\n def append(self, item):\n \"\"\"Insert item at its correct position.\"\"\"\n heapq.heappush(self.heap, (self.f(item), item))\n\n def extend(self, items):\n \"\"\"Insert each item in items at its correct position.\"\"\"\n for item in items:\n self.append(item)\n\n def pop(self):\n \"\"\"Pop and return the item (with min or max f(x) value)\n depending on the order.\"\"\"\n if self.heap:\n return heapq.heappop(self.heap)[1]\n else:\n raise Exception('Trying to pop from empty PriorityQueue.')\n \n def getvalue(self, key):\n \"\"\"Returns the first value associated with key in PriorityQueue.\n Raises KeyError if key is not present.\"\"\"\n for value, item in self.heap:\n if item == key:\n return value, item\n raise KeyError(str(key) + \" is not in the priority queue\")\n\n def __len__(self):\n \"\"\"Return current capacity of PriorityQueue.\"\"\"\n return len(self.heap)\n\n def __contains__(self, key):\n \"\"\"Return True if the key is in PriorityQueue.\"\"\"\n return any([item == key for _, item in self.heap])\n \n def __getitem__(self, key):\n \"\"\"Returns the first value associated with key in PriorityQueue.\n Raises KeyError if key is not present.\"\"\"\n for value, item in self.heap:\n if item == key:\n return item\n raise KeyError(str(key) + \" is not in the priority queue\")\n\n def __delitem__(self, key):\n \"\"\"Delete the first occurrence of key.\"\"\"\n try:\n del self.heap[[item == key for _, item in self.heap].index(True)]\n except ValueError:\n raise KeyError(str(key) + \" is not in the priority queue\")\n heapq.heapify(self.heap)\n\n\n# ______________________________________________________________________________\n# Monte Carlo tree node and ucb function\nclass MCT_Node:\n \"\"\"Node in the Monte Carlo search tree, keeps track of the children states\"\"\"\n\n def __init__(self, parent=None, state=None, U=0, N=0):\n self.__dict__.update(parent=parent, state=state, U=U, N=N)\n self.children = {}\n self.actions = None\n\n\ndef ucb(n, C=1.4):\n return (float('inf') if n.N == 0 else\n n.U / n.N + C * math.sqrt(math.log(n.parent.N) / n.N))\n\n\n# ______________________________________________________________________________\n# Useful Shorthands\n\n\nclass Bool(int):\n \"\"\"Just like `bool`, except values display as 'T' and 'F' instead of 'True' and 'False'\"\"\"\n __str__ = __repr__ = lambda self: 'T' if self else 'F'\n\n\nT = Bool(True)\nF = Bool(False)\n"
]
| [
[
"numpy.tanh"
]
]
|
Wastedzz/deep_gcns_torch | [
"e74e16b98d7b27b585832575453ff9ff1a5d20d4"
]
| [
"examples/ogb/ogbg_ppa/main.py"
]
| [
"import torch\nfrom torch_geometric.data import DataLoader\nimport torch.optim as optim\nfrom model import DeeperGCN\nfrom tqdm import tqdm\nfrom args import ArgsInit\nfrom utils.ckpt_util import save_ckpt\nfrom utils.data_util import add_zeros, extract_node_feature\nimport logging\nfrom functools import partial\nimport time\nimport statistics\nfrom ogb.graphproppred import PygGraphPropPredDataset, Evaluator\nimport wandb\nimport os\nimport matplotlib.pyplot as plt\n\n\n\ndef train(model, device, loader, optimizer, criterion, use_osreg=False):\n loss_list = []\n model.train()\n std_l = 0.\n\n for step, batch in enumerate(tqdm(loader, desc=\"Iteration\")):\n batch = batch.to(device)\n\n if batch.x.shape[0] == 1 or batch.batch[-1] == 0:\n pass\n else:\n pred, loss_reg, std = model(batch)\n std_l += std\n\n optimizer.zero_grad()\n\n loss = criterion(pred.to(torch.float32), batch.y.view(-1, ))\n if use_osreg:\n loss = loss + loss_reg\n loss.backward()\n optimizer.step()\n loss_list.append(loss.item())\n return statistics.mean(loss_list), std_l / (step + 1)\n\n\[email protected]_grad()\ndef eval(model, device, loader, evaluator):\n model.eval()\n y_true = []\n y_pred = []\n\n for step, batch in enumerate(tqdm(loader, desc=\"Iteration\")):\n batch = batch.to(device)\n\n if batch.x.shape[0] == 1:\n pass\n else:\n pred, _, _ = model(batch)\n y_true.append(batch.y.view(-1, 1).detach().cpu())\n y_pred.append(torch.argmax(pred.detach(), dim=1).view(-1, 1).cpu())\n\n y_true = torch.cat(y_true, dim=0).numpy()\n y_pred = torch.cat(y_pred, dim=0).numpy()\n\n input_dict = {\"y_true\": y_true, \"y_pred\": y_pred}\n\n return evaluator.eval(input_dict)['acc']\n\n\ndef main():\n args = ArgsInit().save_exp()\n\n log_to_wandb = args.log_to_wandb\n if log_to_wandb:\n wandb.init(project='deeper-gcn',\n group=args.group,\n config=vars(args),\n entity='cgwang',\n # save_code=True\n )\n\n if args.use_gpu:\n device = torch.device(\"cuda:\" + str(args.device)) if torch.cuda.is_available() else torch.device(\"cpu\")\n else:\n device = torch.device('cpu')\n\n sub_dir = 'BS_{}'.format(args.batch_size)\n\n if args.not_extract_node_feature:\n dataset = PygGraphPropPredDataset(name=args.dataset,\n transform=add_zeros)\n else:\n extract_node_feature_func = partial(extract_node_feature, reduce=args.aggr)\n dataset = PygGraphPropPredDataset(name=args.dataset,\n transform=extract_node_feature_func)\n\n sub_dir = sub_dir + '-NF_{}'.format(args.aggr)\n\n args.num_tasks = dataset.num_classes\n evaluator = Evaluator(args.dataset)\n\n logging.info('%s' % args)\n\n split_idx = dataset.get_idx_split()\n\n train_loader = DataLoader(dataset[split_idx[\"train\"]], batch_size=args.batch_size, shuffle=True,\n num_workers=args.num_workers)\n valid_loader = DataLoader(dataset[split_idx[\"valid\"]], batch_size=args.batch_size, shuffle=False,\n num_workers=args.num_workers)\n test_loader = DataLoader(dataset[split_idx[\"test\"]], batch_size=args.batch_size, shuffle=False,\n num_workers=args.num_workers)\n\n model = DeeperGCN(args).to(device)\n\n logging.info(model)\n\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n criterion = torch.nn.CrossEntropyLoss()\n\n results = {'highest_valid': 0,\n 'final_train': 0,\n 'final_test': 0,\n 'highest_train': 0}\n\n start_time = time.time()\n\n evaluate = True\n\n for epoch in range(1, args.epochs + 1):\n logging.info(\"=====Epoch {}\".format(epoch))\n logging.info('Training...')\n\n epoch_loss,std_l = train(model, device, train_loader, optimizer, criterion, use_osreg=args.use_osreg)\n\n if args.num_layers > args.num_layers_threshold:\n if epoch % args.eval_steps != 0:\n evaluate = False\n else:\n evaluate = True\n\n # model.print_params(epoch=epoch)\n if os.path.isdir(args.save + '/std_info'):\n os.mkdir(args.save + '/std_info')\n if not os.path.exists(args.save + '/std'):\n os.mkdir(args.save + '/std')\n torch.save(std_l, args.save + '/std/epoch-{}.pt'.format(epoch))\n\n plt.figure()\n plt.plot(std_l)\n if not os.path.exists(args.save + '/fig'):\n os.mkdir(args.save + '/fig')\n plt.savefig(args.save + '/fig/epoch-{}'.format(epoch))\n\n if evaluate:\n\n logging.info('Evaluating...')\n\n train_accuracy = eval(model, device, train_loader, evaluator)\n valid_accuracy = eval(model, device, valid_loader, evaluator)\n test_accuracy = eval(model, device, test_loader, evaluator)\n\n logging.info({'Train': train_accuracy,\n 'Validation': valid_accuracy,\n 'Test': test_accuracy})\n\n if log_to_wandb:\n wandb.log({\n 'loss': epoch_loss,\n 'Train_Acc': train_accuracy,\n 'Validation_Acc': valid_accuracy,\n 'Test_Acc': test_accuracy})\n\n if train_accuracy > results['highest_train']:\n\n results['highest_train'] = train_accuracy\n\n if valid_accuracy > results['highest_valid']:\n results['highest_valid'] = valid_accuracy\n results['final_train'] = train_accuracy\n results['final_test'] = test_accuracy\n\n filename = save_ckpt(model, optimizer,\n round(epoch_loss, 4), epoch,\n args.model_save_path,\n sub_dir, name_post='valid_best')\n if log_to_wandb:\n wandb.save(filename)\n\n logging.info(\"%s\" % results)\n if log_to_wandb:\n wandb.log(\n {'final_test': results['final_test']}\n )\n\n # end_time = time.time()\n # total_time = end_time - start_time\n # logging.info('Total time: {}'.format(time.strftime('%H:%M:%S', time.gmtime(total_time))))\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"torch.device",
"torch.cat",
"torch.no_grad",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"torch.cuda.is_available",
"torch.nn.CrossEntropyLoss"
]
]
|
Mele-Lab/2020_GenomeBiology_CisTransMPRA | [
"55da814dee39f232b746deb6c8110cd15d77c3dd"
]
| [
"analysis/01__mpra/03__activs_general/03__activs_general.py"
]
| [
"#!/usr/bin/env python\n# coding: utf-8\n\n# # 03__activs_general\n# \n# in this notebook, i look at activities of TSSs in native contexts (human seqs in hESCs, mouse seqs in mESCs) compared to negative and positive controls. i also look at diffs in activity between tiles\n\n# In[1]:\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\nimport seaborn as sns\nimport sys\n\nfrom scipy.stats import spearmanr\n\n# import utils\nsys.path.append(\"../../../utils\")\nfrom plotting_utils import *\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().run_line_magic('config', \"InlineBackend.figure_format = 'svg'\")\nmpl.rcParams['figure.autolayout'] = False\n\n\n# In[2]:\n\n\nsns.set(**PAPER_PRESET)\nfontsize = PAPER_FONTSIZE\n\n\n# In[3]:\n\n\nnp.random.seed(2019)\n\n\n# ## functions\n\n# In[4]:\n\n\ndef consolidate_cage(row, biotype_col):\n if row[biotype_col] == \"reclassified - CAGE peak\":\n return \"no CAGE activity\"\n else:\n return row[biotype_col]\n\n\n# In[5]:\n\n\ndef fix_cleaner_biotype(row, biotype_col):\n try:\n if row[\"name\"] == \"random_sequence\":\n return \"negative control\"\n elif \"samp\" in row.element:\n return \"positive control\"\n else:\n return row[biotype_col]\n except:\n return row[biotype_col]\n\n\n# In[6]:\n\n\ndef is_sig(row, col):\n if row[col] < 0.05:\n return \"sig\"\n else:\n return \"not sig\"\n\n\n# In[7]:\n\n\ndef fix_cage_exp(row, col):\n if row[col] == \"no cage activity\":\n return 0\n else:\n return float(row[col])\n\n\n# ## variables\n\n# In[8]:\n\n\ndata_dir = \"../../../data/02__mpra/02__activs\"\nalpha_f = \"%s/alpha_per_elem.quantification.txt\" % data_dir\n\n\n# In[9]:\n\n\nindex_f = \"../../../data/01__design/02__index/TWIST_pool4_v8_final.with_element_id.txt.gz\"\n\n\n# In[10]:\n\n\ntss_map_f = \"../../../data/01__design/01__mpra_list/mpra_tss.with_ids.RECLASSIFIED.txt\"\n\n\n# ## 1. import files\n\n# In[11]:\n\n\nalpha = pd.read_table(alpha_f, sep=\"\\t\")\nalpha.reset_index(inplace=True)\nalpha.head()\n\n\n# In[12]:\n\n\nindex = pd.read_table(index_f, sep=\"\\t\")\n\n\n# In[13]:\n\n\nindex_elem = index[[\"element\", \"tile_type\", \"element_id\", \"name\", \"tile_number\", \"chrom\", \"strand\", \"actual_start\", \n \"actual_end\", \"dupe_info\"]]\nindex_elem = index_elem.drop_duplicates()\n\n\n# In[14]:\n\n\ntss_map = pd.read_table(tss_map_f, sep=\"\\t\")\ntss_map.head()\n\n\n# ## 2. merge alphas w/ index\n\n# In[15]:\n\n\npos_ctrls = alpha[alpha[\"index\"].str.contains(\"__samp\")]\npos_ctrls[\"HUES64_log\"] = np.log10(pos_ctrls[\"HUES64\"])\npos_ctrls[\"mESC_log\"] = np.log10(pos_ctrls[\"mESC\"])\nlen(pos_ctrls)\n\n\n# In[16]:\n\n\nalpha = alpha[~alpha[\"index\"].str.contains(\"__samp\")]\nlen(alpha)\n\n\n# In[17]:\n\n\ndata = alpha.merge(index_elem, left_on=\"index\", right_on=\"element\", how=\"left\")\ndata.drop(\"index\", axis=1, inplace=True)\ndata.head()\n\n\n# In[18]:\n\n\ndata[\"HUES64_log\"] = np.log10(data[\"HUES64\"])\ndata[\"mESC_log\"] = np.log10(data[\"mESC\"])\ndata.sample(5)\n\n\n# ## 3. compare activities across biotypes + controls\n\n# In[19]:\n\n\ndata[\"tss_id\"] = data[\"name\"].str.split(\"__\", expand=True)[1]\ndata[\"species\"] = data[\"name\"].str.split(\"_\", expand=True)[0]\ndata[\"tss_tile_num\"] = data[\"name\"].str.split(\"__\", expand=True)[2]\ndata.sample(5)\n\n\n# In[20]:\n\n\npos_ctrls.columns = [\"element\", \"HUES64\", \"mESC\", \"HUES64_pval\", \"mESC_pval\", \"HUES64_padj\", \"mESC_padj\", \n \"HUES64_log\", \"mESC_log\"]\npos_ctrls.head()\n\n\n# In[21]:\n\n\nhuman_df = data[(data[\"species\"] == \"HUMAN\") | (data[\"name\"] == \"random_sequence\")]\nmouse_df = data[(data[\"species\"] == \"MOUSE\") | (data[\"name\"] == \"random_sequence\")]\n\nhuman_df_w_ctrls = human_df.append(pos_ctrls)\nmouse_df_w_ctrls = mouse_df.append(pos_ctrls)\n\nhuman_df_w_ctrls = human_df_w_ctrls.merge(tss_map[[\"hg19_id\", \"biotype_hg19\", \"minimal_biotype_hg19\", \n \"stem_exp_hg19\", \"orig_species\", \"max_cage_hg19\"]], \n left_on=\"tss_id\", right_on=\"hg19_id\", how=\"left\")\nmouse_df_w_ctrls = mouse_df_w_ctrls.merge(tss_map[[\"mm9_id\", \"biotype_mm9\", \"minimal_biotype_mm9\", \"stem_exp_mm9\", \n \"orig_species\", \"max_cage_mm9\"]], \n left_on=\"tss_id\", right_on=\"mm9_id\", how=\"left\")\nmouse_df_w_ctrls.sample(5)\n\n\n# In[22]:\n\n\nhuman_df_w_ctrls[\"minimal_biotype_hg19\"] = human_df_w_ctrls.apply(fix_cleaner_biotype, \n biotype_col=\"minimal_biotype_hg19\",\n axis=1)\nhuman_df_w_ctrls.minimal_biotype_hg19.value_counts()\n\n\n# In[23]:\n\n\nmouse_df_w_ctrls[\"minimal_biotype_mm9\"] = mouse_df_w_ctrls.apply(fix_cleaner_biotype, \n biotype_col=\"minimal_biotype_mm9\",\n axis=1)\nmouse_df_w_ctrls.minimal_biotype_mm9.value_counts()\n\n\n# In[24]:\n\n\nmin_ctrl_order = [\"negative control\", \"no CAGE activity\", \"eRNA\", \n \"lncRNA\", \"mRNA\", \"positive control\"]\n\nmin_human_ctrl_pal = {\"negative control\": \"lightgray\", \"no CAGE activity\": \"gray\", \"reclassified - CAGE peak\": \"gray\",\n \"eRNA\": sns.color_palette(\"Set2\")[1], \"lncRNA\": sns.color_palette(\"Set2\")[1], \n \"mRNA\": sns.color_palette(\"Set2\")[1], \"positive control\": \"black\"}\n\nmin_mouse_ctrl_pal = {\"negative control\": \"lightgray\", \"no CAGE activity\": \"gray\", \"reclassified - CAGE peak\": \"gray\",\n \"eRNA\": sns.color_palette(\"Set2\")[0], \"lncRNA\": sns.color_palette(\"Set2\")[0], \n \"mRNA\": sns.color_palette(\"Set2\")[0],\"positive control\": \"black\"}\n\n\n# In[25]:\n\n\nfig = plt.figure(figsize=(2.35, 1.5))\nax = sns.boxplot(data=human_df_w_ctrls, x=\"minimal_biotype_hg19\", y=\"HUES64\", flierprops = dict(marker='o', markersize=5),\n order=min_ctrl_order, palette=min_human_ctrl_pal)\nmimic_r_boxplot(ax)\n\nax.set_xticklabels(min_ctrl_order, rotation=50, ha='right', va='top')\nax.set_xlabel(\"\")\nax.set_yscale(\"symlog\")\nax.set_ylabel(\"MPRA activity in hESCs\")\n\nfor i, label in enumerate(min_ctrl_order):\n n = len(human_df_w_ctrls[human_df_w_ctrls[\"minimal_biotype_hg19\"] == label])\n color = min_human_ctrl_pal[label]\n ax.annotate(str(n), xy=(i, -0.7), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=color, size=fontsize)\n\nax.set_ylim((-1, 60))\nplt.show()\nfig.savefig(\"Fig1D_1.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\nplt.close()\n\n\n# In[26]:\n\n\nfig = plt.figure(figsize=(2.35, 1.5))\nax = sns.boxplot(data=mouse_df_w_ctrls, x=\"minimal_biotype_mm9\", y=\"mESC\", flierprops = dict(marker='o', markersize=5),\n order=min_ctrl_order, palette=min_mouse_ctrl_pal)\nmimic_r_boxplot(ax)\n\nax.set_xticklabels(min_ctrl_order, rotation=50, ha='right', va='top')\nax.set_xlabel(\"\")\nax.set_yscale(\"symlog\")\nax.set_ylabel(\"MPRA activity in mESCs\")\n\nfor i, label in enumerate(min_ctrl_order):\n n = len(mouse_df_w_ctrls[mouse_df_w_ctrls[\"minimal_biotype_mm9\"] == label])\n color = min_mouse_ctrl_pal[label]\n ax.annotate(str(n), xy=(i, -0.7), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=color, size=fontsize)\n\nax.set_ylim((-1, 60))\nplt.show()\nfig.savefig(\"Fig1D_2.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\nplt.close()\n\n\n# ## 4. compare activities across tiles\n\n# In[27]:\n\n\ndf = data[data[\"tss_tile_num\"].isin([\"tile1\", \"tile2\"])]\nhuman_df = df[df[\"species\"] == \"HUMAN\"]\nmouse_df = df[df[\"species\"] == \"MOUSE\"]\n\nhuman_df = human_df.merge(tss_map[[\"hg19_id\", \"minimal_biotype_hg19\", \"stem_exp_hg19\", \"orig_species\"]], left_on=\"tss_id\", \n right_on=\"hg19_id\", how=\"right\")\nmouse_df = mouse_df.merge(tss_map[[\"mm9_id\", \"minimal_biotype_mm9\", \"stem_exp_mm9\", \"orig_species\"]], left_on=\"tss_id\", \n right_on=\"mm9_id\", how=\"right\")\nmouse_df.sample(5)\n\n\n# In[30]:\n\n\nc = 1\nfor df, species, colname, color, sp in zip([human_df, mouse_df], [\"hESCs\", \"mESCs\"], [\"HUES64\", \"mESC\"], \n [sns.color_palette(\"Set2\")[1], sns.color_palette(\"Set2\")[0]],\n [\"hg19\", \"mm9\"]):\n fig = plt.figure(figsize=(2, 1.5))\n ax = sns.boxplot(data=df, x=\"minimal_biotype_%s\" % sp, y=colname, hue=\"tss_tile_num\", \n flierprops = dict(marker='o', markersize=5),\n order=[\"eRNA\", \"lncRNA\", \"mRNA\"], hue_order=[\"tile1\", \"tile2\"],\n palette={\"tile1\": sns.light_palette(color)[5], \"tile2\": sns.light_palette(color)[2]})\n mimic_r_boxplot(ax)\n ax.set_xticklabels([\"eRNA\", \"lncRNA\", \"mRNA\"], rotation=50, ha=\"right\", va=\"top\")\n\n # calc p-vals b/w dists\n for i, label in enumerate([\"eRNA\", \"lncRNA\", \"mRNA\"]):\n sub = df[df[\"minimal_biotype_%s\" % sp] == label]\n tile1_dist = np.asarray(sub[sub[\"tss_tile_num\"] == \"tile1\"][colname])\n tile2_dist = np.asarray(sub[sub[\"tss_tile_num\"] == \"tile2\"][colname])\n\n tile1_dist = tile1_dist[~np.isnan(tile1_dist)]\n tile2_dist = tile2_dist[~np.isnan(tile2_dist)]\n\n tile_u, tile_pval = stats.mannwhitneyu(tile1_dist, tile2_dist, alternative=\"greater\", use_continuity=False)\n print(tile_pval)\n\n annotate_pval(ax, i-0.2, i+0.2, 50, 0, 50, tile_pval, fontsize-1)\n \n ax.set_yscale('symlog')\n ax.set_ylabel(\"MPRA activity in %s\" % species)\n ax.set_xlabel(\"\")\n ax.get_legend().remove()\n# ax.set_title(species)\n ax.set_ylim((-0.1, 100))\n fig.savefig(\"Fig1E_%s.pdf\" % c, dpi=\"figure\", bbox_inches=\"tight\")\n c += 1\n\n\n# find max tile in each species\n\n# In[31]:\n\n\nhuman_max = human_df[[\"hg19_id\", \"tss_tile_num\", \"HUES64\"]]\nhuman_max = human_max.sort_values(by=\"HUES64\", ascending=False)\nhuman_max = human_max.drop_duplicates(subset=[\"hg19_id\"])\nhuman_max = human_max.sort_values(by=\"hg19_id\")\nhuman_max.head()\n\n\n# In[32]:\n\n\nhuman_grp = human_df[[\"hg19_id\", \"tss_tile_num\", \"HUES64\"]]\nhuman_grp = human_grp[~pd.isnull(human_grp[\"HUES64\"])]\nhuman_grp = human_grp.groupby(\"hg19_id\")[\"tss_tile_num\"].agg(\"count\").reset_index()\nhuman_grp.columns = [\"hg19_id\", \"n_tiles_hg19\"]\nprint(len(human_grp))\nlen(human_grp[human_grp[\"n_tiles_hg19\"] == 2])\n\n\n# In[33]:\n\n\nmouse_max = mouse_df[[\"mm9_id\", \"tss_tile_num\", \"mESC\"]]\nmouse_max = mouse_max.sort_values(by=\"mESC\", ascending=False)\nmouse_max = mouse_max.drop_duplicates(subset=[\"mm9_id\"])\nmouse_max = mouse_max.sort_values(by=\"mm9_id\")\nmouse_max.head()\n\n\n# In[34]:\n\n\nmouse_grp = mouse_df[[\"mm9_id\", \"tss_tile_num\", \"mESC\"]]\nmouse_grp = mouse_grp[~pd.isnull(mouse_grp[\"mESC\"])]\nmouse_grp = mouse_grp.groupby(\"mm9_id\")[\"tss_tile_num\"].agg(\"count\").reset_index()\nmouse_grp.columns = [\"mm9_id\", \"n_tiles_mm9\"]\nprint(len(mouse_grp))\nlen(mouse_grp[mouse_grp[\"n_tiles_mm9\"] == 2])\n\n\n# In[35]:\n\n\ntss_map_mrg = tss_map.merge(human_max[[\"hg19_id\", \"tss_tile_num\"]], on=\"hg19_id\", how=\"left\", \n suffixes=(\"\", \"\")).merge(mouse_max[[\"mm9_id\", \"tss_tile_num\"]],\n on=\"mm9_id\", how=\"left\", suffixes=(\"_max_hg19\", \n \"_max_mm9\"))\ntss_map_mrg = tss_map_mrg.merge(human_grp, on=\"hg19_id\", how=\"left\").merge(mouse_grp, on=\"mm9_id\", how=\"left\")\ntss_map_mrg.sample(10)\n\n\n# In[36]:\n\n\nprint(len(tss_map_mrg))\nprint(len(tss_map_mrg[(tss_map_mrg[\"n_tiles_hg19\"] >= 2) & (tss_map_mrg[\"n_tiles_mm9\"] >= 2)]))\n\n\n# In[37]:\n\n\ntss_map_mrg.tss_tile_num_max_hg19.value_counts()\n\n\n# In[38]:\n\n\ntss_map_mrg.tss_tile_num_max_mm9.value_counts()\n\n\n# In[39]:\n\n\nfig, axarr = plt.subplots(figsize=(3, 1.5), nrows=1, ncols=2, sharey=True)\n\nax0 = axarr[0]\nax1 = axarr[1]\n\nsns.countplot(data=tss_map_mrg, x=\"minimal_biotype_hg19\", hue=\"tss_tile_num_max_hg19\", \n order=[\"eRNA\", \"lncRNA\", \"mRNA\"], hue_order=[\"tile1\", \"tile2\"],\n palette={\"tile1\": sns.light_palette(sns.color_palette(\"Set2\")[1])[5], \n \"tile2\": sns.light_palette(sns.color_palette(\"Set2\")[1])[2]},\n ax=ax0)\nax0.set_xticklabels([\"eRNA\", \"lncRNA\", \"mRNA\"], rotation=50, ha=\"right\", va=\"top\")\nax0.set_xlabel(\"\")\nax0.set_ylabel(\"count of human seqs\")\nax0.get_legend().remove()\n\nsns.countplot(data=tss_map_mrg, x=\"minimal_biotype_mm9\", hue=\"tss_tile_num_max_mm9\", \n order=[\"eRNA\", \"lncRNA\", \"mRNA\"], hue_order=[\"tile1\", \"tile2\"],\n palette={\"tile1\": sns.light_palette(sns.color_palette(\"Set2\")[0])[5], \n \"tile2\": sns.light_palette(sns.color_palette(\"Set2\")[0])[2]},\n ax=ax1)\nax1.set_xticklabels([\"eRNA\", \"lncRNA\", \"mRNA\"], rotation=50, ha=\"right\", va=\"top\")\nax1.set_xlabel(\"\")\nax1.get_legend().remove()\nax1.set_ylabel(\"count of mouse seqs\")\n\nfig.savefig(\"FigS5B.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\n\n\n# In[40]:\n\n\ndef tile_match(row):\n if pd.isnull(row.tss_tile_num_max_hg19) or pd.isnull(row.tss_tile_num_max_mm9):\n return np.nan\n else:\n if row.tss_tile_num_max_hg19 == \"tile1\":\n if row.tss_tile_num_max_mm9 == \"tile1\":\n return \"tile1:tile1\"\n else:\n return \"tile1:tile2\"\n else:\n if row.tss_tile_num_max_mm9 == \"tile2\":\n return \"tile2:tile2\"\n else:\n return \"tile1:tile2\"\n\n\n# In[41]:\n\n\ntss_map_mrg[\"tile_match\"] = tss_map_mrg.apply(tile_match, axis=1)\ntss_map_mrg.tile_match.value_counts()\n\n\n# In[42]:\n\n\ntss_map_mrg[tss_map_mrg[\"tile_match\"] == \"tile1:tile2\"].sample(5)\n\n\n# In[43]:\n\n\nhuman_df[human_df[\"hg19_id\"] == \"h.299\"][[\"hg19_id\", \"tss_tile_num\", \"HUES64\"]].sort_values(by=\"tss_tile_num\")\n\n\n# In[44]:\n\n\nmouse_df[mouse_df[\"mm9_id\"] == \"m.192\"][[\"mm9_id\", \"tss_tile_num\", \"mESC\"]].sort_values(by=\"tss_tile_num\")\n\n\n# In[45]:\n\n\nfig = plt.figure(figsize=(1, 1))\n\nax = sns.countplot(data=tss_map_mrg, x=\"tile_match\", color=sns.color_palette(\"Set2\")[2])\nax.set_xticklabels([\"tile1:tile1\", \"tile1:tile2\", \"tile2:tile2\"], rotation=50, ha=\"right\", va=\"top\")\n\nax.set_xlabel(\"\")\nax.set_ylabel(\"count of pairs\")\nfig.savefig(\"FigS5C.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\n\n\n# ## 5. correlate MPRA activities w/ endogenous activs\n\n# In[46]:\n\n\nhuman_tmp = human_df_w_ctrls\nhuman_tmp.columns\n\n\n# In[47]:\n\n\nhuman_tmp[\"stem_exp_hg19_fixed\"] = human_tmp.apply(fix_cage_exp, col=\"stem_exp_hg19\", axis=1)\nhuman_tmp.sample(5)\n\n\n# In[48]:\n\n\nfor tile_num in [\"tile1\", \"tile2\"]:\n df = human_tmp[(human_tmp[\"tss_tile_num\"] == tile_num) & \n (~human_tmp[\"minimal_biotype_hg19\"].isin([\"no CAGE activity\"]))]\n \n fig, ax = plt.subplots(figsize=(1.5, 1.5), nrows=1, ncols=1)\n\n df[\"stem_exp_hg19_log\"] = np.log10(df[\"stem_exp_hg19_fixed\"] + 1)\n sub = df[~pd.isnull(df[\"HUES64_log\"])]\n print(len(sub))\n\n sns.regplot(data=sub, x=\"stem_exp_hg19_log\", y=\"HUES64_log\", color=min_human_ctrl_pal[\"mRNA\"], \n scatter_kws={\"s\": 15, \"alpha\": 0.75, \"linewidth\": 0.5, \"edgecolor\": \"white\"}, fit_reg=True, ax=ax)\n\n # annotate corr\n no_nan = sub[(~pd.isnull(sub[\"stem_exp_hg19_log\"])) & (~pd.isnull(sub[\"HUES64_log\"]))]\n r, p = spearmanr(no_nan[\"stem_exp_hg19_log\"], no_nan[\"HUES64_log\"])\n\n ax.text(0.95, 0.15, \"r = {:.2f}\".format(r), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n ax.text(0.95, 0.05, \"n = %s\" % (len(no_nan)), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n\n ax.set_xlabel(\"log10(CAGE expression + 1)\\n(hESCs)\")\n ax.set_ylabel(\"log10(MPRA activity)\\n(hESCs)\")\n\n plt.show()\n #fig.savefig(\"cage_corr_human.all.%s.pdf\" % tile_num, dpi=\"figure\", bbox_inches=\"tight\")\n plt.close()\n\n\n# In[49]:\n\n\nfor tile_num in [\"tile1\", \"tile2\"]:\n df = human_tmp[(human_tmp[\"tss_tile_num\"] == tile_num)]\n \n fig, ax = plt.subplots(figsize=(1.5, 1.5), nrows=1, ncols=1)\n\n sub = df[~pd.isnull(df[\"HUES64_log\"])]\n sub[\"cage_log\"] = np.log10(sub[\"max_cage_hg19\"] + 1)\n print(len(sub))\n\n sns.regplot(data=sub, x=\"cage_log\", y=\"HUES64_log\", color=min_human_ctrl_pal[\"mRNA\"], \n scatter_kws={\"s\": 15, \"alpha\": 0.75, \"linewidth\": 0.5, \"edgecolor\": \"white\"}, fit_reg=True, ax=ax)\n\n # annotate corr\n no_nan = sub[(~pd.isnull(sub[\"cage_log\"])) & (~pd.isnull(sub[\"HUES64_log\"]))]\n r, p = spearmanr(no_nan[\"cage_log\"], no_nan[\"HUES64_log\"])\n\n ax.text(0.95, 0.15, \"r = {:.2f}\".format(r), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n ax.text(0.95, 0.05, \"n = %s\" % (len(no_nan)), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n\n ax.set_xlabel(\"log10(max CAGE counts + 1)\")\n ax.set_ylabel(\"log10(MPRA activity)\\n(hESCs)\")\n\n plt.show()\n #fig.savefig(\"cage_corr_human.all.%s.pdf\" % tile_num, dpi=\"figure\", bbox_inches=\"tight\")\n plt.close()\n\n\n# In[50]:\n\n\nmouse_tmp = mouse_df_w_ctrls\nmouse_tmp[\"stem_exp_mm9_fixed\"] = mouse_tmp.apply(fix_cage_exp, col=\"stem_exp_mm9\", axis=1)\nlen(mouse_tmp)\n\n\n# In[51]:\n\n\nfor tile_num in [\"tile1\", \"tile2\"]:\n df = mouse_tmp[(mouse_tmp[\"tss_tile_num\"] == tile_num) & \n (~mouse_tmp[\"minimal_biotype_mm9\"].isin([\"no CAGE activity\"]))]\n \n fig, ax = plt.subplots(figsize=(1.5, 1.5), nrows=1, ncols=1)\n\n df[\"stem_exp_mm9_log\"] = np.log10(df[\"stem_exp_mm9_fixed\"] + 1)\n sub = df[~pd.isnull(df[\"mESC_log\"])]\n print(len(sub))\n\n sns.regplot(data=sub, x=\"stem_exp_mm9_log\", y=\"mESC_log\", color=min_mouse_ctrl_pal[\"mRNA\"], \n scatter_kws={\"s\": 15, \"alpha\": 0.75, \"linewidth\": 0.5, \"edgecolor\": \"white\"}, fit_reg=True, ax=ax)\n\n # annotate corr\n no_nan = sub[(~pd.isnull(sub[\"stem_exp_mm9_log\"])) & (~pd.isnull(sub[\"mESC_log\"]))]\n r, p = spearmanr(no_nan[\"stem_exp_mm9_log\"], no_nan[\"mESC_log\"])\n\n ax.text(0.95, 0.15, \"r = {:.2f}\".format(r), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n ax.text(0.95, 0.05, \"n = %s\" % (len(no_nan)), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n\n ax.set_xlabel(\"log10(CAGE expression + 1)\\n(mESCs)\")\n ax.set_ylabel(\"log10(MPRA activity)\\n(mESCs)\")\n\n plt.show()\n# fig.savefig(\"cage_corr_mouse.all.%s.pdf\" % tile_num, dpi=\"figure\", bbox_inches=\"tight\")\n plt.close()\n\n\n# In[52]:\n\n\nfor tile_num in [\"tile1\", \"tile2\"]:\n df = mouse_tmp[(mouse_tmp[\"tss_tile_num\"] == tile_num)]\n \n fig, ax = plt.subplots(figsize=(1.5, 1.5), nrows=1, ncols=1)\n\n sub = df[~pd.isnull(df[\"mESC_log\"])]\n sub[\"cage_log\"] = np.log10(sub[\"max_cage_mm9\"] + 1)\n print(len(sub))\n\n sns.regplot(data=sub, x=\"cage_log\", y=\"mESC_log\", color=min_mouse_ctrl_pal[\"mRNA\"], \n scatter_kws={\"s\": 15, \"alpha\": 0.75, \"linewidth\": 0.5, \"edgecolor\": \"white\"}, fit_reg=True, ax=ax)\n\n # annotate corr\n no_nan = sub[(~pd.isnull(sub[\"cage_log\"])) & (~pd.isnull(sub[\"mESC_log\"]))]\n r, p = spearmanr(no_nan[\"cage_log\"], no_nan[\"mESC_log\"])\n\n ax.text(0.95, 0.15, \"r = {:.2f}\".format(r), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n ax.text(0.95, 0.05, \"n = %s\" % (len(no_nan)), ha=\"right\", va=\"bottom\", fontsize=fontsize,\n transform=ax.transAxes)\n\n ax.set_xlabel(\"log10(max CAGE counts + 1)\")\n ax.set_ylabel(\"log10(MPRA activity)\\n(mESCs)\")\n\n plt.show()\n #fig.savefig(\"cage_corr_mouse.all.%s.pdf\" % tile_num, dpi=\"figure\", bbox_inches=\"tight\")\n plt.close()\n\n\n# ## 6. how does endogenous CAGE expr compare between human and mouse\n\n# In[53]:\n\n\nhuman_tmp[\"species\"] = \"human\"\nmouse_tmp[\"species\"] = \"mouse\"\n\nhuman_tmp = human_tmp[[\"tss_id\", \"minimal_biotype_hg19\", \"stem_exp_hg19_fixed\", \"species\", \"max_cage_hg19\"]]\nhuman_tmp.columns = [\"tss_id\", \"minimal_biotype\", \"stem_exp_fixed\", \"species\", \"max_cage\"]\nmouse_tmp = mouse_tmp[[\"tss_id\", \"minimal_biotype_mm9\", \"stem_exp_mm9_fixed\", \"species\", \"max_cage_mm9\"]]\nmouse_tmp.columns = [\"tss_id\", \"minimal_biotype\", \"stem_exp_fixed\", \"species\", \"max_cage\"]\n\ntmp = human_tmp.append(mouse_tmp)\ntmp[\"log_stem\"] = np.log10(tmp[\"stem_exp_fixed\"]+1)\ntmp[\"log_max\"] = np.log10(tmp[\"max_cage\"]+1)\ntmp.head(5)\n\n\n# In[54]:\n\n\ntmp_pal = {\"human\": sns.color_palette(\"Set2\")[1], \"mouse\": sns.color_palette(\"Set2\")[0]}\n\n\n# In[55]:\n\n\nfig = plt.figure(figsize=(2.5, 1.5))\n\nax = sns.boxplot(data=tmp, x=\"minimal_biotype\", y=\"stem_exp_fixed\", hue=\"species\",\n flierprops = dict(marker='o', markersize=5),\n order=[\"eRNA\", \"lncRNA\", \"mRNA\"], palette=tmp_pal)\nmimic_r_boxplot(ax)\n\nax.set_xticklabels([\"eRNA\", \"lncRNA\", \"mRNA\"], rotation=50, ha='right', va='top')\nax.set_xlabel(\"\")\nax.set_yscale(\"symlog\")\nax.set_ylabel(\"CAGE tpm\\n(ESCs)\")\nplt.legend(loc=2, bbox_to_anchor=(1.05, 1))\n\nys = [1, 2, 22]\nfor i, label in enumerate([\"eRNA\", \"lncRNA\", \"mRNA\"]):\n sub = tmp[tmp[\"minimal_biotype\"] == label]\n human = sub[sub[\"species\"] == \"human\"]\n mouse = sub[sub[\"species\"] == \"mouse\"]\n \n human_vals = np.asarray(human[\"stem_exp_fixed\"])\n mouse_vals = np.asarray(mouse[\"stem_exp_fixed\"])\n\n human_vals = human_vals[~np.isnan(human_vals)]\n mouse_vals = mouse_vals[~np.isnan(mouse_vals)]\n\n u, pval = stats.mannwhitneyu(human_vals, mouse_vals, alternative=\"two-sided\", use_continuity=False)\n print(pval)\n \n if pval >= 0.05:\n annotate_pval(ax, i-0.1, i+0.1, ys[i], 0, ys[i], pval, fontsize)\n else:\n annotate_pval(ax, i-0.1, i+0.1, ys[i], 0, ys[i], pval, fontsize)\n \n n_human = len(human)\n n_mouse = len(mouse)\n\n ax.annotate(str(n_human), xy=(i-0.25, -1), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=tmp_pal[\"human\"], size=fontsize)\n ax.annotate(str(n_mouse), xy=(i+0.25, -1), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=tmp_pal[\"mouse\"], size=fontsize)\n\nax.set_ylim((-1.25, 1500))\n#fig.savefig(\"human_v_mouse_cage.min.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\n\n\n# In[56]:\n\n\nfig = plt.figure(figsize=(2.5, 1.5))\n\nax = sns.boxplot(data=tmp, x=\"minimal_biotype\", y=\"max_cage\", hue=\"species\",\n flierprops = dict(marker='o', markersize=5),\n order=[\"eRNA\", \"lncRNA\", \"mRNA\"], palette=tmp_pal)\nmimic_r_boxplot(ax)\n\nax.set_xticklabels([\"eRNA\", \"lncRNA\", \"mRNA\"], rotation=50, ha='right', va='top')\nax.set_xlabel(\"\")\nax.set_yscale(\"symlog\")\nax.set_ylabel(\"max CAGE reads\")\nplt.legend(loc=2, bbox_to_anchor=(1.05, 1))\n\nys = [200, 5000, 50000]\nfor i, label in enumerate([\"eRNA\", \"lncRNA\", \"mRNA\"]):\n sub = tmp[tmp[\"minimal_biotype\"] == label]\n human = sub[sub[\"species\"] == \"human\"]\n mouse = sub[sub[\"species\"] == \"mouse\"]\n \n human_vals = np.asarray(human[\"max_cage\"])\n mouse_vals = np.asarray(mouse[\"max_cage\"])\n\n human_vals = human_vals[~np.isnan(human_vals)]\n mouse_vals = mouse_vals[~np.isnan(mouse_vals)]\n\n u, pval = stats.mannwhitneyu(human_vals, mouse_vals, alternative=\"two-sided\", use_continuity=False)\n print(pval)\n \n if pval >= 0.05:\n annotate_pval(ax, i-0.1, i+0.1, ys[i], 0, ys[i], pval, fontsize)\n else:\n annotate_pval(ax, i-0.1, i+0.1, ys[i], 0, ys[i], pval, fontsize)\n \n n_human = len(human)\n n_mouse = len(mouse)\n\n ax.annotate(str(n_human), xy=(i-0.25, -1), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=tmp_pal[\"human\"], size=fontsize)\n ax.annotate(str(n_mouse), xy=(i+0.25, -1), xycoords=\"data\", xytext=(0, 0), \n textcoords=\"offset pixels\", ha='center', va='bottom', \n color=tmp_pal[\"mouse\"], size=fontsize)\n\n#ax.set_ylim((-1.25, 1500))\n#fig.savefig(\"human_v_mouse_cage.min.pdf\", dpi=\"figure\", bbox_inches=\"tight\")\n\n\n# ## 7. write files\n\n# In[57]:\n\n\nhuman_df_filename = \"%s/human_TSS_vals.both_tiles.txt\" % data_dir\nmouse_df_filename = \"%s/mouse_TSS_vals.both_tiles.txt\" % data_dir\n\n\n# In[58]:\n\n\nhuman_df.to_csv(human_df_filename, sep=\"\\t\", index=False)\nmouse_df.to_csv(mouse_df_filename, sep=\"\\t\", index=False)\n\n\n# In[59]:\n\n\ntss_map_mrg.to_csv(\"../../../data/01__design/01__mpra_list/mpra_tss.with_ids.RECLASSIFIED_WITH_MAX.txt\", sep=\"\\t\", index=False)\n\n\n# In[ ]:\n\n\n\n\n"
]
| [
[
"pandas.isnull",
"pandas.read_table",
"numpy.isnan",
"numpy.asarray",
"numpy.random.seed",
"scipy.stats.spearmanr",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"numpy.log10"
]
]
|
gxdai/CarND-Semantic-Segmentation | [
"78240ad8cfe45b9e4a4336ee1ad923614ba1f17f"
]
| [
"main.py"
]
| [
"#!/usr/bin/env python3\nimport os.path\nimport tensorflow as tf\nimport helper\nimport warnings\nfrom distutils.version import LooseVersion\nimport project_tests as tests\n\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\ndef load_vgg(sess, vgg_path):\n \"\"\"\n Load Pretrained VGG Model into TensorFlow.\n :param sess: TensorFlow Session\n :param vgg_path: Path to vgg folder, containing \"variables/\" and \"saved_model.pb\"\n :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out)\n \"\"\"\n # TODO: Implement function\n # Use tf.saved_model.loader.load to load the model and weights\n vgg_tag = 'vgg16'\n vgg_input_tensor_name = 'image_input:0'\n vgg_keep_prob_tensor_name = 'keep_prob:0'\n vgg_layer3_out_tensor_name = 'layer3_out:0'\n vgg_layer4_out_tensor_name = 'layer4_out:0'\n vgg_layer7_out_tensor_name = 'layer7_out:0'\n \n return None, None, None, None, None\ntests.test_load_vgg(load_vgg, tf)\n\n\ndef layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):\n \"\"\"\n Create the layers for a fully convolutional network. Build skip-layers using the vgg layers.\n :param vgg_layer3_out: TF Tensor for VGG Layer 3 output\n :param vgg_layer4_out: TF Tensor for VGG Layer 4 output\n :param vgg_layer7_out: TF Tensor for VGG Layer 7 output\n :param num_classes: Number of classes to classify\n :return: The Tensor for the last layer of output\n \"\"\"\n # TODO: Implement function\n return None\ntests.test_layers(layers)\n\n\ndef optimize(nn_last_layer, correct_label, learning_rate, num_classes):\n \"\"\"\n Build the TensorFLow loss and optimizer operations.\n :param nn_last_layer: TF Tensor of the last layer in the neural network\n :param correct_label: TF Placeholder for the correct label image\n :param learning_rate: TF Placeholder for the learning rate\n :param num_classes: Number of classes to classify\n :return: Tuple of (logits, train_op, cross_entropy_loss)\n \"\"\"\n # TODO: Implement function\n return None, None, None\ntests.test_optimize(optimize)\n\n\ndef train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,\n correct_label, keep_prob, learning_rate):\n \"\"\"\n Train neural network and print out the loss during training.\n :param sess: TF Session\n :param epochs: Number of epochs\n :param batch_size: Batch size\n :param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size)\n :param train_op: TF Operation to train the neural network\n :param cross_entropy_loss: TF Tensor for the amount of loss\n :param input_image: TF Placeholder for input images\n :param correct_label: TF Placeholder for label images\n :param keep_prob: TF Placeholder for dropout keep probability\n :param learning_rate: TF Placeholder for learning rate\n \"\"\"\n # TODO: Implement function\n pass\ntests.test_train_nn(train_nn)\n\n\ndef run():\n num_classes = 2\n image_shape = (160, 576) # KITTI dataset uses 160x576 images\n data_dir = './data'\n runs_dir = './runs'\n tests.test_for_kitti_dataset(data_dir)\n\n # Download pretrained vgg model\n helper.maybe_download_pretrained_vgg(data_dir)\n\n # OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset.\n # You'll need a GPU with at least 10 teraFLOPS to train on.\n # https://www.cityscapes-dataset.com/\n\n with tf.Session() as sess:\n # Path to vgg model\n vgg_path = os.path.join(data_dir, 'vgg')\n # Create function to get batches\n get_batches_fn = helper.gen_batch_function(os.path.join(data_dir, 'data_road/training'), image_shape)\n\n # OPTIONAL: Augment Images for better results\n # https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network\n\n # TODO: Build NN using load_vgg, layers, and optimize function\n\n # TODO: Train NN using the train_nn function\n\n # TODO: Save inference data using helper.save_inference_samples\n # helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, input_image)\n\n # OPTIONAL: Apply the trained model to a video\n\n\nif __name__ == '__main__':\n run()\n"
]
| [
[
"tensorflow.Session",
"tensorflow.test.gpu_device_name"
]
]
|
ebrahimebrahim/easyreg | [
"f767e68af8c2f230f45ef8a5219db9d8ff2b17f0"
]
| [
"easyreg/test_expr.py"
]
| [
"from time import time\nfrom .net_utils import get_test_model\nimport os\nimport numpy as np\n\n\ndef test_model(opt,model, dataloaders):\n\n model_path = opt['tsk_set']['path']['model_load_path']\n if isinstance(model_path, list):\n for i, path in enumerate(model_path):\n __test_model(opt,model,dataloaders,path,str(i)+'_')\n else:\n __test_model(opt,model, dataloaders,model_path)\n\n\n\n\ndef __test_model(opt,model,dataloaders, model_path,task_name=''):\n since = time()\n record_path = opt['tsk_set']['path']['record_path']\n cur_gpu_id = opt['tsk_set'][('gpu_ids', -1,\"the gpu id\")]\n task_type = opt['dataset'][('task_type','reg',\"the task type, either 'reg' or 'seg'\")]\n running_range=[-1]#opt['tsk_set']['running_range'] # todo should be [-1]\n running_part_data = running_range[0]>=0\n if running_part_data:\n print(\"running part of the test data from range {}\".format(running_range))\n gpu_id = cur_gpu_id\n\n if model.network is not None and gpu_id>=0:\n model.network = model.network.cuda()\n save_fig_on = opt['tsk_set'][('save_fig_on', True, 'saving fig')]\n save_running_resolution_3d_img = opt['tsk_set'][('save_running_resolution_3d_img', True, 'saving fig')]\n output_taking_original_image_format = opt['tsk_set'][('output_taking_original_image_format', False, 'output follows the same sz and physical format of the original image (input by command line or txt)')]\n\n phases = ['test'] #['val','test'] ###################################3\n if len(model_path):\n get_test_model(model_path, model.network, model.optimizer) ##############TODO model.optimizer\n else:\n print(\"Warning, the model is not manual loaded, make sure your model itself has been inited\")\n\n model.set_cur_epoch(-1)\n for phase in phases:\n num_samples = len(dataloaders[phase])\n if running_part_data:\n num_samples = len(running_range)\n records_score_np = np.zeros(num_samples)\n records_time_np = np.zeros(num_samples)\n if task_type == 'reg':\n records_jacobi_val_np = np.zeros(num_samples)\n records_jacobi_num_np = np.zeros(num_samples)\n loss_detail_list = []\n jacobi_val_res = 0.\n jacobi_num_res = 0.\n running_test_score = 0\n time_total= 0\n for idx, data in enumerate(dataloaders[phase]):\n i= idx\n if running_part_data:\n if i not in running_range:\n continue\n i = i - running_range[0]\n\n batch_size = len(data[0]['image'])\n is_train = False\n if model.network is not None:\n model.network.train(False)\n model.set_val()\n model.set_input(data, is_train)\n ex_time = time()\n model.cal_test_errors()\n batch_time = time() - ex_time\n time_total += batch_time\n print(\"the batch sample registration takes {} to complete\".format(batch_time))\n records_time_np[i] = batch_time\n if save_fig_on:\n model.save_fig('debug_model_'+phase)\n if save_running_resolution_3d_img:\n model.save_fig_3D(phase='test')\n if task_type == 'reg':\n model.save_deformation()\n\n if output_taking_original_image_format:\n model.save_image_into_original_sz_with_given_reference()\n\n\n loss,loss_detail = model.get_test_res(detail=True)\n print(\"the loss_detailed is {}\".format(loss_detail))\n running_test_score += loss * batch_size\n records_score_np[i] = loss\n loss_detail_list += [loss_detail]\n print(\"id {} and current pair name is : {}\".format(i,data[1]))\n print('the current running_score:{}'.format(loss))\n print('the current average running_score:{}'.format(running_test_score/(i+1)/batch_size))\n if task_type == 'reg':\n jaocbi_res = model.get_jacobi_val()\n if jaocbi_res is not None:\n jacobi_val_res += jaocbi_res[0] * batch_size\n jacobi_num_res += jaocbi_res[1] * batch_size\n records_jacobi_val_np[i] = jaocbi_res[0]\n records_jacobi_num_np[i] = jaocbi_res[1]\n print('the current jacobi is {}'.format(jaocbi_res))\n print('the current averge jocobi val is {}'.format(jacobi_val_res/(i+1)/batch_size))\n print('the current averge jocobi num is {}'.format(jacobi_num_res/(i+1)/batch_size))\n test_score = running_test_score / len(dataloaders[phase].dataset)\n time_per_img = time_total / len((dataloaders[phase].dataset))\n print('the average {}_loss: {:.4f}'.format(phase, test_score))\n print(\"the average time for per image is {}\".format(time_per_img))\n time_elapsed = time() - since\n print('the size of {} is {}, evaluation complete in {:.0f}m {:.0f}s'.format(len(dataloaders[phase].dataset),phase,\n time_elapsed // 60,\n time_elapsed % 60))\n np.save(os.path.join(record_path,task_name+'records'),records_score_np)\n records_detail_np = extract_interest_loss(loss_detail_list,sample_num=len(dataloaders[phase].dataset))\n np.save(os.path.join(record_path,task_name+'records_detail'),records_detail_np)\n np.save(os.path.join(record_path,task_name+'records_time'),records_time_np)\n if task_type == 'reg':\n jacobi_val_res = jacobi_val_res / len(dataloaders[phase].dataset)\n jacobi_num_res = jacobi_num_res / len(dataloaders[phase].dataset)\n print(\"the average {}_ jacobi val: {} :\".format(phase, jacobi_val_res))\n print(\"the average {}_ jacobi num: {} :\".format(phase, jacobi_num_res))\n np.save(os.path.join(record_path, task_name + 'records_jacobi'), records_jacobi_val_np)\n np.save(os.path.join(record_path, task_name + 'records_jacobi_num'), records_jacobi_num_np)\n return model\n\n\ndef extract_interest_loss(loss_detail_list,sample_num):\n \"\"\"\" multi_metric_res:{iou: Bx #label , dice: Bx#label...} ,\"\"\"\n assert len(loss_detail_list)>0\n if isinstance(loss_detail_list[0],dict):\n label_num = loss_detail_list[0]['dice'].shape[1]\n records_detail_np = np.zeros([sample_num,label_num])\n sample_count = 0\n for multi_metric_res in loss_detail_list:\n batch_len = multi_metric_res['dice'].shape[0]\n records_detail_np[sample_count:sample_count+batch_len,:] = multi_metric_res['dice']\n sample_count += batch_len\n else:\n records_detail_np=np.array([-1])\n return records_detail_np\n\n\n"
]
| [
[
"numpy.array",
"numpy.zeros"
]
]
|
PatrikDurdevic/Deep-Learning | [
"a29e16df1361f045bb0aff6df16d3aa02b7d5877"
]
| [
"Tensorflow Basics/Dense_MNIST.py"
]
| [
"import tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n\ntrain_images = train_images / 255\ntest_images = test_images / 255\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(10)\n])\nmodel.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n\nhistory = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\nprint('\\nTest accuracy:', test_acc)\n\nplt.figure(figsize=[8,6])\nplt.plot(history.history['accuracy'],'r',linewidth=3.0)\nplt.plot(history.history['val_accuracy'],'b',linewidth=3.0)\nplt.legend(['Training Accuracy', 'Validation Accuracy'],fontsize=18)\nplt.xlabel('Epochs ',fontsize=16)\nplt.ylabel('Accuracy',fontsize=16)\nplt.title('Accuracy Curves',fontsize=16)\nplt.show()\n\n\ndef plot_image(i, predictions_array, true_label, img):\n\tpredictions_array, true_label, img = predictions_array, true_label[i], img[i]\n\tplt.grid(False)\n\tplt.xticks([])\n\tplt.yticks([])\n\n\tplt.imshow(img, cmap=plt.cm.binary)\n\n\tpredicted_label = np.argmax(predictions_array)\n\tif predicted_label == true_label:\n\t\tcolor = 'blue'\n\telse:\n\t\tcolor = 'red'\n\n\tplt.xlabel(\"{} {:2.0f}% ({})\".format(predicted_label, 100*np.max(predictions_array), true_label), color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n\tpredictions_array, true_label = predictions_array, true_label[i]\n\tplt.grid(False)\n\tplt.xticks(range(10))\n\tplt.yticks([])\n\tthisplot = plt.bar(range(10), predictions_array, color=\"#777777\")\n\tplt.ylim([0, 1])\n\tpredicted_label = np.argmax(predictions_array)\n\n\tthisplot[predicted_label].set_color('red')\n\tthisplot[true_label].set_color('blue')\n\n\n\nprobability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])\npredictions = probability_model.predict(test_images)\n\nnum_rows = 5\nnum_cols = 3\nnum_images = num_rows*num_cols\nplt.figure(figsize=(2*2*num_cols, 2*num_rows))\nfor i in range(num_images):\n\tplt.subplot(num_rows, 2*num_cols, 2*i+1)\n\tplot_image(i, predictions[i], test_labels, test_images)\n\tplt.subplot(num_rows, 2*num_cols, 2*i+2)\n\tplot_value_array(i, predictions[i], test_labels)\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
]
| [
[
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.xticks",
"numpy.max",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"numpy.argmax",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplot",
"tensorflow.keras.datasets.mnist.load_data",
"matplotlib.pyplot.title",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Flatten",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.layers.Softmax",
"matplotlib.pyplot.imshow"
]
]
|
YuTingLiu/EfficientDet-TOD | [
"598c2700d761180f19bb87ea807e32fbf16e74fa"
]
| [
"inference_quad.py"
]
| [
"from model import efficientdet\nimport cv2\nimport os\nimport numpy as np\nimport time\nfrom utils import preprocess_image\nfrom utils.anchors import anchors_for_shape, AnchorParameters\nimport os.path as osp\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\nphi = 1\nweighted_bifpn = False\nmodel_path = 'checkpoints/colab_efficientdet.h5'\nimage_sizes = (512, 640, 768, 896, 1024, 1280, 1408)\nimage_size = image_sizes[phi]\n# classes = [\n# 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',\n# 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor',\n# ]\nclasses = ['text']\nnum_classes = len(classes)\nanchor_parameters = AnchorParameters(\n ratios=(0.25, 0.5, 1., 2.),\n sizes=(16, 32, 64, 128, 256))\nscore_threshold = 0.4\ncolors = [np.random.randint(0, 256, 3).tolist() for i in range(num_classes)]\nmodel, prediction_model = efficientdet(phi=phi,\n weighted_bifpn=weighted_bifpn,\n num_classes=num_classes,\n num_anchors=anchor_parameters.num_anchors(),\n score_threshold=score_threshold,\n detect_quadrangle=True,\n anchor_parameters=anchor_parameters,\n )\nprediction_model.load_weights(model_path, by_name=True)\n\nimport glob\n\nfor image_path in glob.glob('datasets/*.png'):\n image = cv2.imread(image_path)\n src_image = image.copy()\n image = image[:, :, ::-1]\n h, w = image.shape[:2]\n\n image, scale, offset_h, offset_w = preprocess_image(image, image_size=image_size)\n inputs = np.expand_dims(image, axis=0)\n anchors = anchors_for_shape((image_size, image_size), anchor_params=anchor_parameters)\n # run network\n start = time.time()\n boxes, scores, alphas, ratios, labels = prediction_model.predict_on_batch([np.expand_dims(image, axis=0),\n np.expand_dims(anchors, axis=0)])\n # alphas = np.exp(alphas)\n alphas = 1 / (1 + np.exp(-alphas))\n ratios = 1 / (1 + np.exp(-ratios))\n quadrangles = np.zeros(boxes.shape[:2] + (8,))\n quadrangles[:, :, 0] = boxes[:, :, 0] + (boxes[:, :, 2] - boxes[:, :, 0]) * alphas[:, :, 0]\n quadrangles[:, :, 1] = boxes[:, :, 1]\n quadrangles[:, :, 2] = boxes[:, :, 2]\n quadrangles[:, :, 3] = boxes[:, :, 1] + (boxes[:, :, 3] - boxes[:, :, 1]) * alphas[:, :, 1]\n quadrangles[:, :, 4] = boxes[:, :, 2] - (boxes[:, :, 2] - boxes[:, :, 0]) * alphas[:, :, 2]\n quadrangles[:, :, 5] = boxes[:, :, 3]\n quadrangles[:, :, 6] = boxes[:, :, 0]\n quadrangles[:, :, 7] = boxes[:, :, 3] - (boxes[:, :, 3] - boxes[:, :, 1]) * alphas[:, :, 3]\n print(time.time() - start)\n\n boxes[0, :, [0, 2]] = boxes[0, :, [0, 2]] - offset_w\n boxes[0, :, [1, 3]] = boxes[0, :, [1, 3]] - offset_h\n boxes /= scale\n boxes[0, :, 0] = np.clip(boxes[0, :, 0], 0, w - 1)\n boxes[0, :, 1] = np.clip(boxes[0, :, 1], 0, h - 1)\n boxes[0, :, 2] = np.clip(boxes[0, :, 2], 0, w - 1)\n boxes[0, :, 3] = np.clip(boxes[0, :, 3], 0, h - 1)\n\n quadrangles[0, :, [0, 2, 4, 6]] = quadrangles[0, :, [0, 2, 4, 6]] - offset_w\n quadrangles[0, :, [1, 3, 5, 7]] = quadrangles[0, :, [1, 3, 5, 7]] - offset_h\n quadrangles /= scale\n quadrangles[0, :, [0, 2, 4, 6]] = np.clip(quadrangles[0, :, [0, 2, 4, 6]], 0, w - 1)\n quadrangles[0, :, [1, 3, 5, 7]] = np.clip(quadrangles[0, :, [1, 3, 5, 7]], 0, h - 1)\n\n # select indices which have a score above the threshold\n indices = np.where(scores[0, :] > score_threshold)[0]\n\n # select those detections\n boxes = boxes[0, indices]\n scores = scores[0, indices]\n labels = labels[0, indices]\n quadrangles = quadrangles[0, indices]\n ratios = ratios[0, indices]\n\n for bbox, score, label, quadrangle, ratio in zip(boxes, scores, labels, quadrangles, ratios):\n xmin = int(round(bbox[0]))\n ymin = int(round(bbox[1]))\n xmax = int(round(bbox[2]))\n ymax = int(round(bbox[3]))\n score = '{:.4f}'.format(score)\n class_id = int(label)\n color = colors[class_id]\n class_name = classes[class_id]\n label = '-'.join([class_name, score])\n ret, baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n cv2.rectangle(src_image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 1)\n # cv2.rectangle(src_image, (xmin, ymax - ret[1] - baseline), (xmin + ret[0], ymax), color, -1)\n # cv2.putText(src_image, label, (xmin, ymax - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)\n cv2.putText(src_image, f'{ratio:.2f}', (xmin + (xmax - xmin) // 3, (ymin + ymax) // 2),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)\n cv2.drawContours(src_image, [quadrangle.astype(np.int32).reshape((4, 2))], -1, (0, 0, 255), 1)\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n cv2.imshow('image', src_image)\n cv2.waitKey(0)\n"
]
| [
[
"numpy.zeros",
"numpy.exp",
"numpy.where",
"numpy.random.randint",
"numpy.clip",
"numpy.expand_dims"
]
]
|
bdforbes/pandas | [
"aefae55e1960a718561ae0369e83605e3038f292"
]
| [
"pandas/tests/scalar/test_nat.py"
]
| [
"from datetime import datetime, timedelta\nimport operator\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import iNaT\nimport pandas.compat as compat\n\nfrom pandas.core.dtypes.common import is_datetime64_any_dtype\n\nfrom pandas import (\n DatetimeIndex,\n Index,\n NaT,\n Period,\n Series,\n Timedelta,\n TimedeltaIndex,\n Timestamp,\n isna,\n offsets,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray\nfrom pandas.core.ops import roperator\n\n\[email protected](\n \"nat,idx\",\n [\n (Timestamp(\"NaT\"), DatetimeIndex),\n (Timedelta(\"NaT\"), TimedeltaIndex),\n (Period(\"NaT\", freq=\"M\"), PeriodArray),\n ],\n)\ndef test_nat_fields(nat, idx):\n\n for field in idx._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n\n result = getattr(NaT, field)\n assert np.isnan(result)\n\n result = getattr(nat, field)\n assert np.isnan(result)\n\n for field in idx._bool_ops:\n\n result = getattr(NaT, field)\n assert result is False\n\n result = getattr(nat, field)\n assert result is False\n\n\ndef test_nat_vector_field_access():\n idx = DatetimeIndex([\"1/1/2000\", None, None, \"1/4/2000\"])\n\n for field in DatetimeIndex._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n if field in [\"week\", \"weekofyear\"]:\n # GH#33595 Deprecate week and weekofyear\n continue\n\n result = getattr(idx, field)\n expected = Index([getattr(x, field) for x in idx])\n tm.assert_index_equal(result, expected)\n\n ser = Series(idx)\n\n for field in DatetimeIndex._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == \"weekday\":\n continue\n if field in [\"week\", \"weekofyear\"]:\n # GH#33595 Deprecate week and weekofyear\n continue\n\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n for field in DatetimeIndex._bool_ops:\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n\[email protected](\"klass\", [Timestamp, Timedelta, Period])\[email protected](\"value\", [None, np.nan, iNaT, float(\"nan\"), NaT, \"NaT\", \"nat\"])\ndef test_identity(klass, value):\n assert klass(value) is NaT\n\n\[email protected](\"klass\", [Timestamp, Timedelta, Period])\[email protected](\"value\", [\"\", \"nat\", \"NAT\", None, np.nan])\ndef test_equality(klass, value):\n if klass is Period and value == \"\":\n pytest.skip(\"Period cannot parse empty string\")\n\n assert klass(value).value == iNaT\n\n\[email protected](\"klass\", [Timestamp, Timedelta])\[email protected](\"method\", [\"round\", \"floor\", \"ceil\"])\[email protected](\"freq\", [\"s\", \"5s\", \"min\", \"5min\", \"h\", \"5h\"])\ndef test_round_nat(klass, method, freq):\n # see gh-14940\n ts = klass(\"nat\")\n\n round_method = getattr(ts, method)\n assert round_method(freq) is ts\n\n\[email protected](\n \"method\",\n [\n \"astimezone\",\n \"combine\",\n \"ctime\",\n \"dst\",\n \"fromordinal\",\n \"fromtimestamp\",\n pytest.param(\n \"fromisocalendar\",\n marks=pytest.mark.skipif(\n not compat.PY38,\n reason=\"'fromisocalendar' was added in stdlib datetime in python 3.8\",\n ),\n ),\n \"isocalendar\",\n \"strftime\",\n \"strptime\",\n \"time\",\n \"timestamp\",\n \"timetuple\",\n \"timetz\",\n \"toordinal\",\n \"tzname\",\n \"utcfromtimestamp\",\n \"utcnow\",\n \"utcoffset\",\n \"utctimetuple\",\n \"timestamp\",\n ],\n)\ndef test_nat_methods_raise(method):\n # see gh-9513, gh-17329\n msg = f\"NaTType does not support {method}\"\n\n with pytest.raises(ValueError, match=msg):\n getattr(NaT, method)()\n\n\[email protected](\"method\", [\"weekday\", \"isoweekday\"])\ndef test_nat_methods_nan(method):\n # see gh-9513, gh-17329\n assert np.isnan(getattr(NaT, method)())\n\n\[email protected](\n \"method\", [\"date\", \"now\", \"replace\", \"today\", \"tz_convert\", \"tz_localize\"]\n)\ndef test_nat_methods_nat(method):\n # see gh-8254, gh-9513, gh-17329\n assert getattr(NaT, method)() is NaT\n\n\[email protected](\n \"get_nat\", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)]\n)\ndef test_nat_iso_format(get_nat):\n # see gh-12300\n assert get_nat(\"NaT\").isoformat() == \"NaT\"\n\n\[email protected](\n \"klass,expected\",\n [\n (Timestamp, [\"freqstr\", \"normalize\", \"to_julian_date\", \"to_period\", \"tz\"]),\n (\n Timedelta,\n [\n \"components\",\n \"delta\",\n \"is_populated\",\n \"resolution_string\",\n \"to_pytimedelta\",\n \"to_timedelta64\",\n \"view\",\n ],\n ),\n ],\n)\ndef test_missing_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # Here, we check which public methods NaT does not have. We\n # ignore any missing private methods.\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n missing = [x for x in klass_names if x not in nat_names and not x.startswith(\"_\")]\n missing.sort()\n\n assert missing == expected\n\n\ndef _get_overlap_public_nat_methods(klass, as_tuple=False):\n \"\"\"\n Get overlapping public methods between NaT and another class.\n\n Parameters\n ----------\n klass : type\n The class to compare with NaT\n as_tuple : bool, default False\n Whether to return a list of tuples of the form (klass, method).\n\n Returns\n -------\n overlap : list\n \"\"\"\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n overlap = [\n x\n for x in nat_names\n if x in klass_names and not x.startswith(\"_\") and callable(getattr(klass, x))\n ]\n\n # Timestamp takes precedence over Timedelta in terms of overlap.\n if klass is Timedelta:\n ts_names = dir(Timestamp)\n overlap = [x for x in overlap if x not in ts_names]\n\n if as_tuple:\n overlap = [(klass, method) for method in overlap]\n\n overlap.sort()\n return overlap\n\n\[email protected](\n \"klass,expected\",\n [\n (\n Timestamp,\n [\n \"astimezone\",\n \"ceil\",\n \"combine\",\n \"ctime\",\n \"date\",\n \"day_name\",\n \"dst\",\n \"floor\",\n \"fromisocalendar\",\n \"fromisoformat\",\n \"fromordinal\",\n \"fromtimestamp\",\n \"isocalendar\",\n \"isoformat\",\n \"isoweekday\",\n \"month_name\",\n \"now\",\n \"replace\",\n \"round\",\n \"strftime\",\n \"strptime\",\n \"time\",\n \"timestamp\",\n \"timetuple\",\n \"timetz\",\n \"to_datetime64\",\n \"to_numpy\",\n \"to_pydatetime\",\n \"today\",\n \"toordinal\",\n \"tz_convert\",\n \"tz_localize\",\n \"tzname\",\n \"utcfromtimestamp\",\n \"utcnow\",\n \"utcoffset\",\n \"utctimetuple\",\n \"weekday\",\n ],\n ),\n (Timedelta, [\"total_seconds\"]),\n ],\n)\ndef test_overlap_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # In case when Timestamp, Timedelta, and NaT are overlap, the overlap\n # is considered to be with Timestamp and NaT, not Timedelta.\n\n # \"fromisoformat\" was introduced in 3.7\n if klass is Timestamp and not compat.PY37:\n expected.remove(\"fromisoformat\")\n\n # \"fromisocalendar\" was introduced in 3.8\n if klass is Timestamp and not compat.PY38:\n expected.remove(\"fromisocalendar\")\n\n assert _get_overlap_public_nat_methods(klass) == expected\n\n\[email protected](\n \"compare\",\n (\n _get_overlap_public_nat_methods(Timestamp, True)\n + _get_overlap_public_nat_methods(Timedelta, True)\n ),\n)\ndef test_nat_doc_strings(compare):\n # see gh-17327\n #\n # The docstrings for overlapping methods should match.\n klass, method = compare\n klass_doc = getattr(klass, method).__doc__\n\n nat_doc = getattr(NaT, method).__doc__\n assert klass_doc == nat_doc\n\n\n_ops = {\n \"left_plus_right\": lambda a, b: a + b,\n \"right_plus_left\": lambda a, b: b + a,\n \"left_minus_right\": lambda a, b: a - b,\n \"right_minus_left\": lambda a, b: b - a,\n \"left_times_right\": lambda a, b: a * b,\n \"right_times_left\": lambda a, b: b * a,\n \"left_div_right\": lambda a, b: a / b,\n \"right_div_left\": lambda a, b: b / a,\n}\n\n\[email protected](\"op_name\", list(_ops.keys()))\[email protected](\n \"value,val_type\",\n [\n (2, \"scalar\"),\n (1.5, \"floating\"),\n (np.nan, \"floating\"),\n (\"foo\", \"str\"),\n (timedelta(3600), \"timedelta\"),\n (Timedelta(\"5s\"), \"timedelta\"),\n (datetime(2014, 1, 1), \"timestamp\"),\n (Timestamp(\"2014-01-01\"), \"timestamp\"),\n (Timestamp(\"2014-01-01\", tz=\"UTC\"), \"timestamp\"),\n (Timestamp(\"2014-01-01\", tz=\"US/Eastern\"), \"timestamp\"),\n (pytz.timezone(\"Asia/Tokyo\").localize(datetime(2014, 1, 1)), \"timestamp\"),\n ],\n)\ndef test_nat_arithmetic_scalar(op_name, value, val_type):\n # see gh-6873\n invalid_ops = {\n \"scalar\": {\"right_div_left\"},\n \"floating\": {\n \"right_div_left\",\n \"left_minus_right\",\n \"right_minus_left\",\n \"left_plus_right\",\n \"right_plus_left\",\n },\n \"str\": set(_ops.keys()),\n \"timedelta\": {\"left_times_right\", \"right_times_left\"},\n \"timestamp\": {\n \"left_times_right\",\n \"right_times_left\",\n \"left_div_right\",\n \"right_div_left\",\n },\n }\n\n op = _ops[op_name]\n\n if op_name in invalid_ops.get(val_type, set()):\n if (\n val_type == \"timedelta\"\n and \"times\" in op_name\n and isinstance(value, Timedelta)\n ):\n typs = \"(Timedelta|NaTType)\"\n msg = rf\"unsupported operand type\\(s\\) for \\*: '{typs}' and '{typs}'\"\n elif val_type == \"str\":\n # un-specific check here because the message comes from str\n # and varies by method\n msg = \"|\".join(\n [\n \"can only concatenate str\",\n \"unsupported operand type\",\n \"can't multiply sequence\",\n \"Can't convert 'NaTType'\",\n \"must be str, not NaTType\",\n ]\n )\n else:\n msg = \"unsupported operand type\"\n\n with pytest.raises(TypeError, match=msg):\n op(NaT, value)\n else:\n if val_type == \"timedelta\" and \"div\" in op_name:\n expected = np.nan\n else:\n expected = NaT\n\n assert op(NaT, value) is expected\n\n\[email protected](\n \"val,expected\", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64(\"NaT\"), np.nan)]\n)\ndef test_nat_rfloordiv_timedelta(val, expected):\n # see gh-#18846\n #\n # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv\n td = Timedelta(hours=3, minutes=4)\n assert td // val is expected\n\n\[email protected](\n \"op_name\",\n [\"left_plus_right\", \"right_plus_left\", \"left_minus_right\", \"right_minus_left\"],\n)\[email protected](\n \"value\",\n [\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\"], name=\"x\"),\n DatetimeIndex([\"2011-01-01\", \"2011-01-02\"], tz=\"US/Eastern\", name=\"x\"),\n DatetimeArray._from_sequence([\"2011-01-01\", \"2011-01-02\"]),\n DatetimeArray._from_sequence([\"2011-01-01\", \"2011-01-02\"], tz=\"US/Pacific\"),\n TimedeltaIndex([\"1 day\", \"2 day\"], name=\"x\"),\n ],\n)\ndef test_nat_arithmetic_index(op_name, value):\n # see gh-11718\n exp_name = \"x\"\n exp_data = [NaT] * 2\n\n if is_datetime64_any_dtype(value.dtype) and \"plus\" in op_name:\n expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name)\n else:\n expected = TimedeltaIndex(exp_data, name=exp_name)\n\n if not isinstance(value, Index):\n expected = expected.array\n\n op = _ops[op_name]\n result = op(NaT, value)\n tm.assert_equal(result, expected)\n\n\[email protected](\n \"op_name\",\n [\"left_plus_right\", \"right_plus_left\", \"left_minus_right\", \"right_minus_left\"],\n)\[email protected](\"box\", [TimedeltaIndex, Series, TimedeltaArray._from_sequence])\ndef test_nat_arithmetic_td64_vector(op_name, box):\n # see gh-19124\n vec = box([\"1 day\", \"2 day\"], dtype=\"timedelta64[ns]\")\n box_nat = box([NaT, NaT], dtype=\"timedelta64[ns]\")\n tm.assert_equal(_ops[op_name](vec, NaT), box_nat)\n\n\[email protected](\n \"dtype,op,out_dtype\",\n [\n (\"datetime64[ns]\", operator.add, \"datetime64[ns]\"),\n (\"datetime64[ns]\", roperator.radd, \"datetime64[ns]\"),\n (\"datetime64[ns]\", operator.sub, \"timedelta64[ns]\"),\n (\"datetime64[ns]\", roperator.rsub, \"timedelta64[ns]\"),\n (\"timedelta64[ns]\", operator.add, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", roperator.radd, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", operator.sub, \"datetime64[ns]\"),\n (\"timedelta64[ns]\", roperator.rsub, \"timedelta64[ns]\"),\n ],\n)\ndef test_nat_arithmetic_ndarray(dtype, op, out_dtype):\n other = np.arange(10).astype(dtype)\n result = op(NaT, other)\n\n expected = np.empty(other.shape, dtype=out_dtype)\n expected.fill(\"NaT\")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_nat_pinned_docstrings():\n # see gh-17327\n assert NaT.ctime.__doc__ == datetime.ctime.__doc__\n\n\ndef test_to_numpy_alias():\n # GH 24653: alias .to_numpy() for scalars\n expected = NaT.to_datetime64()\n result = NaT.to_numpy()\n\n assert isna(expected) and isna(result)\n\n\[email protected](\n \"other\",\n [\n Timedelta(0),\n Timedelta(0).to_pytimedelta(),\n pytest.param(\n Timedelta(0).to_timedelta64(),\n marks=pytest.mark.xfail(\n reason=\"td64 doesnt return NotImplemented, see numpy#17017\"\n ),\n ),\n Timestamp(0),\n Timestamp(0).to_pydatetime(),\n pytest.param(\n Timestamp(0).to_datetime64(),\n marks=pytest.mark.xfail(\n reason=\"dt64 doesnt return NotImplemented, see numpy#17017\"\n ),\n ),\n Timestamp(0).tz_localize(\"UTC\"),\n NaT,\n ],\n)\ndef test_nat_comparisons(compare_operators_no_eq_ne, other):\n # GH 26039\n opname = compare_operators_no_eq_ne\n\n assert getattr(NaT, opname)(other) is False\n\n op = getattr(operator, opname.strip(\"_\"))\n assert op(NaT, other) is False\n assert op(other, NaT) is False\n\n\[email protected](\"other\", [np.timedelta64(0, \"ns\"), np.datetime64(\"now\", \"ns\")])\ndef test_nat_comparisons_numpy(other):\n # Once numpy#17017 is fixed and the xfailed cases in test_nat_comparisons\n # pass, this test can be removed\n assert not NaT == other\n assert NaT != other\n assert not NaT < other\n assert not NaT > other\n assert not NaT <= other\n assert not NaT >= other\n\n\[email protected](\"other\", [\"foo\", 2, 2.0])\[email protected](\"op\", [operator.le, operator.lt, operator.ge, operator.gt])\ndef test_nat_comparisons_invalid(other, op):\n # GH#35585\n assert not NaT == other\n assert not other == NaT\n\n assert NaT != other\n assert other != NaT\n\n with pytest.raises(TypeError):\n op(NaT, other)\n\n with pytest.raises(TypeError):\n op(other, NaT)\n\n\[email protected](\n \"obj\",\n [\n offsets.YearEnd(2),\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.MonthEnd(2),\n offsets.MonthEnd(12),\n offsets.Day(2),\n offsets.Day(5),\n offsets.Hour(24),\n offsets.Hour(3),\n offsets.Minute(),\n np.timedelta64(3, \"h\"),\n np.timedelta64(4, \"h\"),\n np.timedelta64(3200, \"s\"),\n np.timedelta64(3600, \"s\"),\n np.timedelta64(3600 * 24, \"s\"),\n np.timedelta64(2, \"D\"),\n np.timedelta64(365, \"D\"),\n timedelta(-2),\n timedelta(365),\n timedelta(minutes=120),\n timedelta(days=4, minutes=180),\n timedelta(hours=23),\n timedelta(hours=23, minutes=30),\n timedelta(hours=48),\n ],\n)\ndef test_nat_addsub_tdlike_scalar(obj):\n assert NaT + obj is NaT\n assert obj + NaT is NaT\n assert NaT - obj is NaT\n\n\ndef test_pickle():\n # GH#4606\n p = tm.round_trip_pickle(NaT)\n assert p is NaT\n"
]
| [
[
"pandas.offsets.YearEnd",
"pandas.DatetimeIndex",
"pandas.offsets.Day",
"pandas.offsets.Minute",
"pandas.core.dtypes.common.is_datetime64_any_dtype",
"pandas.NaT.to_datetime64",
"pandas.Timestamp",
"numpy.empty",
"pandas.Timedelta",
"pandas._testing.round_trip_pickle",
"numpy.arange",
"pandas.offsets.YearBegin",
"pandas.TimedeltaIndex",
"pandas.Period",
"numpy.timedelta64",
"pandas._testing.assert_equal",
"pandas._testing.assert_index_equal",
"numpy.datetime64",
"pandas.offsets.MonthEnd",
"pandas.NaT.to_numpy",
"numpy.isnan",
"pandas.isna",
"pandas.offsets.MonthBegin",
"pandas.offsets.Hour",
"pandas.core.arrays.DatetimeArray._from_sequence",
"pandas._testing.assert_numpy_array_equal",
"pandas.Series"
]
]
|
tobiasraabe/respy_for_ma | [
"405f40851b176705fe924220fba606263d47f3d6"
]
| [
"development/modules/auxiliary_shared.py"
]
| [
"import argparse\nimport os\nimport random\nimport socket\nimport string\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom string import Formatter\n\nimport numpy as np\n\nfrom development.modules.clsMail import MailCls\nfrom development.modules.config import PACKAGE_DIR\n\n\ndef update_class_instance(respy_obj, spec_dict):\n \"\"\" Update model specification from the baseline initialization file.\n \"\"\"\n\n respy_obj.unlock()\n\n # Varying the baseline level of ambiguity requires special case. The same is true\n # for the discount rate.\n if \"level\" in spec_dict[\"update\"].keys():\n respy_obj.attr[\"optim_paras\"][\"level\"] = np.array(\n [spec_dict[\"update\"][\"level\"]]\n )\n if \"delta\" in spec_dict[\"update\"].keys():\n respy_obj.attr[\"optim_paras\"][\"delta\"] = np.array(\n [spec_dict[\"update\"][\"delta\"]]\n )\n\n for key_ in spec_dict[\"update\"].keys():\n if key_ in [\"level\", \"delta\"]:\n continue\n respy_obj.set_attr(key_, spec_dict[\"update\"][key_])\n\n respy_obj.lock()\n\n return respy_obj\n\n\ndef strfdelta(tdelta, fmt):\n \"\"\" Get a string from a timedelta.\n \"\"\"\n f, d = Formatter(), {}\n l = {\"D\": 86400, \"H\": 3600, \"M\": 60, \"S\": 1}\n k = list(map(lambda x: x[1], list(f.parse(fmt))))\n rem = int(tdelta.total_seconds())\n for i in (\"D\", \"H\", \"M\", \"S\"):\n if i in k and i in l.keys():\n d[i], rem = divmod(rem, l[i])\n return f.format(fmt, **d)\n\n\ndef cleanup():\n os.system(\"git clean -d -f\")\n\n\ndef compile_package(is_debug=False):\n \"\"\" Compile the package for use.\n \"\"\"\n python_exec = sys.executable\n cwd = os.getcwd()\n os.chdir(PACKAGE_DIR + \"/respy\")\n subprocess.check_call(python_exec + \" waf distclean\", shell=True)\n if not is_debug:\n subprocess.check_call(python_exec + \" waf configure build\", shell=True)\n else:\n subprocess.check_call(python_exec + \" waf configure build --debug \", shell=True)\n\n os.chdir(cwd)\n\n\ndef send_notification(which, **kwargs):\n \"\"\" Finishing up a run of the testing battery.\n \"\"\"\n # This allows to run the scripts even when no notification can be send.\n home = Path(os.environ.get(\"HOME\") or os.environ.get(\"HOMEPATH\"))\n if not os.path.exists(str(home / \".credentials\")):\n return\n\n hours, is_failed, num_tests, seed = None, None, None, None\n\n # Distribute keyword arguments\n if \"is_failed\" in kwargs.keys():\n is_failed = kwargs[\"is_failed\"]\n\n if \"hours\" in kwargs.keys():\n hours = \"{}\".format(kwargs[\"hours\"])\n\n if \"procs\" in kwargs.keys():\n procs = str(kwargs[\"procs\"])\n\n if \"num_tests\" in kwargs.keys():\n num_tests = \"{}\".format(kwargs[\"num_tests\"])\n\n if \"seed\" in kwargs.keys():\n seed = \"{}\".format(kwargs[\"seed\"])\n\n if \"idx_failures\" in kwargs.keys():\n idx_failures = \", \".join(str(e) for e in kwargs[\"idx_failures\"])\n\n if \"old_release\" in kwargs.keys():\n old_release = kwargs[\"old_release\"]\n\n if \"new_release\" in kwargs.keys():\n new_release = kwargs[\"new_release\"]\n\n if \"failed_seeds\" in kwargs.keys():\n failed_seeds = kwargs[\"failed_seeds\"]\n\n hostname = socket.gethostname()\n\n if which == \"scalability\":\n subject = \" RESPY: Scalability Testing\"\n message = \" Scalability testing is completed on @\" + hostname + \".\"\n elif which == \"reliability\":\n subject = \" RESPY: Reliability Testing\"\n message = \" Reliability testing is completed on @\" + hostname + \".\"\n elif which == \"property\":\n subject = \" RESPY: Property Testing\"\n message = (\n \" A \"\n + hours\n + \" hour run of the testing battery on @\"\n + hostname\n + \" is completed.\"\n )\n\n elif which == \"regression\":\n subject = \" RESPY: Regression Testing\"\n if is_failed:\n message = (\n \"Failure during regression testing @\"\n + hostname\n + \" for test(s): \"\n + idx_failures\n + \".\"\n )\n else:\n message = \" Regression testing is completed on @\" + hostname + \".\"\n\n elif which == \"release\":\n subject = \" RESPY: Release Testing\"\n if is_failed:\n message = (\n \" Failure during release testing with seed \"\n + seed\n + \" on @\"\n + hostname\n + \".\"\n )\n else:\n message = (\n \" Release testing completed successfully after \"\n + hours\n + \" hours on @\"\n + hostname\n + \". We compared release \"\n + old_release\n + \" against \"\n + new_release\n + \" for a total of \"\n + num_tests\n + \" tests.\"\n )\n elif which == \"robustness\":\n subject = \" RESPY: Robustness Testing\"\n if is_failed is True:\n failed_pct = len(failed_seeds) / float(num_tests) * 100\n failed_pct = \"({} %)\".format(failed_pct)\n message = (\n \" Failure during robustness testing on @{}. In total {} \"\n + \"tests were run in {} hours on {} cores. {} tests failed \"\n + \"{}. The failed tests have the following seeds: {}.\"\n )\n message = message.format(\n hostname,\n num_tests,\n hours,\n procs,\n len(failed_seeds),\n failed_pct,\n str(failed_seeds),\n )\n else:\n message = (\n \" Robustness testing completed successfully after \"\n + hours\n + \" hours, running on \"\n + procs\n + \" cores on @\"\n + hostname\n + \". In total \"\n + num_tests\n + \" were run.\"\n )\n else:\n raise AssertionError\n\n mail_obj = MailCls()\n mail_obj.set_attr(\"subject\", subject)\n mail_obj.set_attr(\"message\", message)\n\n if which == \"property\":\n mail_obj.set_attr(\"attachment\", \"property.respy.info\")\n elif which == \"scalability\":\n mail_obj.set_attr(\"attachment\", \"scalability.respy.info\")\n elif which == \"reliability\":\n mail_obj.set_attr(\"attachment\", \"reliability.respy.info\")\n elif which == \"robustness\":\n mail_obj.set_attr(\"attachment\", \"robustness.respy.info\")\n\n mail_obj.lock()\n\n mail_obj.send()\n\n\ndef aggregate_information(which, fnames):\n \"\"\" This function simply aggregates the information from the different specifications.\n \"\"\"\n if which == \"scalability\":\n fname_info = \"scalability.respy.info\"\n elif which == \"reliability\":\n fname_info = \"reliability.respy.info\"\n else:\n raise AssertionError\n\n dirnames = []\n for fname in fnames:\n dirnames += [fname.replace(\".ini\", \"\")]\n\n with open(fname_info, \"w\") as outfile:\n outfile.write(\"\\n\")\n for dirname in dirnames:\n\n if not os.path.exists(dirname):\n continue\n\n outfile.write(\" \" + dirname + \"\\n\")\n os.chdir(dirname)\n with open(fname_info, \"r\") as infile:\n outfile.write(infile.read())\n os.chdir(\"../\")\n outfile.write(\"\\n\\n\")\n\n\ndef process_command_line_arguments(description):\n \"\"\" Process command line arguments for the request.\n \"\"\"\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n dest=\"is_debug\",\n default=False,\n help=\"use debugging specification\",\n )\n\n args = parser.parse_args()\n is_debug = args.is_debug\n\n return is_debug\n\n\ndef get_random_dirname(length):\n \"\"\" This function creates a random directory name.\n\n The random name is used for a temporary testing directory. It starts with two\n underscores so that it does not clutter the root directory.\n\n TODO: Sensible length default.\n\n \"\"\"\n return \"__\" + \"\".join(random.choice(string.ascii_lowercase) for _ in range(length))\n"
]
| [
[
"numpy.array"
]
]
|
LSSTDESC/qp | [
"00ce24c749ca1ae1adfa124c31642ba5f6c36a12"
]
| [
"tests/test_utils.py"
]
| [
"\"\"\"\nUnit tests for PDF class\n\"\"\"\nimport numpy as np\nimport unittest\nimport qp\n\nfrom qp import test_data\n\nclass UtilsTestCase(unittest.TestCase):\n \"\"\" Test the utility functions \"\"\"\n\n def setUp(self):\n \"\"\"\n Make any objects that are used in multiple tests.\n \"\"\"\n\n def tearDown(self):\n \"\"\" Clean up any mock data files created by the tests. \"\"\"\n\n @staticmethod\n def test_profile():\n \"\"\" Test the utils.profile function \"\"\"\n npdf = 100\n x_bins = test_data.XBINS\n x_cents = qp.utils.edge_to_center(x_bins)\n nbin = x_cents.size\n x_data = (np.ones((npdf, 1))*x_cents).T\n c_vals = np.linspace(0.5, 2.5, nbin)\n y_data = np.expand_dims(c_vals, -1)*(0.95 + 0.1*np.random.uniform(size=(nbin, npdf)))\n pf_1 = qp.utils.profile(x_data.flatten(), y_data.flatten(), x_bins, std=False)\n pf_2 = qp.utils.profile(x_data.flatten(), y_data.flatten(), x_bins, std=True)\n qp.test_funcs.assert_all_close(pf_1[0], c_vals, atol=0.02, test_name=\"profile_mean\")\n qp.test_funcs.assert_all_close(pf_1[0], pf_2[0], test_name=\"profile_check\")\n qp.test_funcs.assert_all_close(pf_1[1], c_vals/npdf*np.sqrt(12), atol=0.2, test_name=\"profile_std\")\n qp.test_funcs.assert_all_close(pf_1[1], 0.1*pf_2[1], test_name=\"profile_err\")\n\n def test_sparse(self):\n \"\"\" Test the sparse representation \"\"\"\n\n xvals = np.linspace(0,1,101)\n #assert basic construction\n A = qp.sparse_rep.create_voigt_basis(xvals, (0, 1), 11, (0.01, 0.5), 10, 10)\n self.assertEqual(A.shape, (101, 1100))\n #check consistency of a constrained case od voigt basis\n pdf0 = np.exp(-((xvals - 0.5) ** 2) / (2.* 0.01)) / (np.sqrt(2*np.pi)*0.1)\n pdf2 = qp.sparse_rep.shapes2pdf([1,], [0.5,], [0.1,], [0,], dict(xvals=xvals), cut=1.e-7)\n self.assertTrue(np.allclose(pdf2, pdf0))\n A = qp.sparse_rep.create_voigt_basis(xvals, (0.5,0.5), 1, (0.1,0.1), 1, 1)\n pdf1 = np.squeeze(A) * np.sqrt((pdf0**2).sum())\n self.assertTrue(np.allclose(pdf1,pdf0))\n #NSparse set to 2 so that unit testing goes through more code in sparse_basis\n ALL, bigD, _ = qp.sparse_rep.build_sparse_representation(xvals, [pdf0], (0.5,0.5), 1, (0.1,0.1), 1, 1, 2)\n va, ma, sa, ga = qp.sparse_rep.indices2shapes(ALL, bigD)\n self.assertEqual(va[:, 1], 0.)\n self.assertEqual([va[:, 0], ma[:, 0], sa[:, 0], ga[:, 0]], [1., 0.5, 0.1, 0.])\n #check default values\n ALL, bigD, A = qp.sparse_rep.build_sparse_representation(xvals, [pdf0])\n self.assertEqual(bigD['mu'], [min(xvals), max(xvals)])\n self.assertEqual(bigD['dims'][0], len(xvals))\n pdf_rec = qp.sparse_rep.pdf_from_sparse(ALL, A, xvals)\n self.assertTrue(np.allclose(pdf_rec[:, 0], pdf0, atol=1.5e-2))\n\n\nif __name__ == '__main__':\n unittest.main()\n"
]
| [
[
"numpy.ones",
"numpy.exp",
"numpy.allclose",
"numpy.random.uniform",
"numpy.sqrt",
"numpy.linspace",
"numpy.squeeze",
"numpy.expand_dims"
]
]
|
naigamshah/NBEATS | [
"7a85b36256f46ac39ba252c70b4ed2783531d75c"
]
| [
"examples/trainer_pytorch.py"
]
| [
"import os\nfrom argparse import ArgumentParser\n\nimport matplotlib.pyplot as plt\nimport torch\nfrom data import get_m4_data, dummy_data_generator\nfrom torch import optim\nfrom torch.nn import functional as F\n\nfrom nbeats_pytorch.model import NBeatsNet\n\nCHECKPOINT_NAME = 'nbeats-training-checkpoint.th'\n\n\ndef get_script_arguments():\n parser = ArgumentParser(description='N-Beats')\n parser.add_argument('--disable-cuda', action='store_true', help='Disable CUDA')\n parser.add_argument('--disable-plot', action='store_true', help='Disable interactive plots')\n parser.add_argument('--task', choices=['m4', 'dummy'], required=True)\n parser.add_argument('--test', action='store_true')\n return parser.parse_args()\n\n\ndef split(arr, size):\n arrays = []\n while len(arr) > size:\n slice_ = arr[:size]\n arrays.append(slice_)\n arr = arr[size:]\n arrays.append(arr)\n return arrays\n\n\ndef batcher(dataset, batch_size, infinite=False):\n while True:\n x, y = dataset\n for x_, y_ in zip(split(x, batch_size), split(y, batch_size)):\n yield x_, y_\n if not infinite:\n break\n\n\ndef main():\n args = get_script_arguments()\n device = torch.device('cuda') if not args.disable_cuda and torch.cuda.is_available() else torch.device('cpu')\n forecast_length = 10\n backcast_length = 5 * forecast_length\n batch_size = 4 # greater than 4 for viz\n\n if args.task == 'm4':\n data_gen = batcher(get_m4_data(backcast_length, forecast_length), batch_size=batch_size, infinite=True)\n elif args.task == 'dummy':\n data_gen = dummy_data_generator(backcast_length, forecast_length,\n signal_type='seasonality', random=True,\n batch_size=batch_size)\n else:\n raise Exception('Unknown task.')\n\n print('--- Model ---')\n net = NBeatsNet(device=device,\n stack_types=[NBeatsNet.TREND_BLOCK, NBeatsNet.SEASONALITY_BLOCK],\n forecast_length=forecast_length,\n thetas_dims=[2, 8],\n nb_blocks_per_stack=3,\n backcast_length=backcast_length,\n hidden_layer_units=1024,\n share_weights_in_stack=False,\n nb_harmonics=None)\n\n # net = NBeatsNet(device=device,\n # stack_types=[NBeatsNet.GENERIC_BLOCK, NBeatsNet.GENERIC_BLOCK],\n # forecast_length=forecast_length,\n # thetas_dims=[7, 8],\n # nb_blocks_per_stack=3,\n # backcast_length=backcast_length,\n # hidden_layer_units=128,\n # share_weights_in_stack=False\n # )\n\n optimiser = optim.Adam(net.parameters())\n\n def plot_model(x, target, grad_step):\n if not args.disable_plot:\n print('plot()')\n plot(net, x, target, backcast_length, forecast_length, grad_step)\n\n max_grad_steps = 10000\n if args.test:\n max_grad_steps = 5\n\n simple_fit(net, optimiser, data_gen, plot_model, device, max_grad_steps)\n\n\ndef simple_fit(net, optimiser, data_generator, on_save_callback, device, max_grad_steps=10000):\n print('--- Training ---')\n initial_grad_step = load(net, optimiser)\n for grad_step, (x, target) in enumerate(data_generator):\n grad_step += initial_grad_step\n optimiser.zero_grad()\n net.train()\n backcast, forecast = net(torch.tensor(x, dtype=torch.float).to(device))\n loss = F.mse_loss(forecast, torch.tensor(target, dtype=torch.float).to(device))\n loss.backward()\n optimiser.step()\n print(f'grad_step = {str(grad_step).zfill(6)}, loss = {loss.item():.6f}')\n if grad_step % 1000 == 0 or (grad_step < 1000 and grad_step % 100 == 0):\n with torch.no_grad():\n save(net, optimiser, grad_step)\n if on_save_callback is not None:\n on_save_callback(x, target, grad_step)\n if grad_step > max_grad_steps:\n print('Finished.')\n break\n\n\ndef save(model, optimiser, grad_step):\n torch.save({\n 'grad_step': grad_step,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimiser.state_dict(),\n }, CHECKPOINT_NAME)\n\n\ndef load(model, optimiser):\n if os.path.exists(CHECKPOINT_NAME):\n checkpoint = torch.load(CHECKPOINT_NAME)\n model.load_state_dict(checkpoint['model_state_dict'])\n optimiser.load_state_dict(checkpoint['optimizer_state_dict'])\n grad_step = checkpoint['grad_step']\n print(f'Restored checkpoint from {CHECKPOINT_NAME}.')\n return grad_step\n return 0\n\n\ndef plot(net, x, target, backcast_length, forecast_length, grad_step):\n net.eval()\n _, f = net(torch.tensor(x, dtype=torch.float))\n subplots = [221, 222, 223, 224]\n\n plt.figure(1)\n plt.subplots_adjust(top=0.88)\n for i in range(4):\n ff, xx, yy = f.cpu().numpy()[i], x[i], target[i]\n plt.subplot(subplots[i])\n plt.plot(range(0, backcast_length), xx, color='b')\n plt.plot(range(backcast_length, backcast_length + forecast_length), yy, color='g')\n plt.plot(range(backcast_length, backcast_length + forecast_length), ff, color='r')\n # plt.title(f'step #{grad_step} ({i})')\n\n output = 'n_beats_{}.png'.format(grad_step)\n plt.savefig(output)\n plt.clf()\n print('Saved image to {}.'.format(output))\n\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"torch.device",
"matplotlib.pyplot.savefig",
"torch.no_grad",
"matplotlib.pyplot.figure",
"torch.cuda.is_available",
"torch.tensor",
"torch.load",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.subplot"
]
]
|
LSDOlab/csdl | [
"04c2c5764f6ca9b865ec87ecfeaf6f22ecacc5a3"
]
| [
"csdl/examples/valid/ex_bracketed_search_bracketed_array_define_model_inline.py"
]
| [
"def example(Simulator):\n from csdl import Model, ScipyKrylov, NewtonSolver, NonlinearBlockGS\n import numpy as np\n from csdl.examples.models.quadratic_function import QuadraticFunction\n from csdl.examples.models.quadratic_function import QuadraticFunction\n from csdl.examples.models.quadratic_wih_extra_term import QuadraticWithExtraTerm\n from csdl.examples.models.simple_add import SimpleAdd\n from csdl.examples.models.fixed_point import FixedPoint2\n from csdl.examples.models.quadratic_wih_extra_term import QuadraticWithExtraTerm\n from csdl.examples.models.simple_add import SimpleAdd\n from csdl.examples.models.fixed_point import FixedPoint2\n \n \n class ExampleBracketedArrayDefineModelInline(Model):\n def define(self):\n model = Model()\n a = model.declare_variable('a', shape=(2, ))\n b = model.declare_variable('b', shape=(2, ))\n c = model.declare_variable('c', shape=(2, ))\n x = model.declare_variable('x', shape=(2, ))\n y = a * x**2 + b * x + c\n model.register_output('y', y)\n \n solve_quadratic = self.create_implicit_operation(model)\n solve_quadratic.declare_state('x',\n residual='y',\n bracket=(\n np.array([0, 2.]),\n np.array([2, np.pi], ),\n ))\n \n a = self.declare_variable('a', val=[1, -1])\n b = self.declare_variable('b', val=[-4, 4])\n c = self.declare_variable('c', val=[3, -3])\n x = solve_quadratic(a, b, c)\n \n \n sim = Simulator(ExampleBracketedArrayDefineModelInline())\n sim.run()\n \n print('x', sim['x'].shape)\n print(sim['x'])\n \n return sim"
]
| [
[
"numpy.array"
]
]
|
zejiangp/EBERT | [
"07489e5e95d0a7bbd05314333b6b368697df71cd"
]
| [
"custom_utils/cutils.py"
]
| [
"import torch\nimport numpy as np\n\ndef single_head_flops(length, config, ratio):\n L = length\n d = config.hidden_size\n # q, k, v: (L x d) (d x 64) -> (L x 64)\n flops_qkv = (L * 64 * d * 2) * 3\n # attn: (L x 64) (64 x L) -> (L x L)\n flops_attn = L * L * 64 * 2\n # attn * v: (L x L) (L x 64) -> (L x 64)\n flops_attn_v = L * 64 * L * 2\n # self_output: (L x 64) (64 x d) -> ( L x d)\n flops_self = L * d * 64 * 2\n return ratio * (flops_qkv + flops_attn + flops_attn_v + flops_self)\n\ndef ffn_flops(length, config, ratio):\n L = length\n d = config.hidden_size\n inter = config.intermediate_size * ratio # using ratio to get average number of intermediate nodes\n # ffn0: (L x d) (d x inter) -> (L x inter)\n flops_fc0 = L * inter * d * 2\n # ffn1: (L x inter) (inter x d) -> (L x d)\n flops_fc1 = L * d * inter * 2\n return flops_fc0 + flops_fc1\n\ndef head_mask_generator_flops(config):\n d = config.hidden_size\n # (1 x d) (d x 64) -> (1 x 64)\n flops_fc0 = 1 * 64 * d * 2\n # (1 x 64) (64 x 12) -> (1 x 12)\n flops_fc1 = 1 * 12 * 64 * 2\n return flops_fc0 + flops_fc1\n\ndef ffn_mask_generator_flops(config):\n d = config.hidden_size\n inter = config.intermediate_size\n # (1x d) (d x 64) -> (1 x 64)\n flops_fc0 = 1 * 64 * d * 2\n # (1 x 64) (64 x 4d) -> (1 x 3072)\n flops_fc1 = 1 * inter * 64 * 2\n return flops_fc0 + flops_fc1\n\ndef compute_model_flops(length, config, model=None, num_samples=1, is_sparsity=False):\n total_flops = 0.0\n\n if not is_sparsity:\n total_flops = single_head_flops(length, config, 1.0) * config.num_attention_heads\n total_flops += ffn_flops(length, config, 1.0) \n total_flops *= config.num_hidden_layers\n elif model is not None:\n for key, value in model.named_buffers():\n if 'head_nopruned_times' in key:\n value = value.detach().cpu().numpy() / float(num_samples)\n for h in value:\n total_flops += single_head_flops(length, config, h)\n total_flops += head_mask_generator_flops(config)\n\n if 'ffn_nopruned_times' in key:\n value = np.mean(value.detach().cpu().numpy() / float(num_samples))\n\n total_flops += ffn_flops(length, config, value)\n total_flops += ffn_mask_generator_flops(config)\n\n return total_flops\n\ndef get_mean_times(model=None, num_samples=1):\n for key, value in model.named_buffers():\n if 'head_nopruned_times' in key:\n value = value.detach().cpu().numpy() / float(num_samples)\n print(np.sum(value))\n\n if 'ffn_nopruned_times' in key:\n value = value.detach().cpu().numpy() / float(num_samples)\n print(np.sum(value))\n\ndef compute_model_sparsity(length, num_samples, model, logger, writer, log):\n\n logger.info(\"***** sparsity and flops *****\")\n config = model.config\n total_flops = compute_model_flops(length, config)\n total_compressed_flops = compute_model_flops(length, config, model, num_samples, True)\n\n original_flops = total_flops / (1024 ** 3)\n dynamic_flops = total_compressed_flops / (1024 ** 3)\n compress_ratio = total_compressed_flops / total_flops\n \n if log is not None:\n log({'compress_ratio': compress_ratio})\n\n logger.info(\"Original model flops = {:.3f} GFLOPs\".format(original_flops))\n logger.info(\"Dynamic model average flops = {:.3f} GFLOPs\".format(dynamic_flops))\n logger.info(\"Compressed ratio = {:.3f}\".format(compress_ratio))\n\n if writer is not None:\n writer.write(\"Original model flops = {:.3f} GFLOPs\\n\".format(original_flops))\n writer.write(\"Dynamic model average flops = {:.3f} GFLOPs\\n\".format(dynamic_flops))\n writer.write(\"Compressed ratio = {:.3f}\".format(compress_ratio))\n return compress_ratio\n\nclass Binarize_STE(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, t):\n return (input > t).float()\n @staticmethod\n def backward(ctx, grad_output):\n return grad_output, None"
]
| [
[
"numpy.sum"
]
]
|
constantinpape/ome-ngff-implementations | [
"67b4e0f3cc7cc0f0c62aa8f9fbba1072d0f54b37"
]
| [
"single_image/package_example_data.py"
]
| [
"import json\nimport os\n\nimport imageio\nimport h5py\nimport numpy as np\nimport zarr\n\n\n# collect the example data from the kreshuk lab and convert it to tifs\n# to collect all example data in the same format and prepare for packaging it\ndef package_examples():\n os.makedirs(\"./example_data\", exist_ok=True)\n metadata = {}\n\n def to_h5(data, name):\n out_path = f\"./example_data/{name}\"\n with h5py.File(out_path, mode=\"w\") as f:\n f.create_dataset(\"data\", data=data, compression=\"gzip\")\n\n # example data for cyx, yx\n path = os.path.join(\"/g/kreshuk/data/covid/covid-data-vibor/20200405_test_images\",\n \"WellC01_PointC01_0000_ChannelDAPI,WF_GFP,TRITC,WF_Cy5_Seq0216.tiff\")\n data = imageio.volread(path)\n to_h5(data, \"image_with_channels.h5\")\n metadata[\"image_with_channels\"] = {\"voxel_size\": None, \"unit\": None}\n\n # example data for zyx\n path = os.path.join(\"/g/kreshuk/pape/Work/mobie/covid-em-datasets/data\",\n \"Covid19-S4-Area2/images/local/sbem-6dpf-1-whole-raw.n5\")\n key = \"setup0/timepoint0/s3\"\n with zarr.open(path, mode=\"r\") as f:\n data = f[key][:]\n to_h5(data, \"volume.h5\")\n # original voxel size is 8 nm (isotropic) and we use scale 3 (downsampled by 2^3 = 8)\n # -> voxel size is 64 nm\n metadata[\"volume\"] = {\"voxel_size\": {\"z\": 64.0, \"y\": 64.0, \"x\": 64.0}, \"unit\": \"nanometer\"}\n\n # example data for tyx, tcyx, tczyx\n path1 = \"/g/kreshuk/pape/Work/mobie/arabidopsis-root-lm-datasets/data/arabidopsis-root/images/local/lm-membranes.n5\"\n path2 = \"/g/kreshuk/pape/Work/mobie/arabidopsis-root-lm-datasets/data/arabidopsis-root/images/local/lm-nuclei.n5\"\n timepoints = [32, 33, 34]\n data = []\n for tp in timepoints:\n key = f\"setup0/timepoint{tp}/s2\"\n with zarr.open(path1, mode=\"r\") as f:\n d1 = f[key][:]\n with zarr.open(path2, mode=\"r\") as f:\n d2 = f[key][:]\n data.append(np.concatenate([d1[None], d2[None]], axis=0)[None])\n data = np.concatenate(data, axis=0)\n to_h5(data, \"timeseries_with_channels.h5\")\n # original voxel size is 0.25 x 0.1625 x 0.1625 micrometer and we use cale 2 (downsampled by 2^2=4)\n metadata[\"timeseries_with_channels\"] = {\"voxel_size\": {\"z\": 1.0, \"y\": 0.65, \"x\": 0.65}, \"unit\": \"micrometer\"}\n\n with open(\"./example_data/voxel_sizes.json\", \"w\") as f:\n json.dump(metadata, f)\n\n\nif __name__ == \"__main__\":\n package_examples()\n"
]
| [
[
"numpy.concatenate"
]
]
|
microopus/cvat | [
"77264252c0f37c681dbbddc1a6877961f8f99930"
]
| [
"cvat/apps/engine/media_extractors.py"
]
| [
"# Copyright (C) 2019-2020 Intel Corporation\n#\n# SPDX-License-Identifier: MIT\n\nimport os\nimport tempfile\nimport shutil\nimport zipfile\nimport io\nimport itertools\nimport struct\nimport re\nfrom abc import ABC, abstractmethod\n\nimport av\nimport numpy as np\nfrom pyunpack import Archive\nfrom PIL import Image, ImageFile\nimport open3d as o3d\nfrom cvat.apps.engine.utils import rotate_image\nfrom cvat.apps.engine.models import DimensionType\n\n# fixes: \"OSError:broken data stream\" when executing line 72 while loading images downloaded from the web\n# see: https://stackoverflow.com/questions/42462431/oserror-broken-data-stream-when-reading-image-file\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nfrom cvat.apps.engine.mime_types import mimetypes\n\ndef get_mime(name):\n for type_name, type_def in MEDIA_TYPES.items():\n if type_def['has_mime_type'](name):\n return type_name\n\n return 'unknown'\n\ndef create_tmp_dir():\n return tempfile.mkdtemp(prefix='cvat-', suffix='.data')\n\ndef delete_tmp_dir(tmp_dir):\n if tmp_dir:\n shutil.rmtree(tmp_dir)\n\nclass IMediaReader(ABC):\n def __init__(self, source_path, step, start, stop):\n self._source_path = sorted(source_path)\n self._step = step\n self._start = start\n self._stop = stop\n\n @abstractmethod\n def __iter__(self):\n pass\n\n @abstractmethod\n def get_preview(self):\n pass\n\n @abstractmethod\n def get_progress(self, pos):\n pass\n\n @staticmethod\n def _get_preview(obj):\n PREVIEW_SIZE = (256, 256)\n if isinstance(obj, io.IOBase):\n preview = Image.open(obj)\n else:\n preview = obj\n preview.thumbnail(PREVIEW_SIZE)\n\n return preview.convert('RGB')\n\n @abstractmethod\n def get_image_size(self, i):\n pass\n\n def __len__(self):\n return len(self.frame_range)\n\n @property\n def frame_range(self):\n return range(self._start, self._stop, self._step)\n\nclass ImageListReader(IMediaReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n if not source_path:\n raise Exception('No image found')\n\n if stop is None:\n stop = len(source_path)\n else:\n stop = min(len(source_path), stop + 1)\n step = max(step, 1)\n assert stop > start\n\n super().__init__(\n source_path=source_path,\n step=step,\n start=start,\n stop=stop,\n )\n\n def __iter__(self):\n for i in range(self._start, self._stop, self._step):\n yield (self.get_image(i), self.get_path(i), i)\n\n def get_path(self, i):\n return self._source_path[i]\n\n def get_image(self, i):\n return self._source_path[i]\n\n def get_progress(self, pos):\n return (pos - self._start + 1) / (self._stop - self._start)\n\n def get_preview(self):\n fp = open(self._source_path[0], \"rb\")\n return self._get_preview(fp)\n\n def get_image_size(self, i):\n img = Image.open(self._source_path[i])\n return img.width, img.height\n\nclass DirectoryReader(ImageListReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n image_paths = []\n for source in source_path:\n for root, _, files in os.walk(source):\n paths = [os.path.join(root, f) for f in files]\n paths = filter(lambda x: get_mime(x) == 'image', paths)\n image_paths.extend(paths)\n super().__init__(\n source_path=image_paths,\n step=step,\n start=start,\n stop=stop,\n )\n\nclass ArchiveReader(DirectoryReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n self._archive_source = source_path[0]\n extract_dir = source_path[1] if len(source_path) > 1 else os.path.dirname(source_path[0])\n Archive(self._archive_source).extractall(extract_dir)\n if extract_dir == os.path.dirname(source_path[0]):\n os.remove(self._archive_source)\n super().__init__(\n source_path=[extract_dir],\n step=step,\n start=start,\n stop=stop,\n )\n\nclass PdfReader(ImageListReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n if not source_path:\n raise Exception('No PDF found')\n\n self._pdf_source = source_path[0]\n\n _basename = os.path.splitext(os.path.basename(self._pdf_source))[0]\n _counter = itertools.count()\n def _make_name():\n for page_num in _counter:\n yield '{}{:09d}.jpeg'.format(_basename, page_num)\n\n from pdf2image import convert_from_path\n self._tmp_dir = os.path.dirname(source_path[0])\n os.makedirs(self._tmp_dir, exist_ok=True)\n\n # Avoid OOM: https://github.com/openvinotoolkit/cvat/issues/940\n paths = convert_from_path(self._pdf_source,\n last_page=stop, paths_only=True,\n output_folder=self._tmp_dir, fmt=\"jpeg\", output_file=_make_name())\n\n os.remove(source_path[0])\n\n super().__init__(\n source_path=paths,\n step=step,\n start=start,\n stop=stop,\n )\n\nclass ZipReader(ImageListReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n self._dimension = DimensionType.DIM_2D\n self._zip_source = zipfile.ZipFile(source_path[0], mode='a')\n self.extract_dir = source_path[1] if len(source_path) > 1 else None\n file_list = [f for f in self._zip_source.namelist() if get_mime(f) == 'image']\n super().__init__(file_list, step, start, stop)\n\n def __del__(self):\n self._zip_source.close()\n\n def get_preview(self):\n if self._dimension == DimensionType.DIM_3D:\n fp = open(os.path.join(os.path.dirname(__file__), 'assets/3d_preview.jpeg'), \"rb\")\n return self._get_preview(fp)\n io_image = io.BytesIO(self._zip_source.read(self._source_path[0]))\n return self._get_preview(io_image)\n\n def get_image_size(self, i):\n if self._dimension == DimensionType.DIM_3D:\n with self._zip_source.open(self._source_path[i], \"r\") as file:\n properties = ValidateDimension.get_pcd_properties(file)\n return int(properties[\"WIDTH\"]), int(properties[\"HEIGHT\"])\n img = Image.open(io.BytesIO(self._zip_source.read(self._source_path[i])))\n return img.width, img.height\n\n def get_image(self, i):\n return io.BytesIO(self._zip_source.read(self._source_path[i]))\n\n def add_files(self, source_path):\n root_path = os.path.split(self._zip_source.filename)[0]\n for path in source_path:\n self._zip_source.write(path, path.replace(root_path, \"\"))\n\n def get_zip_filename(self):\n return self._zip_source.filename\n\n def reconcile(self, source_files, step=1, start=0, stop=None, dimension=DimensionType.DIM_2D):\n self._dimension = dimension\n super().__init__(\n source_path=source_files,\n step=step,\n start=start,\n stop=stop\n )\n\n def get_path(self, i):\n if self._zip_source.filename:\n return os.path.join(os.path.dirname(self._zip_source.filename), self._source_path[i]) \\\n if not self.extract_dir else os.path.join(self.extract_dir, self._source_path[i])\n else: # necessary for mime_type definition\n return self._source_path[i]\n\n def extract(self):\n self._zip_source.extractall(self.extract_dir if self.extract_dir else os.path.dirname(self._zip_source.filename))\n if not self.extract_dir:\n os.remove(self._zip_source.filename)\n\nclass VideoReader(IMediaReader):\n def __init__(self, source_path, step=1, start=0, stop=None):\n super().__init__(\n source_path=source_path,\n step=step,\n start=start,\n stop=stop + 1 if stop is not None else stop,\n )\n\n def _has_frame(self, i):\n if i >= self._start:\n if (i - self._start) % self._step == 0:\n if self._stop is None or i < self._stop:\n return True\n\n return False\n\n def _decode(self, container):\n frame_num = 0\n for packet in container.demux():\n if packet.stream.type == 'video':\n for image in packet.decode():\n frame_num += 1\n if self._has_frame(frame_num - 1):\n if packet.stream.metadata.get('rotate'):\n old_image = image\n image = av.VideoFrame().from_ndarray(\n rotate_image(\n image.to_ndarray(format='bgr24'),\n 360 - int(container.streams.video[0].metadata.get('rotate'))\n ),\n format ='bgr24'\n )\n image.pts = old_image.pts\n yield (image, self._source_path[0], image.pts)\n\n def __iter__(self):\n container = self._get_av_container()\n source_video_stream = container.streams.video[0]\n source_video_stream.thread_type = 'AUTO'\n\n return self._decode(container)\n\n def get_progress(self, pos):\n container = self._get_av_container()\n # Not for all containers return real value\n stream = container.streams.video[0]\n return pos / stream.duration if stream.duration else None\n\n def _get_av_container(self):\n if isinstance(self._source_path[0], io.BytesIO):\n self._source_path[0].seek(0) # required for re-reading\n return av.open(self._source_path[0])\n\n def get_preview(self):\n container = self._get_av_container()\n stream = container.streams.video[0]\n preview = next(container.decode(stream))\n return self._get_preview(preview.to_image() if not stream.metadata.get('rotate') \\\n else av.VideoFrame().from_ndarray(\n rotate_image(\n preview.to_ndarray(format='bgr24'),\n 360 - int(container.streams.video[0].metadata.get('rotate'))\n ),\n format ='bgr24'\n ).to_image()\n )\n\n def get_image_size(self, i):\n image = (next(iter(self)))[0]\n return image.width, image.height\n\nclass IChunkWriter(ABC):\n def __init__(self, quality, dimension=DimensionType.DIM_2D):\n # translate inversed range [1:100] to [0:51]\n self._image_quality = round(51 * (100 - quality) / 99)\n self._dimension = dimension\n\n @staticmethod\n def _compress_image(image_path, quality):\n image = image_path.to_image() if isinstance(image_path, av.VideoFrame) else Image.open(image_path)\n # Ensure image data fits into 8bit per pixel before RGB conversion as PIL clips values on conversion\n if image.mode == \"I\":\n # Image mode is 32bit integer pixels.\n # Autoscale pixels by factor 2**8 / im_data.max() to fit into 8bit\n im_data = np.array(image)\n im_data = im_data * (2**8 / im_data.max())\n image = Image.fromarray(im_data.astype(np.int32))\n converted_image = image.convert('RGB')\n image.close()\n buf = io.BytesIO()\n converted_image.save(buf, format='JPEG', quality=quality, optimize=True)\n buf.seek(0)\n width, height = converted_image.size\n converted_image.close()\n return width, height, buf\n\n @abstractmethod\n def save_as_chunk(self, images, chunk_path):\n pass\n\nclass ZipChunkWriter(IChunkWriter):\n def save_as_chunk(self, images, chunk_path):\n with zipfile.ZipFile(chunk_path, 'x') as zip_chunk:\n for idx, (image, path, _) in enumerate(images):\n arcname = '{:06d}{}'.format(idx, os.path.splitext(path)[1])\n if isinstance(image, io.BytesIO):\n zip_chunk.writestr(arcname, image.getvalue())\n else:\n zip_chunk.write(filename=image, arcname=arcname)\n # return empty list because ZipChunkWriter write files as is\n # and does not decode it to know img size.\n return []\n\nclass ZipCompressedChunkWriter(IChunkWriter):\n def save_as_chunk(self, images, chunk_path):\n image_sizes = []\n with zipfile.ZipFile(chunk_path, 'x') as zip_chunk:\n for idx, (image, _, _) in enumerate(images):\n if self._dimension == DimensionType.DIM_2D:\n w, h, image_buf = self._compress_image(image, self._image_quality)\n extension = \"jpeg\"\n else:\n image_buf = open(image, \"rb\") if isinstance(image, str) else image\n properties = ValidateDimension.get_pcd_properties(image_buf)\n w, h = int(properties[\"WIDTH\"]), int(properties[\"HEIGHT\"])\n extension = \"pcd\"\n image_buf.seek(0, 0)\n image_buf = io.BytesIO(image_buf.read())\n image_sizes.append((w, h))\n arcname = '{:06d}.{}'.format(idx, extension)\n zip_chunk.writestr(arcname, image_buf.getvalue())\n return image_sizes\n\nclass Mpeg4ChunkWriter(IChunkWriter):\n def __init__(self, quality=67):\n super().__init__(quality)\n self._output_fps = 25\n try:\n codec = av.codec.Codec('libopenh264', 'w')\n self._codec_name = codec.name\n self._codec_opts = {\n 'profile': 'constrained_baseline',\n 'qmin': str(self._image_quality),\n 'qmax': str(self._image_quality),\n 'rc_mode': 'buffer',\n }\n except av.codec.codec.UnknownCodecError:\n codec = av.codec.Codec('libx264', 'w')\n self._codec_name = codec.name\n self._codec_opts = {\n \"crf\": str(self._image_quality),\n \"preset\": \"ultrafast\",\n }\n\n def _create_av_container(self, path, w, h, rate, options, f='mp4'):\n # x264 requires width and height must be divisible by 2 for yuv420p\n if h % 2:\n h += 1\n if w % 2:\n w += 1\n\n container = av.open(path, 'w',format=f)\n video_stream = container.add_stream(self._codec_name, rate=rate)\n video_stream.pix_fmt = \"yuv420p\"\n video_stream.width = w\n video_stream.height = h\n video_stream.options = options\n\n return container, video_stream\n\n def save_as_chunk(self, images, chunk_path):\n if not images:\n raise Exception('no images to save')\n\n input_w = images[0][0].width\n input_h = images[0][0].height\n\n output_container, output_v_stream = self._create_av_container(\n path=chunk_path,\n w=input_w,\n h=input_h,\n rate=self._output_fps,\n options=self._codec_opts,\n )\n\n self._encode_images(images, output_container, output_v_stream)\n output_container.close()\n return [(input_w, input_h)]\n\n @staticmethod\n def _encode_images(images, container, stream):\n for frame, _, _ in images:\n # let libav set the correct pts and time_base\n frame.pts = None\n frame.time_base = None\n\n for packet in stream.encode(frame):\n container.mux(packet)\n\n # Flush streams\n for packet in stream.encode():\n container.mux(packet)\n\nclass Mpeg4CompressedChunkWriter(Mpeg4ChunkWriter):\n def __init__(self, quality):\n super().__init__(quality)\n if self._codec_name == 'libx264':\n self._codec_opts = {\n 'profile': 'baseline',\n 'coder': '0',\n 'crf': str(self._image_quality),\n 'wpredp': '0',\n 'flags': '-loop',\n }\n\n def save_as_chunk(self, images, chunk_path):\n if not images:\n raise Exception('no images to save')\n\n input_w = images[0][0].width\n input_h = images[0][0].height\n\n downscale_factor = 1\n while input_h / downscale_factor >= 1080:\n downscale_factor *= 2\n\n output_h = input_h // downscale_factor\n output_w = input_w // downscale_factor\n\n output_container, output_v_stream = self._create_av_container(\n path=chunk_path,\n w=output_w,\n h=output_h,\n rate=self._output_fps,\n options=self._codec_opts,\n )\n\n self._encode_images(images, output_container, output_v_stream)\n output_container.close()\n return [(input_w, input_h)]\n\ndef _is_archive(path):\n mime = mimetypes.guess_type(path)\n mime_type = mime[0]\n encoding = mime[1]\n supportedArchives = ['application/x-rar-compressed',\n 'application/x-tar', 'application/x-7z-compressed', 'application/x-cpio',\n 'gzip', 'bzip2']\n return mime_type in supportedArchives or encoding in supportedArchives\n\ndef _is_video(path):\n mime = mimetypes.guess_type(path)\n return mime[0] is not None and mime[0].startswith('video')\n\ndef _is_image(path):\n mime = mimetypes.guess_type(path)\n # Exclude vector graphic images because Pillow cannot work with them\n return mime[0] is not None and mime[0].startswith('image') and \\\n not mime[0].startswith('image/svg')\n\ndef _is_dir(path):\n return os.path.isdir(path)\n\ndef _is_pdf(path):\n mime = mimetypes.guess_type(path)\n return mime[0] == 'application/pdf'\n\ndef _is_zip(path):\n mime = mimetypes.guess_type(path)\n mime_type = mime[0]\n encoding = mime[1]\n supportedArchives = ['application/zip']\n return mime_type in supportedArchives or encoding in supportedArchives\n\n# 'has_mime_type': function receives 1 argument - path to file.\n# Should return True if file has specified media type.\n# 'extractor': class that extracts images from specified media.\n# 'mode': 'annotation' or 'interpolation' - mode of task that should be created.\n# 'unique': True or False - describes how the type can be combined with other.\n# True - only one item of this type and no other is allowed\n# False - this media types can be combined with other which have unique == False\n\nMEDIA_TYPES = {\n 'image': {\n 'has_mime_type': _is_image,\n 'extractor': ImageListReader,\n 'mode': 'annotation',\n 'unique': False,\n },\n 'video': {\n 'has_mime_type': _is_video,\n 'extractor': VideoReader,\n 'mode': 'interpolation',\n 'unique': True,\n },\n 'archive': {\n 'has_mime_type': _is_archive,\n 'extractor': ArchiveReader,\n 'mode': 'annotation',\n 'unique': True,\n },\n 'directory': {\n 'has_mime_type': _is_dir,\n 'extractor': DirectoryReader,\n 'mode': 'annotation',\n 'unique': False,\n },\n 'pdf': {\n 'has_mime_type': _is_pdf,\n 'extractor': PdfReader,\n 'mode': 'annotation',\n 'unique': True,\n },\n 'zip': {\n 'has_mime_type': _is_zip,\n 'extractor': ZipReader,\n 'mode': 'annotation',\n 'unique': True,\n }\n}\n\n\nclass ValidateDimension:\n\n def __init__(self, path=None):\n self.dimension = DimensionType.DIM_2D\n self.path = path\n self.related_files = {}\n self.image_files = {}\n self.converted_files = []\n\n @staticmethod\n def get_pcd_properties(fp, verify_version=False):\n kv = {}\n pcd_version = [\"0.7\", \"0.6\", \"0.5\", \"0.4\", \"0.3\", \"0.2\", \"0.1\",\n \".7\", \".6\", \".5\", \".4\", \".3\", \".2\", \".1\"]\n try:\n for line in fp:\n line = line.decode(\"utf-8\")\n if line.startswith(\"#\"):\n continue\n k, v = line.split(\" \", maxsplit=1)\n kv[k] = v.strip()\n if \"DATA\" in line:\n break\n if verify_version:\n if \"VERSION\" in kv and kv[\"VERSION\"] in pcd_version:\n return True\n return None\n return kv\n except AttributeError:\n return None\n\n @staticmethod\n def convert_bin_to_pcd(path, delete_source=True):\n list_pcd = []\n with open(path, \"rb\") as f:\n size_float = 4\n byte = f.read(size_float * 4)\n while byte:\n x, y, z, _ = struct.unpack(\"ffff\", byte)\n list_pcd.append([x, y, z])\n byte = f.read(size_float * 4)\n np_pcd = np.asarray(list_pcd)\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(np_pcd)\n pcd_filename = path.replace(\".bin\", \".pcd\")\n o3d.io.write_point_cloud(pcd_filename, pcd)\n if delete_source:\n os.remove(path)\n return pcd_filename\n\n def set_path(self, path):\n self.path = path\n\n def bin_operation(self, file_path, actual_path):\n pcd_path = ValidateDimension.convert_bin_to_pcd(file_path)\n self.converted_files.append(pcd_path)\n return pcd_path.split(actual_path)[-1][1:]\n\n @staticmethod\n def pcd_operation(file_path, actual_path):\n with open(file_path, \"rb\") as file:\n is_pcd = ValidateDimension.get_pcd_properties(file, verify_version=True)\n return file_path.split(actual_path)[-1][1:] if is_pcd else file_path\n\n def process_files(self, root, actual_path, files):\n pcd_files = {}\n\n for file in files:\n file_name, file_extension = file.rsplit('.', maxsplit=1)\n file_path = os.path.abspath(os.path.join(root, file))\n\n if file_extension == \"bin\":\n path = self.bin_operation(file_path, actual_path)\n pcd_files[file_name] = path\n self.related_files[path] = []\n\n elif file_extension == \"pcd\":\n path = ValidateDimension.pcd_operation(file_path, actual_path)\n if path == file_path:\n self.image_files[file_name] = file_path\n else:\n pcd_files[file_name] = path\n self.related_files[path] = []\n else:\n self.image_files[file_name] = file_path\n return pcd_files\n\n def validate_velodyne_points(self, *args):\n root, actual_path, files = args\n velodyne_files = self.process_files(root, actual_path, files)\n related_path = os.path.split(os.path.split(root)[0])[0]\n\n path_list = [re.search(r'image_\\d.*', path, re.IGNORECASE) for path in os.listdir(related_path) if\n os.path.isdir(os.path.join(related_path, path))]\n\n for path_ in path_list:\n if path_:\n path = os.path.join(path_.group(), \"data\")\n path = os.path.abspath(os.path.join(related_path, path))\n\n files = [file for file in os.listdir(path) if\n os.path.isfile(os.path.abspath(os.path.join(path, file)))]\n for file in files:\n\n f_name = file.split(\".\")[0]\n if velodyne_files.get(f_name, None):\n self.related_files[velodyne_files[f_name]].append(\n os.path.abspath(os.path.join(path, file)))\n\n def validate_pointcloud(self, *args):\n root, actual_path, files = args\n pointcloud_files = self.process_files(root, actual_path, files)\n related_path = root.split(\"pointcloud\")[0]\n related_images_path = os.path.join(related_path, \"related_images\")\n\n if os.path.isdir(related_images_path):\n paths = [path for path in os.listdir(related_images_path) if\n os.path.isdir(os.path.abspath(os.path.join(related_images_path, path)))]\n\n for k in pointcloud_files:\n for path in paths:\n\n if k == path.split(\"_\")[0]:\n file_path = os.path.abspath(os.path.join(related_images_path, path))\n files = [file for file in os.listdir(file_path) if\n os.path.isfile(os.path.join(file_path, file))]\n for related_image in files:\n self.related_files[pointcloud_files[k]].append(os.path.join(file_path, related_image))\n\n def validate_default(self, *args):\n root, actual_path, files = args\n pcd_files = self.process_files(root, actual_path, files)\n if len(list(pcd_files.keys())):\n\n for image in self.image_files.keys():\n if pcd_files.get(image, None):\n self.related_files[pcd_files[image]].append(self.image_files[image])\n\n current_directory_name = os.path.split(root)\n\n if len(pcd_files.keys()) == 1:\n pcd_name = list(pcd_files.keys())[0].split(\".\")[0]\n if current_directory_name[1] == pcd_name:\n for related_image in self.image_files.values():\n if root == os.path.split(related_image)[0]:\n self.related_files[pcd_files[pcd_name]].append(related_image)\n\n def validate(self):\n \"\"\"\n Validate the directory structure for kitty and point cloud format.\n \"\"\"\n if not self.path:\n return\n actual_path = self.path\n for root, _, files in os.walk(actual_path):\n\n if root.endswith(\"data\"):\n if os.path.split(os.path.split(root)[0])[1] == \"velodyne_points\":\n self.validate_velodyne_points(root, actual_path, files)\n\n elif os.path.split(root)[-1] == \"pointcloud\":\n self.validate_pointcloud(root, actual_path, files)\n\n else:\n self.validate_default(root, actual_path, files)\n\n if len(self.related_files.keys()):\n self.dimension = DimensionType.DIM_3D\n"
]
| [
[
"numpy.array",
"numpy.asarray"
]
]
|
rickdr/Data-analysis-DNN-testing | [
"a6b049ba218843c3ea9edf318f13a6f192b7a440"
]
| [
".history/project/data_coverage/coverage_methods_20220218003450.py"
]
| [
"import torch\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nfrom sklearn.multiclass import OneVsOneClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\ndef num_per_target(targets):\n target_count = {}\n for target in targets:\n for key in target:\n if hasattr(key, 'cpu'):\n key = key.cpu()\n key = key.item()\n\n if key not in target_count:\n target_count[key] = 0\n target_count[key] += 1\n return target_count\n\ndef eq_part(targets):\n target_count = num_per_target(targets)\n num_classes = len(target_count)\n means = {}\n total = sum(target_count.values())\n for x, i in enumerate(target_count):\n means[i] = target_count[i] * num_classes / total\n # mean_dist = float(sum(means.values())) / num_classes\n # minimal_dist = float(min(means.values())) / num_classes\n return means \n\ndef cent_pos(dataset, targets, bound_threshold=10):\n \"\"\"\n for case in range(classes)\n Average euclidean distance centroid to test points per class\n --------------------------------\n number of testcases per class\n \"\"\"\n class_sorted_data = {}\n centroids = {}\n target_count = num_per_target(targets)\n \n # sort points per class\n for data, target in zip(dataset, targets):\n for data_point, label in zip(data, target):\n if label.item() not in class_sorted_data:\n class_sorted_data[label.item()] = []\n\n point = data_point.reshape(-1)\n class_sorted_data[label.item()].append(point)\n\n for target, data in class_sorted_data.items():\n # Calculate centroid(mean of points per target)\n mean_example = torch.mean(torch.stack(data), dim=0)\n centroids[target] = mean_example\n\n dists = []\n for i, data_point in enumerate(data):\n dist = torch.linalg.norm(centroids[target] - data_point)\n dists.append(1 if dist.item() <= bound_threshold else 0)\n\n class_sorted_data[target] = sum(dists) / target_count[target]\n\n return class_sorted_data"
]
| [
[
"torch.linalg.norm",
"torch.stack"
]
]
|
pdx-cs-sound/harmony | [
"435cdabd85139317cd0e8bce7a25904a3257d30b"
]
| [
"harmony.py"
]
| [
"#!/usr/bin/python3\n# Copyright © 2019 Bart Massey\n# [This program is licensed under the \"MIT License\"]\n# Please see the file LICENSE in the source\n# distribution of this software for license terms.\n\n\nimport numpy as np\nimport resamp\nimport wavio\n\n# Combine a sample with a copy shifted up a third and a copy\n# shifted down two octaves for a harmonizing effect.\n# Play it for 5 seconds.\n\n# Get some samples.\nsamples = wavio.readwav(\"loop.wav\")\nnsamples = len(samples)\n\n# Minimum and maximum expected fundamental frequency of\n# samples in Hz.\nf_min = 110\nf_max = 1720\n\n# Minimum and maximum periods in samples.\ns_max = 48000 // f_min\ns_min = 48000 // f_max\n\n# Do an FFT to try to find the period of the signal.\nnfft = 2**14\nnwin = 4 * s_max\nwindowed = np.hamming(nwin) * np.array(samples[:nwin])\nspectrum = np.abs(np.fft.rfft(windowed, n=nfft))\nimax = np.argmax(spectrum)\ndc = np.abs(spectrum[0])\namax = np.abs(spectrum[imax])\nfmax = np.fft.rfftfreq(nfft, d=1/48000)[imax]\npmax = int(48000 / fmax)\nprint(dc, amax, fmax, pmax)\n\n# Maximum search for autocorrelator.\nac_samples = 2 * pmax\n\n# Sample length for autocorrelator.\nac_length = ac_samples\n\n# Do an autocorrelation to try to find a good place to\n# end the samples so they loop.\ncmax = None\numax = None\nfor t in range(ac_samples):\n u = nsamples - ac_length - t\n st = samples[:ac_length]\n su = samples[u:u+ac_length]\n corr = np.dot(st, su)\n if cmax == None or corr > cmax:\n cmax = corr\n umax = u\nprint(cmax, nsamples - umax)\nsamples = samples[:umax + ac_length]\nnsamples = len(samples)\n\n# Size of lap window from beginning to end of samples.\nlap_samples = 0\n\n# Lap the samples.\nfor i in range(lap_samples):\n c = i / (lap_samples - 1)\n samples[i] *= 1 - c\n samples[i] += c * samples[nsamples + i - lap_samples - 1]\n\n# Use an interpolation window this size around each sample.\n# Window should be odd.\nwindow = 9\n\n# Replicate the samples for 5 seconds.\nnreplica = 5 * 48000\n\n# We will skip through the samples ratio faster.\ndef make_harmony(ratio):\n ratio *= 440 / fmax\n cutoff = 20000 * min(1, ratio)\n harmony = np.array([0] * nreplica, dtype=np.float)\n for i in range(nreplica):\n x = (i * ratio) % nsamples\n harmony[i] = resamp.resamp(x, samples, cutoff, 48000, window)\n return harmony\n\n# Make a slightly truncated copy of the root.\nroot = make_harmony(1)\n\n# A third is four semitones up from the root.\nthird = make_harmony(2**(4 / 12))\n\n# Two octaves is 1/4 rate.\noctaves_down = make_harmony(0.25)\n\n# Mix the notes.\nharmony = (root + third + octaves_down) / 3\n\nwavio.writewav(\"harmony.wav\", harmony)\n"
]
| [
[
"numpy.array",
"numpy.fft.rfft",
"numpy.dot",
"numpy.fft.rfftfreq",
"numpy.hamming",
"numpy.argmax",
"numpy.abs"
]
]
|
ryujaehun/chameleon | [
"e9f480ece508e05eae7698d621aa7bfd2dc63221"
]
| [
"optimization_tvm/tune_relay_cuda.py"
]
| [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nAuto-tuning a convolutional network for NVIDIA GPU\n==================================================\n**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_, `Eddie Yan <https://github.com/eqy/>`_\n\nAuto-tuning for specific devices and workloads is critical for getting the\nbest performance. This is a tutorial on how to tune a whole convolutional\nnetwork for NVIDIA GPU.\n\nThe operator implementation for NVIDIA GPU in TVM is written in template form.\nThe template has many tunable knobs (tile factor, unrolling, etc).\nWe will tune all convolution and depthwise convolution operators\nin the neural network. After tuning, we produce a log file which stores\nthe best knob values for all required operators. When the TVM compiler compiles\nthese operators, it will query this log file to get the best knob values.\n\nWe also released pre-tuned parameters for some NVIDIA GPUs. You can go to\n`NVIDIA GPU Benchmark <https://github.com/apache/incubator-tvm/wiki/Benchmark#nvidia-gpu>`_\nto see the results.\n\"\"\"\n\n######################################################################\n# Install dependencies\n# --------------------\n# To use the autotvm package in tvm, we need to install some extra dependencies.\n# (change \"3\" to \"2\" if you use python2):\n#\n# .. code-block:: bash\n#\n# pip3 install --user psutil xgboost tornado\n#\n# To make TVM run faster during tuning, it is recommended to use cython\n# as FFI of tvm. In the root directory of tvm, execute:\n#\n# .. code-block:: bash\n#\n# pip3 install --user cython\n# sudo make cython3\n#\n# Now return to python code. Import packages.\n\nimport os,datetime\nimport argparse\nimport numpy as np\n\nimport tvm\nfrom tvm import autotvm\nfrom tvm import relay\nimport tvm.relay.testing\nfrom tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\nfrom tvm.autotvm.graph_tuner import DPTuner, PBQPTuner\nfrom tvm.contrib import util,graph_runtime\nfrom tvm.contrib.util import tempdir\nimport tvm.contrib.graph_runtime as runtime\n\nparser = argparse.ArgumentParser(prog='autotune-cuda')\nparser.add_argument('--network', type=str, default='resnet-34', help='choose network')\nparser.add_argument('--batch', type=int, default=1, help='choose batch size')\nparser.add_argument('--tuner', type=str, default='random', help='choose num of threads')\nparser.add_argument('--n_trial', type=int, default=2, help='choose num of threads')\nparser.add_argument('--time', type=str, default='200', help='choose num of threads')\nopt = parser.parse_args()\n#################################################################\n# Define Network\n# --------------\n# First we need to define the network in relay frontend API.\n# We can load some pre-defined network from :code:`tvm.relay.testing`.\n# We can also load models from MXNet, ONNX and TensorFlow.\n\ndef get_network(name, batch_size):\n \"\"\"Get the symbol definition and random weight of a network\"\"\"\n input_shape = (batch_size, 3, 224, 224)\n output_shape = (batch_size, 1000)\n\n if \"resnet\" in name:\n n_layer = int(name.split('-')[1])\n mod, params = relay.testing.resnet.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n elif \"vgg\" in name:\n n_layer = int(name.split('-')[1])\n mod, params = relay.testing.vgg.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n elif name == 'mobilenet':\n mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n elif name == 'squeezenet_v1.1':\n mod, params = relay.testing.squeezenet.get_workload(batch_size=batch_size, version='1.1', dtype=dtype)\n elif name == 'inception_v3':\n input_shape = (1, 3, 299, 299)\n mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n elif name == 'mxnet':\n # an example for mxnet model\n from mxnet.gluon.model_zoo.vision import get_model\n block = get_model('resnet18_v1', pretrained=True)\n mod, params = relay.frontend.from_mxnet(block, shape={'data': input_shape}, dtype=dtype)\n net = mod[\"main\"]\n net = relay.Function(net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs)\n mod = tvm.IRModule.from_expr(net)\n else:\n raise ValueError(\"Unsupported network: \" + name)\n\n return mod, params, input_shape, output_shape\n\n###########################################\n# Set Tuning Options\n# ------------------\n# Before tuning, we apply some configurations.\n\n#### DEVICE CONFIG ####\ntarget = tvm.target.cuda()\n# time=\"_\".join(str(datetime.datetime.now()).split())\n# time=os.path.join('results/cuda',time)\n# os.makedirs(time)\ntime=opt.time\n\n#### TUNING OPTION ####\nmodel_name =opt.network\nlog_file =time+ \"/%s.log\" % model_name\ngraph_opt_sch_file = time+\"/%s_graph_opt.log\" % model_name\ndtype = 'float32'\ninput_name = \"data\"\ntuning_option = {\n 'log_filename': log_file,\n 'tuner': opt.tuner,\n 'n_trial': opt.n_trial,\n 'early_stopping': 1000,\n 'measure_option': autotvm.measure_option(\n builder=autotvm.LocalBuilder(timeout=10),\n runner=autotvm.LocalRunner(number=20, repeat=3, timeout=4, min_repeat_ms=150)\n\n ),\n}\n\n## ISSUE : https://discuss.tvm.ai/t/autotvm-localrunner-not-working-on-windows/969/3\n\n\ndef tune_tasks(tasks,\n measure_option,\n tuner='xgb',\n n_trial=1000,\n early_stopping=None,\n log_filename=time+'/tuning.log',\n use_transfer_learning=True,\n try_winograd=True):\n if try_winograd:\n for i in range(len(tasks)):\n try: # try winograd template\n tsk = autotvm.task.create(tasks[i].name, tasks[i].args,\n tasks[i].target, tasks[i].target_host, 'winograd')\n input_channel = tsk.workload[1][1]\n if input_channel >= 64:\n tasks[i] = tsk\n except Exception:\n pass\n \n # create tmp log file\n tmp_log_file = log_filename + \".tmp\"\n if os.path.exists(tmp_log_file):\n os.remove(tmp_log_file)\n\n for i, tsk in enumerate(reversed(tasks)):\n prefix = \"[Task %2d/%2d] \" %(i+1, len(tasks))\n\n # create tuner\n if tuner == 'xgb' or tuner == 'xgb-rank':\n tuner_obj = XGBTuner(tsk, loss_type='rank')\n elif tuner == 'ga':\n tuner_obj = GATuner(tsk, pop_size=100)\n elif tuner == 'random':\n tuner_obj = RandomTuner(tsk)\n elif tuner == 'gridsearch':\n tuner_obj = GridSearchTuner(tsk)\n else:\n raise ValueError(\"Invalid tuner: \" + tuner)\n\n if use_transfer_learning:\n if os.path.isfile(tmp_log_file):\n tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n\n # do tuning\n tsk_trial = min(n_trial, len(tsk.config_space))\n tuner_obj.tune(n_trial=tsk_trial,\n early_stopping=early_stopping,\n measure_option=measure_option,\n callbacks=[\n autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n autotvm.callback.log_to_file(tmp_log_file)\n ])\n\n # pick best records to a cache file\n autotvm.record.pick_best(tmp_log_file, log_filename)\n os.remove(tmp_log_file)\n\n\n########################################################################\n# Finally, we launch tuning jobs and evaluate the end-to-end performance.\ndef tune_graph(graph, dshape, records, opt_sch_file, use_DP=True):\n target_op = [relay.nn.conv2d]\n Tuner = DPTuner if use_DP else PBQPTuner\n executor = Tuner(graph, {input_name: dshape}, records, target_op, target,log_file=time+\"/graph_tuner.log\")\n executor.benchmark_layout_transform(min_exec_num=2000,target_host='cuda')\n executor.run()\n executor.write_opt_sch2record_file(opt_sch_file)\n\ndef tune_and_evaluate(tuning_opt):\n # extract workloads from relay program\n print(\"Extract tasks...\")\n mod, params, input_shape, out_shape = get_network(model_name, batch_size=1)\n tasks = autotvm.task.extract_from_program(mod[\"main\"], target=target,\n params=params, ops=(relay.op.nn.conv2d,))\n\n # run tuning tasks\n print(\"Tuning...\")\n tune_tasks(tasks, **tuning_opt)\n #tune_graph(mod[\"main\"], input_shape, log_file, graph_opt_sch_file)\n\n # compile kernels with history best records\n with autotvm.apply_history_best(log_file):\n print(\"Compile...\")\n with relay.build_config(opt_level=3):\n graph, lib, params = relay.build_module.build(\n mod, target=target, params=params)\n\n # export library\n\n filename = os.path.join(os.getcwd(),time)+\"/net.tar\"\n lib.export_library(filename)\n\n # load parameters\n ctx = tvm.context(str(target), 0)\n module = runtime.create(graph, lib, ctx)\n data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n module.set_input('data', data_tvm)\n module.set_input(**params)\n\n # evaluate\n # print(\"Evaluate inference time cost...\")\n # ftimer = module.module.time_evaluator(\"run\", ctx, number=1, repeat=600)\n # prof_res = np.array(ftimer().results) * 1000 # convert to millisecond\n # print(\"Mean inference time (std dev): %.2f ms (%.2f ms)\" %\n # (np.mean(prof_res), np.std(prof_res)))\n save_graph(graph,params,lib)\n # load_graph(ctx=ctx,data_shape=input_shape,out_shape=out_shape)\ndef save_graph(graph,params,lib):\n temp = os.path.join(os.getcwd(),time)\n path_lib =os.path.join(temp,\"deploy_lib.tar\")\n lib.export_library(path_lib)\n with open(os.path.join(temp,\"deploy_graph.json\"), \"w\") as fo:\n fo.write(graph)\n with open(os.path.join(temp,\"deploy_param.params\"), \"wb\") as fo:\n fo.write(relay.save_param_dict(params))\n print(os.listdir(temp))\ndef load_graph(ctx,data_shape,out_shape,path=None):\n if path is None:\n path=os.path.join(os.getcwd(),time)\n\n path_lib = os.path.join(path,\"deploy_lib.tar\")\n loaded_json = open(os.path.join(path,\"deploy_graph.json\")).read()\n loaded_lib = tvm.runtime.load_module(path_lib)\n loaded_params = bytearray(open(os.path.join(path,\"deploy_param.params\"), \"rb\").read())\n input_data = tvm.nd.array(np.random.uniform(size=data_shape).astype(\"float32\"))\n\n module = graph_runtime.create(loaded_json, loaded_lib, ctx)\n module.load_params(loaded_params)\n module.run(data=input_data)\n out_deploy = module.get_output(0).asnumpy()\n # Print first 10 elements of output\n print(out_deploy.flatten()[0:10])\n # check whether the output from deployed module is consistent with original one\n out = module.get_output(0, tvm.nd.empty(out_shape)).asnumpy()\n tvm.testing.assert_allclose(out_deploy, out, atol=1e-3)\n# We do not run the tuning in our webpage server since it takes too long.\n# Uncomment the following line to run it by yourself.\n\ntune_and_evaluate(tuning_option)\n\n"
]
| [
[
"numpy.random.uniform"
]
]
|
mnpinto/FWIe | [
"b131cc19af8810df4f8170eb97f95bf40511f1d6"
]
| [
"fwie/core.py"
]
| [
"# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).\n\n__all__ = ['chi', 'time_from_wrf', 'coords_from_wrf', 'chi_from_wrf', 'wrf2msg']\n\n# Cell\nimport numpy as np\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom netCDF4 import Dataset\nimport scipy.io as sio\nfrom tqdm import tqdm\nfrom wrf import getvar, interplevel\n\n# Cell\ndef chi(t_850:np.ndarray, td_850:np.ndarray, t_700:np.ndarray):\n \"\"\"\n Computes Continuous Haines Index (CHI)\n t_850 is the temperature at 850 hPa\n t_700 is the temperature at 700 hPa\n td_850 is the dew point temperature at 850 hPa\n \"\"\"\n A = t_850 - t_700\n B = t_850 - td_850\n B[B>30]=30\n CA = 0.5 * A - 2\n CB = 0.3333 * B - 1\n CB[CB>5] = 5 + (CB[CB>5] - 5) / 2\n return CA + CB\n\ndef time_from_wrf(file, time_index):\n ncfile = Dataset(file, mode='r')\n return pd.Timestamp(str(getvar(ncfile, \"times\", timeidx=time_index).data))\n\ndef coords_from_wrf(file):\n ncfile = Dataset(file, mode='r')\n return getvar(ncfile, \"lon\").data, getvar(ncfile, \"lat\").data\n\ndef chi_from_wrf(file, time_index):\n ncfile = Dataset(file, mode='r')\n td = getvar(ncfile, \"td\", timeidx=time_index)\n tc = getvar(ncfile, \"tc\", timeidx=time_index)\n p = getvar(ncfile, \"pressure\", timeidx=time_index)\n t850, t700 = [interplevel(tc, p, level).data for level in [850, 700]]\n td850 = interplevel(td, p, 850).data\n chaines = chi(t850, td850, t700)\n return chaines\n\ndef wrf2msg(lon_wrf, lat_wrf, data_wrf, lon_msg, lat_msg):\n rs, cs = lat_msg.shape\n data_msg = np.zeros_like(lat_msg)*np.nan\n for i in range(1,rs-1):\n for j in range(1,cs-1):\n lat_o = [lat_msg[i-1,j-1], lat_msg[i-1,j+1], lat_msg[i+1,j-1], lat_msg[i+1, j+1]]\n lon_o = [lon_msg[i-1,j-1], lon_msg[i-1,j+1], lon_msg[i+1,j-1], lon_msg[i+1, j+1]]\n I = ((lat_wrf >= min(lat_o)) & (lat_wrf < max(lat_o)) &\n (lon_wrf >= min(lon_o)) & (lon_wrf < max(lon_o)))\n data_msg[i,j] = np.nanmean(data_wrf[I])\n return data_msg"
]
| [
[
"numpy.zeros_like",
"numpy.nanmean"
]
]
|
achawkins/Forsteri | [
"882d684d22d1f1d23ab03fde0b513ec95ac78251"
]
| [
"forsteri/process/model.py"
]
| [
"#!/usr/bin/python\n\n\"\"\"\nGraphical User Interface\n\nCopyright (c) 2014, 2015 Andrew Hawkins\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\n\"\"\"\nImport Declarations\n\"\"\"\nimport copy\nimport datetime as dt\nimport numpy as np\nimport sqlite3\nimport threading as td\nimport wx\n\nfrom forsteri.interface import data as idata\nfrom forsteri.interface import sql as isql\n\n\"\"\"\nConstant Declarations\n\"\"\"\n\n\n\"\"\"\nMain Functions\n\"\"\"\ndef runAllErrors():\n \"\"\"\n \"\"\"\n\n # Create the progress dialog box.\n progress_dlg = wx.ProgressDialog(\"Running Errors\",\n \"Opening database connection.\")\n\n # Open a connection to the data database.\n connection = sqlite3.connect(idata.MASTER)\n\n progress_dlg.Update(10, \"Connection initialized, running MLR errors.\")\n\n # Find the MLR errors.\n idata.updateError(\"mlr\", connection)\n\n progress_dlg.Update(40, \"MLR errors complete, running EMA errors.\")\n\n # Find the EMA errors.\n idata.updateError(\"ema\", connection)\n\n progress_dlg.Update(70, \"EMA errors complete, running Naive errors.\")\n\n # Find the Naive errors.\n idata.updateError(\"naive\", connection)\n\n progress_dlg.Update(99, \"Naive errors complete, commiting changes.\")\n\n # Commit and close the connection.\n connection.commit()\n connection.close()\n\n progress_dlg.Update(100, \"Error process complete.\")\n progress_dlg.Destroy()\n\n return True\n\ndef runAll(products=None):\n \"\"\"\n \"\"\"\n\n # Create the progress dialog box.\n progress_dlg = wx.ProgressDialog(\"Running Models\",\n \"Opening database connection.\")\n\n # Open a connection to the data database.\n connection = sqlite3.connect(idata.MASTER)\n\n progress_dlg.Update(5, \"Connection initialized, gathering products.\")\n\n # Get all products if none are given.\n if products is None:\n products = isql.getProductNames()\n\n progress_dlg.Update(10, \"Products gathered, running EMA model.\")\n\n # Run the EMA model.\n runEMA(products, connection)\n\n progress_dlg.Update(40, \"EMA model complete, running MLR model.\")\n\n # Run the MLR model.\n runMLR(products, connection)\n\n progress_dlg.Update(70, \"MLR model complete, running Nieve model.\")\n\n # Run the Naive model.\n runNaive(products, connection)\n\n progress_dlg.Update(99, \"All models complete, commiting changes.\")\n\n # Commit and close the connection.\n connection.commit()\n connection.close()\n\n progress_dlg.Update(100, \"Model process complete.\")\n progress_dlg.Destroy()\n\n return True\n\ndef runEMA(products=None, connection=None):\n \"\"\"\n Run the exponential moving avergae model for the given products.\n \"\"\"\n\n # Open the master database if it is not supplied.\n flag = False\n if connection is None:\n connection = sqlite3.connect(idata.MASTER)\n flag = True\n\n # Get all products if none are given.\n if products is None:\n products = isql.getProductNames()\n\n # Iterate over each product.\n for product in products:\n # Get the data for the product.\n data = idata.getData(product, \"finished_goods\", connection)\n\n # If no data is held for a product skip it.\n if len(data) == 0:\n continue\n\n # Convert the data to an overlapped numpy array.\n data = overlap(data)\n\n # Find the averages for each month.\n average = eMA(data, alpha=0.7)\n\n # Convert nan to NULL.\n average = [\"NULL\" if np.isnan(x) else x for x in average]\n\n # Add the forecasts to the database.\n idata.updateForecast(product, \"ema\", average, connection)\n\n # Close the connection.\n if flag:\n connection.commit()\n connection.close()\n\n return True\n\ndef runMLR(products=None, connection=None):\n \"\"\"\n Run the multiple linear regression model for the given products with all\n available variables.\n \"\"\"\n\n # Open the master database if it is not supplied.\n flag = False\n if connection is None:\n connection = sqlite3.connect(idata.MASTER)\n flag = True\n\n # Get all products if none are given.\n if products is None:\n products = isql.getProductNames()\n\n # Iterate over each product.\n for product in products:\n # Get the data for the current product.\n (header, data) = idata.getAllData(product)\n\n # If there is no data for a product, skip to the next product.\n if data is None:\n continue\n\n # Process the data into a the overlap form.\n try:\n dataNew = overlap3(data)\n except IndexError:\n continue\n\n # Iterate over each month.\n forecast = []\n for i in range(0, 12):\n try:\n # Determine the coefficient values\n (beta, fit) = mLR(dataNew[i][:, 0], dataNew[i][:, 1:])\n\n # Determine the values to use for each variable.\n vals = np.concatenate((np.array([1]), eMA(dataNew[i][:, 1:],\n alpha=0.7)))\n\n # Find the forecast.\n forecast.append(np.dot(vals, beta))\n except IndexError:\n # Add nan to the forecast.\n forecast.append(np.nan)\n\n # Concert nan to NULL.\n forecast = [\"NULL\" if np.isnan(x) else x for x in forecast]\n\n # Add the forecast values to the database.\n idata.updateForecast(product, \"mlr\", forecast, connection)\n\n # Close the connection.\n if flag:\n connection.commit()\n connection.close()\n\n return True\n\ndef runNaive(products=None, connection=None):\n \"\"\"\n \"\"\"\n\n # Open the master database if it is not supplied.\n flag = False\n if connection is None:\n connection = sqlite3.connect(idata.MASTER)\n flag = True\n\n # Get all products if none are given.\n if products is None:\n products = isql.getProductNames()\n\n # Get the date.\n today = dt.date(1, 1, 1).today()\n\n # Get the finished goods data.\n for product in products:\n data = idata.getData(product, \"finished_goods_monthly\", connection)\n\n # Extract the last 12 data points.\n forecast = data[-12:]\n\n # Convert the dates to be just the months.\n forecast = {dt.datetime.strptime(x[0], \"%Y-%m-%d\").month: x[1] for x\\\n in forecast}\n\n # Pad forecast with NULLs if it is less than length 12.\n if len(forecast) < 12:\n for i in range(1, 13):\n try:\n forecast[i]\n except KeyError:\n forecast[i] = \"NULL\"\n\n # Sort by month.\n forecast = sorted(forecast.items(), key=lambda s: s[0])\n\n # Add the forecast values to the database.\n idata.updateForecast(product, \"naive\", [x[1] for x in forecast],\n connection)\n\n # Close the connection.\n if flag:\n connection.commit()\n connection.close()\n\n return True\n\n\"\"\"\nModel Functions\n\"\"\"\ndef eMA(data, alpha=None):\n \"\"\"\n Find the exponential moving average of some data.\n\n Args:\n data (numpy.array): An array of data.\n alpha (int, optional): The weighting factor.\n\n Returns:\n numpy.array: \n \"\"\"\n\n # Find the shape of the input data.\n shape = np.shape(data)\n\n # If the dimension is higher than one run the function recursively.\n if len(shape) == 2:\n average = []\n for i in range(0, shape[1]):\n average.append(eMA([x[i] for x in data], alpha))\n return average\n elif len(shape) > 2:\n raise(IndexError(\"this function can only take up to a 2 dimensional \\\narray\"))\n\n # If no alpha is given determine the alpha.\n if alpha is None:\n alpha = 2 / (len(data) + 1.0)\n\n # Find the compliment of alpha.\n comp = 1 - alpha\n\n # Find the first non nan index.\n try:\n index = np.where(np.isnan(data) == False)[0][0]\n except IndexError:\n return data[-1]\n\n # Set the initial average.\n average = data[index]\n\n # Iterate over all data points and update the average.\n for i in range(index + 1, len(data)):\n # If the value is nan then do not change the average.\n if np.isnan(data[i]):\n pass\n else:\n average = comp * average + alpha * data[i]\n\n return average\n\ndef mLR(dep, ind):\n \"\"\"\n \"\"\"\n\n # Add a bias column to the independent variables.\n (rows, cols) = np.shape(ind)\n indB = np.ones((rows, cols + 1))\n indB[:, 1:] = ind\n\n # Determine the weighting coefficients.\n beta = np.dot(np.dot(np.linalg.pinv(np.dot(indB.T, indB)), indB.T), dep)\n\n # Determine the historical fit of data.\n fit = np.dot(indB, beta)\n\n return beta, fit\n\n\"\"\"\nHelper Functions\n\"\"\"\ndef overlap(data):\n \"\"\"\n data is in the form [(date1, value1), (date2, value2), ...]\n \"\"\"\n\n # Make a copy of the data.\n data2 = copy.copy(data)\n\n # Extract the first and last year and month.\n firstYear = int(data2[0][0][0 : 4])\n firstMonth = int(data2[0][0][5 : 7])\n lastYear = int(data2[-1][0][0 : 4])\n lastMonth = int(data2[-1][0][5 : 7])\n\n # If the first month is not one, add dates.\n if firstMonth != 1:\n temp = [(str(dt.date(firstYear, i, 1)), np.nan) for i in range(1,\n firstMonth)]\n temp.extend(data2)\n data2 = copy.copy(temp)\n\n # If the last month is not 12, add dates.\n if lastMonth != 12:\n data2.extend([(str(dt.date(lastYear, i, 1)), np.nan) for i in \\\n range(lastMonth + 1, 13)])\n\n # Extract only the values from the data.\n values = [x[1] for x in data2]\n\n # Reshape the data.\n new = np.array([values[i : i + 12] for i in range(0, len(values), 12)])\n\n return new\n\ndef overlap2(data):\n \"\"\"\n \"\"\"\n\n # Make a copy of the data.\n data2 = copy.copy(data)\n\n # Extract the first and last year and month.\n firstYear = int(data2[0][0][0 : 4])\n firstMonth = int(data2[0][0][5 : 7])\n lastYear = int(data2[-1][0][0 : 4])\n lastMonth = int(data2[-1][0][5 : 7])\n\n naTemp = [np.nan] * (len(data2[0]) - 1)\n\n # If the first month is not one, add dates with nan values.\n if firstMonth != 1:\n head = []\n for i in range(1, firstMonth):\n temp = [str(dt.date(firstYear, i, 1))]\n temp.extend(naTemp)\n head.append(tuple(temp))\n head.extend(data2)\n data2 = head.copy()\n\n # If the last month is not 12, add dates with nan values.\n if lastMonth != 12:\n tail = []\n for i in range(lastMonth + 1, 13):\n temp = [str(dt.date(lastYear, i, 1))]\n temp.extend(naTemp)\n tail.append(tuple(temp))\n data2.extend(tail)\n\n final = [[] for i in range(0, 12)]\n index = 1\n for x in data2:\n final[index % 12].append(x[1:])\n index += 1\n\n return final\n\ndef overlap3(data):\n \"\"\"\n \"\"\"\n\n #\n dataC = copy.copy(data)\n\n temp = [[] for i in range(0, 12)]\n\n index = int(dataC[0][0][5 : 7])\n for x in dataC:\n temp[(index % 12) - 1].append(x[1:])\n index += 1\n\n final = []\n for x in temp:\n final.append(np.array(x))\n\n return final\n\ndef curtail(data):\n \"\"\"\n \"\"\"\n\n # Make a copy of the data.\n variables = data.copy()\n\n # Find all of the start and end dates.\n starts = []\n ends = []\n for variable in variables.values():\n starts.append(variable[0][0])\n ends.append(variable[-1][0])\n\n # Determine the latest start and the earliest end.\n first = max(starts)\n last = min(ends)\n\n # Extract the data.\n newData = dict()\n for (key, value) in variables.items():\n temp = []\n for point in value:\n if point[0] < first or point[0] > last:\n pass\n else:\n temp.append(point)\n newData[key] = temp\n\n return newData\n\ndef separate(data):\n \"\"\"\n \"\"\"\n\n # \n for (key, value) in data.items():\n for i in range(0, 12):\n months[i + 1] = np.column_stack(months[i + 1], )\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.isnan",
"numpy.ones",
"numpy.shape",
"numpy.column_stack"
]
]
|
neviim/sklearn | [
"fa1e7d9afedcfcba2c0d21573c72b2b8933c0abd"
]
| [
"src/smv_working_file.py"
]
| [
"'''\n Neste tutorial em python de aprendizado de máquina, apresentarei as Máquinas de \n vetores de suporte. Isso é usado principalmente para classificação e é capaz de \n executar a classificação para dados dimensionais grandes. Também mostrarei como \n carregar conjuntos de dados diretamente do módulo sklearn.\n\n Neste tutorial em python do aprendizado de máquina, explique como funciona uma \n máquina de vetores de suporte. O SVM funciona criando um hiperplano que divide \n os dados de teste em suas classes. Então, olho para qual lado do hiperplano está \n um ponto de dados de teste e o classifico.\n\n Doc:\n sklearn (https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html)\n'''\n\nimport sklearn\nfrom sklearn import datasets\nfrom sklearn import svm\nfrom sklearn import metrics\nfrom sklearn.neighbors import KNeighborsClassifier\n\ncancer = datasets.load_breast_cancer()\n\n#print(cancer.feature_names)\n#print(cancer.target_names)\n\nx = cancer.data\ny = cancer.target\n\nx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)\n\n#print(x_train, y_train)\nclasses = [\"malignant\", \"benign\"]\n\n#clf = svm.SVC() # com este parametro acc = 0.6578947368421053\n#clf = svm.SVC(kernel=\"linear\") # com este parametro acc = 0.9736842105263158\n#clf = svm.SVC(kernel=\"linear\", C=1) # com este parametro acc = 0.956140350877193\n#clf = svm.SVC(kernel=\"linear\", C=2) # com este parametro acc = 0.9298245614035088\n#clf = KNeighborsClassifier(n_neighbors=9) # com este parametro acc = 0.9473684210526315\nclf = KNeighborsClassifier(n_neighbors=13) # com este parametro acc = 0.9210526315789473\nclf.fit(x_train, y_train)\n\ny_pred = clf.predict(x_test)\n\nacc = metrics.accuracy_score(y_test, y_pred)\nprint(acc)\n\n"
]
| [
[
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.metrics.accuracy_score",
"sklearn.datasets.load_breast_cancer"
]
]
|
renier/qiskit-nature | [
"a06f378a219d650d96e16db96d763ea4aec9cfc2"
]
| [
"qiskit_nature/properties/second_quantization/electronic/integrals/two_body_electronic_integrals.py"
]
| [
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The 2-body electronic integrals.\"\"\"\n\nfrom typing import List, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom qiskit_nature import QiskitNatureError\n\nfrom .electronic_integrals import ElectronicIntegrals\nfrom .one_body_electronic_integrals import OneBodyElectronicIntegrals\nfrom ..bases import ElectronicBasis, ElectronicBasisTransform\n\n\nclass TwoBodyElectronicIntegrals(ElectronicIntegrals):\n \"\"\"The 2-body electronic integrals.\"\"\"\n\n EINSUM_AO_TO_MO = \"pqrs,pi,qj,rk,sl->ijkl\"\n EINSUM_CHEM_TO_PHYS = \"ijkl->ljik\"\n\n # TODO: provide symmetry testing functionality?\n\n def __init__(\n self,\n basis: ElectronicBasis,\n matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]],\n threshold: float = ElectronicIntegrals.INTEGRAL_TRUNCATION_LEVEL,\n ) -> None:\n # pylint: disable=line-too-long\n \"\"\"\n Args:\n basis: the basis which these integrals are stored in. If this is initialized with\n :class:`~qiskit_nature.properties.second_quantization.electronic.bases.ElectronicBasis.SO`,\n these integrals will be used *ad verbatim* during the mapping to a\n :class:`~qiskit_nature.operators.second_quantization.SecondQuantizedOp`.\n matrices: the matrices (one or many) storing the actual electronic integrals. If this is\n a single matrix, ``basis`` must be set to\n :class:`~qiskit_nature.properties.second_quantization.electronic.bases.ElectronicBasis.SO`.\n Otherwise, this must be a quartet of matrices, the first one being the\n alpha-alpha-spin matrix (which is required), followed by the beta-alpha-spin,\n beta-beta-spin, and alpha-beta-spin matrices (which are optional). The order of\n these matrices follows the standard assigned of quadrants in a plane geometry. If\n any of the latter three matrices are ``None``, the alpha-alpha-spin matrix will be\n used in their place. However, the final matrix will be replaced by the transpose of\n the second one, if and only if that happens to differ from ``None``.\n threshold: the truncation level below which to treat the integral as zero-valued.\n \"\"\"\n num_body_terms = 2\n super().__init__(num_body_terms, basis, matrices, threshold)\n self._matrix_representations = [\"Alpha-Alpha\", \"Beta-Alpha\", \"Beta-Beta\", \"Alpha-Beta\"]\n\n def _fill_matrices(self) -> None:\n \"\"\"Fills the internal matrices where ``None`` placeholders were inserted.\n\n This method iterates the internal list of matrices and replaces any occurrences of ``None``\n according to the following rules:\n 1. If the Alpha-Beta matrix (third index) is ``None`` and the Beta-Alpha matrix was not\n ``None``, its transpose will be used.\n 2. If the Beta-Alpha matrix was ``None``, the Alpha-Alpha matrix is used as is.\n 3. Any other missing matrix gets replaced by the Alpha-Alpha matrix.\n \"\"\"\n filled_matrices = []\n alpha_beta_spin_idx = 3\n for idx, mat in enumerate(self._matrices):\n if mat is not None:\n filled_matrices.append(mat)\n elif idx == alpha_beta_spin_idx:\n if self._matrices[1] is None:\n filled_matrices.append(self._matrices[0])\n else:\n filled_matrices.append(self._matrices[1].T)\n else:\n filled_matrices.append(self._matrices[0])\n self._matrices = tuple(filled_matrices)\n\n def transform_basis(self, transform: ElectronicBasisTransform) -> \"TwoBodyElectronicIntegrals\":\n # pylint: disable=line-too-long\n \"\"\"Transforms the integrals according to the given transform object.\n\n If the integrals are already in the correct basis, ``self`` is returned.\n\n Args:\n transform: the transformation object with the integral coefficients.\n\n Returns:\n The transformed\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.ElectronicIntegrals`.\n\n Raises:\n QiskitNatureError: if the integrals do not match\n :class:`~qiskit_nature.properties.second_quantization.electronic.bases.ElectronicBasisTransform.initial_basis`.\n \"\"\"\n if self._basis == transform.final_basis:\n return self\n\n if self._basis != transform.initial_basis:\n raise QiskitNatureError(\n f\"The integrals' basis, {self._basis}, does not match the initial basis of the \"\n f\"transform, {transform.initial_basis}.\"\n )\n\n coeff_alpha = transform.coeff_alpha\n coeff_beta = transform.coeff_beta\n\n coeff_list = [\n (coeff_alpha, coeff_alpha, coeff_alpha, coeff_alpha),\n (coeff_beta, coeff_beta, coeff_alpha, coeff_alpha),\n (coeff_beta, coeff_beta, coeff_beta, coeff_beta),\n (coeff_alpha, coeff_alpha, coeff_beta, coeff_beta),\n ]\n matrices: List[Optional[np.ndarray]] = []\n for mat, coeffs in zip(self._matrices, coeff_list):\n if mat is None:\n matrices.append(None)\n continue\n matrices.append(np.einsum(self.EINSUM_AO_TO_MO, mat, *coeffs))\n\n return TwoBodyElectronicIntegrals(transform.final_basis, tuple(matrices))\n\n def to_spin(self) -> np.ndarray:\n \"\"\"Transforms the integrals into the special\n :class:`~qiskit_nature.properties.second_quantization.electronic.bases.ElectronicBasis.SO`\n basis.\n\n Returns:\n A single matrix containing the ``n-body`` integrals in the spin orbital basis.\n \"\"\"\n if self._basis == ElectronicBasis.SO:\n return self._matrices # type: ignore\n\n so_matrix = np.zeros([2 * s for s in self._matrices[0].shape])\n one_indices = (\n (0, 0, 0, 0), # alpha-alpha-spin\n (0, 1, 1, 0), # beta-alpha-spin\n (1, 1, 1, 1), # beta-beta-spin\n (1, 0, 0, 1), # alpha-beta-spin\n )\n alpha_beta_spin_idx = 3\n for idx, (ao_mat, one_idx) in enumerate(zip(self._matrices, one_indices)):\n if ao_mat is None:\n if idx == alpha_beta_spin_idx:\n ao_mat = self._matrices[0] if self._matrices[1] is None else self._matrices[1].T\n else:\n ao_mat = self._matrices[0]\n phys_matrix = np.einsum(self.EINSUM_CHEM_TO_PHYS, ao_mat)\n kron = np.zeros((2, 2, 2, 2))\n kron[one_idx] = 1\n so_matrix -= 0.5 * np.kron(kron, phys_matrix)\n\n return np.where(np.abs(so_matrix) > self._threshold, so_matrix, 0.0)\n\n def _calc_coeffs_with_ops(self, indices: Tuple[int, ...]) -> List[Tuple[int, str]]:\n return [(indices[0], \"+\"), (indices[2], \"+\"), (indices[3], \"-\"), (indices[1], \"-\")]\n\n def compose(\n self, other: ElectronicIntegrals, einsum_subscript: Optional[str] = None\n ) -> OneBodyElectronicIntegrals:\n # pylint: disable=line-too-long\n \"\"\"Composes these ``TwoBodyElectronicIntegrals`` with an instance of\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.OneBodyElectronicIntegrals`.\n\n This method requires an ``einsum_subscript`` subscript and produces a new instance of\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.OneBodyElectronicIntegrals`.\n\n Args:\n other: an instance of\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.OneBodyElectronicIntegrals`.\n einsum_subscript: an additional ``np.einsum`` subscript.\n\n Returns:\n The resulting\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.OneBodyElectronicIntegrals`.\n\n Raises:\n TypeError: if ``other`` is not an\n :class:`~qiskit_nature.properties.second_quantization.electronic.integrals.OneBodyElectronicIntegrals`\n instance.\n ValueError: if the bases of ``self`` and ``other`` do not match or if ``einsum_subscript`` is\n ``None``.\n NotImplementedError: if the basis of ``self`` is not\n :class:`~qiskit_nature.properties.second_quantization.electronic.bases.ElectronicBasis.AO`.\n \"\"\"\n if einsum_subscript is None:\n raise ValueError(\n \"TwoBodyElectronicIntegrals.compose requires an Einsum summation convention \"\n \"(`einsum_subscript`) in order to evaluate the composition! It may not be `None`.\"\n )\n\n if not isinstance(other, OneBodyElectronicIntegrals):\n raise TypeError(\n \"TwoBodyElectronicIntegrals.compose expected an `OneBodyElectronicIntegrals` object\"\n f\" and not one of type {type(other)}.\"\n )\n\n if self._basis != other._basis:\n raise ValueError(\n f\"The basis of self, {self._basis.value}, does not match the basis of other, \"\n f\"{other._basis}!\"\n )\n\n if self._basis != ElectronicBasis.AO:\n raise NotImplementedError(\n \"TwoBodyElectronicIntegrals.compose is not yet implemented for integrals in a basis\"\n \" other than the AO basis!\"\n )\n\n eri = self._matrices[0]\n\n alpha = np.einsum(einsum_subscript, eri, other._matrices[0])\n beta = None\n if other._matrices[1] is not None:\n beta = np.einsum(einsum_subscript, eri, other._matrices[1])\n\n return OneBodyElectronicIntegrals(self._basis, (alpha, beta), self._threshold)\n"
]
| [
[
"numpy.abs",
"numpy.einsum",
"numpy.kron",
"numpy.zeros"
]
]
|
julien-c/gradio | [
"5eaa4b1e8b8971d1973b596b3d53aaa99739a07c"
]
| [
"demo/main_note.py"
]
| [
"# Demo: (Audio) -> (Label)\n\nimport gradio as gr\nimport numpy as np\nfrom scipy.fftpack import fft\nimport matplotlib.pyplot as plt\nfrom math import log2, pow\n\nA4 = 440\nC0 = A4*pow(2, -4.75)\nname = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n \ndef get_pitch(freq):\n h = round(12*log2(freq/C0))\n n = h % 12\n return name[n]\n\ndef main_note(audio):\n rate, y = audio\n if len(y.shape) == 2:\n y = y.T[0]\n N = len(y)\n T = 1.0 / rate\n x = np.linspace(0.0, N*T, N)\n yf = fft(y)\n yf2 = 2.0/N * np.abs(yf[0:N//2])\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\n\n volume_per_pitch = {}\n total_volume = np.sum(yf2)\n for freq, volume in zip(xf, yf2):\n if freq == 0:\n continue\n pitch = get_pitch(freq)\n if pitch not in volume_per_pitch:\n volume_per_pitch[pitch] = 0\n volume_per_pitch[pitch] += 1.0 * volume / total_volume\n return volume_per_pitch\n\niface = gr.Interface(\n main_note, \n \"audio\", \n gr.outputs.Label(num_top_classes=4),\n examples=[\n [\"audio/recording1.wav\"],\n [\"audio/cantina.wav\"],\n ],\n interpretation=\"default\")\n\nif __name__ == \"__main__\":\n iface.launch()\n"
]
| [
[
"numpy.sum",
"numpy.linspace",
"scipy.fftpack.fft",
"numpy.abs"
]
]
|
zhyhan/AD3DMIL | [
"33abbf6810dce79cfedd18650e0e6e7b6d2e7122"
]
| [
"model/model_resnet_i3d.py"
]
| [
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2019-12-04 19:25 qiang.zhou <[email protected]>\n#\n# Distributed under terms of the MIT license.\n\n\"\"\" ResNet only. \"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom model.stem_helper import VideoModelStem\nfrom model.resnet_helper import ResStage\nfrom model.head_helper import ResNetBasicHead\n\nimport ops.weight_init_helper as init_helper \n\n#_MODEL_STAGE_DEPTH = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3)}\n_MODEL_STAGE_DEPTH = {50: (1, 1, 1, 1), 101: (3, 4, 23, 3)}\n\n_POOL1 = {\n \"c2d\": [[2, 1, 1]],\n \"c2d_nopool\": [[1, 1, 1]],\n \"i3d\": [[2, 1, 1]],\n \"i3d_nopool\": [[1, 1, 1]],\n \"slowonly\": [[1, 1, 1]],\n \"slowfast\": [[1, 1, 1], [1, 1, 1]],\n}\n\n# Basis of temporal kernel sizes for each of the stage.\n_TEMPORAL_KERNEL_BASIS = {\n \"c2d\": [\n [[1]], # conv1 temporal kernel.\n [[1]], # res2 temporal kernel.\n [[1]], # res3 temporal kernel.\n [[1]], # res4 temporal kernel.\n [[1]], # res5 temporal kernel.\n ],\n \"c2d_nopool\": [\n [[1]], # conv1 temporal kernel.\n [[1]], # res2 temporal kernel.\n [[1]], # res3 temporal kernel.\n [[1]], # res4 temporal kernel.\n [[1]], # res5 temporal kernel.\n ],\n \"i3d\": [\n [[5]], # conv1 temporal kernel.\n [[3]], # res2 temporal kernel.\n [[3, 1]], # res3 temporal kernel.\n [[3, 1]], # res4 temporal kernel.\n [[1, 3]], # res5 temporal kernel.\n ],\n \"i3d_nopool\": [\n [[5]], # conv1 temporal kernel.\n [[3]], # res2 temporal kernel.\n [[3, 1]], # res3 temporal kernel.\n [[3, 1]], # res4 temporal kernel.\n [[1, 3]], # res5 temporal kernel.\n ],\n \"slowonly\": [\n [[1]], # conv1 temporal kernel.\n [[1]], # res2 temporal kernel.\n [[1]], # res3 temporal kernel.\n [[3]], # res4 temporal kernel.\n [[3]], # res5 temporal kernel.\n ],\n \"slowfast\": [\n [[1], [5]], # conv1 temporal kernel for slow and fast pathway.\n [[1], [3]], # res2 temporal kernel for slow and fast pathway.\n [[1], [3]], # res3 temporal kernel for slow and fast pathway.\n [[3], [3]], # res4 temporal kernel for slow and fast pathway.\n [[3], [3]], # res5 temporal kernel for slow and fast pathway.\n ],\n}\n\n_POOL1 = {\n \"c2d\": [[2, 1, 1]],\n \"c2d_nopool\": [[1, 1, 1]],\n \"i3d\": [[2, 1, 1]],\n \"i3d_nopool\": [[1, 1, 1]],\n \"slowonly\": [[1, 1, 1]],\n \"slowfast\": [[1, 1, 1], [1, 1, 1]],\n}\n\n\nclass ENModel(nn.Module):\n \"\"\"\n It builds a ResNet like network backbone without lateral connection.\n Copied from https://github.com/facebookresearch/SlowFast/blob/master/slowfast/models/model_builder.py\n \"\"\"\n def __init__(self, arch=\"i3d\", \n resnet_depth=50, # 50/101\n input_channel=1,\n num_frames=-1,\n crop_h=-1,\n crop_w=-1,\n num_classes=2,\n ):\n super(ENModel, self).__init__()\n \n self.register_buffer('mean', torch.FloatTensor([0.272]).view(1,1,1,1,1))\n\n self.num_pathways = 1 # Because it is only slow, so it is 1\n assert arch in _POOL1.keys()\n pool_size = _POOL1[arch]\n assert len({len(pool_size), self.num_pathways}) == 1\n assert resnet_depth in _MODEL_STAGE_DEPTH.keys()\n (d2, d3, d4, d5) = _MODEL_STAGE_DEPTH[resnet_depth]\n\n # vanilla params\n num_groups = 1\n width_per_group = 16 # origin: 64\n dim_inner = num_groups * width_per_group\n\t\n temp_kernel = _TEMPORAL_KERNEL_BASIS[arch]\n\n self.s1 = VideoModelStem(\n dim_in=[input_channel],\n dim_out=[width_per_group],\n kernel=[temp_kernel[0][0] + [7, 7]],\n stride=[[1, 2, 2]],\n padding=[[temp_kernel[0][0][0] // 2, 3, 3]],\n )\n\n self.s2 = ResStage(\n dim_in=[width_per_group],\n dim_out=[width_per_group * 4],\n dim_inner=[dim_inner],\n temp_kernel_sizes=temp_kernel[1],\n stride=[1],\n num_blocks=[d2],\n num_groups=[num_groups],\n num_block_temp_kernel=[d2],\n nonlocal_inds=[[]],\n nonlocal_group=[1],\n instantiation='softmax',\n trans_func_name='bottleneck_transform',\n stride_1x1=False,\n inplace_relu=True,\n )\n\n for pathway in range(self.num_pathways):\n pool = nn.MaxPool3d(\n kernel_size=pool_size[pathway],\n stride=pool_size[pathway],\n padding=[0, 0, 0]\n )\n self.add_module(\"pathway{}_pool\".format(pathway), pool)\n\n self.s3 = ResStage(\n dim_in=[width_per_group * 4],\n dim_out=[width_per_group * 8],\n dim_inner=[dim_inner * 2],\n temp_kernel_sizes=temp_kernel[2],\n stride=[2],\n num_blocks=[d3],\n num_groups=[num_groups],\n num_block_temp_kernel=[d3],\n nonlocal_inds=[[]],\n nonlocal_group=[1],\n instantiation='softmax',\n trans_func_name='bottleneck_transform',\n stride_1x1=False,\n inplace_relu=True,\n )\n\n self.s4 = ResStage(\n dim_in=[width_per_group * 8],\n dim_out=[width_per_group * 16],\n dim_inner=[dim_inner * 4],\n temp_kernel_sizes=temp_kernel[3],\n stride=[2],\n num_blocks=[d4],\n num_groups=[num_groups],\n num_block_temp_kernel=[d4],\n nonlocal_inds=[[]],\n nonlocal_group=[1],\n instantiation='softmax',\n trans_func_name='bottleneck_transform',\n stride_1x1=False,\n inplace_relu=True,\n )\n\n self.s5 = ResStage(\n dim_in=[width_per_group * 16],\n dim_out=[width_per_group * 32],\n dim_inner=[dim_inner * 8],\n temp_kernel_sizes=temp_kernel[4],\n stride=[2],\n num_blocks=[d5],\n num_groups=[num_groups],\n num_block_temp_kernel=[d5],\n nonlocal_inds=[[]],\n nonlocal_group=[1],\n instantiation='softmax',\n trans_func_name='bottleneck_transform',\n stride_1x1=False,\n inplace_relu=True,\n )\n\n # Classifier\n self.head = ResNetBasicHead(\n dim_in=[width_per_group * 32],\n num_classes=num_classes,\n pool_size=[\n [\n num_frames // pool_size[0][0],\n crop_h // 32 // pool_size[0][1],\n crop_w // 32 // pool_size[0][2],\n ]\n ],\n dropout_rate=0.5,\n )\n\n # init weights\n init_helper.init_weights(\n self, fc_init_std=0.01, zero_init_final_bn=True \n )\n\n def forward(self, x):\n # for pathway in range(self.num_pathways):\n # x[pathway] = x[pathway] - self.mean\n x = self.s1(x)\n x = self.s2(x)\n for pathway in range(self.num_pathways):\n pool = getattr(self, \"pathway{}_pool\".format(pathway))\n x[pathway] = pool(x[pathway])\n x = self.s3(x)\n x = self.s4(x)\n #x = self.s5(x)\n #x = self.head(x)\n return x\n\n"
]
| [
[
"torch.nn.MaxPool3d",
"torch.FloatTensor"
]
]
|
msoeken/aqua | [
"af6a459621bcee90ed832a644ef9220644b84b03"
]
| [
"qiskit_aqua/translators/ising/tsp.py"
]
| [
"# -*- coding: utf-8 -*-\n\n# Copyright 2018 IBM.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\" Convert symmetric TSP instances into Pauli list\nDeal with TSPLIB format. It supports only EUC_2D edge weight type.\nSee https://wwwproxy.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/\nand http://elib.zib.de/pub/mp-testdata/tsp/tsplib/tsp/index.html\nDesign the tsp object `w` as a two-dimensional np.array\ne.g., w[i, j] = x means that the length of a edge between i and j is x\nNote that the weights are symmetric, i.e., w[j, i] = x always holds.\n\"\"\"\n\nimport logging\nfrom collections import OrderedDict, namedtuple\n\nimport numpy as np\nimport numpy.random as rand\nfrom qiskit.tools.qi.pauli import Pauli\n\nfrom qiskit_aqua import Operator\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"Instance data of TSP\"\"\"\nTspData = namedtuple('TspData', 'name dim coord w')\n\n\ndef calc_distance(coord, name='tmp'):\n assert coord.shape[1] == 2\n dim = coord.shape[0]\n w = np.zeros((dim, dim))\n for i in range(dim):\n for j in range(i + 1, dim):\n delta = coord[i] - coord[j]\n w[i, j] = np.rint(np.hypot(delta[0], delta[1]))\n w += w.T\n return TspData(name=name, dim=dim, coord=coord, w=w)\n\n\ndef random_tsp(n, low=0, high=100, savefile=None, seed=None, name='tmp'):\n \"\"\"Generate a random instance for TSP.\n\n Args:\n n (int): number of nodes.\n low (float): lower bound of coordinate.\n high (float): uppper bound of coordinate.\n savefile (str or None): name of file where to save graph.\n seed (int or None): random seed - if None, will not initialize.\n name (str): name of an instance\n\n Returns:\n TspData: instance data.\n\n \"\"\"\n assert n > 0\n if seed:\n rand.seed(seed)\n coord = rand.uniform(low, high, (n, 2))\n ins = calc_distance(coord, name)\n if savefile:\n with open(savefile, 'w') as outfile:\n outfile.write('NAME : {}\\n'.format(ins.name))\n outfile.write('COMMENT : random data\\n')\n outfile.write('TYPE : TSP\\n')\n outfile.write('DIMENSION : {}\\n'.format(ins.dim))\n outfile.write('EDGE_WEIGHT_TYPE : EUC_2D\\n')\n outfile.write('NODE_COORD_SECTION\\n')\n for i in range(ins.dim):\n x = ins.coord[i]\n outfile.write('{} {:.4f} {:.4f}\\n'.format(i + 1, x[0], x[1]))\n return ins\n\n\ndef parse_tsplib_format(filename):\n \"\"\"Read graph in TSPLIB format from file.\n\n Args:\n filename (str): name of the file.\n\n Returns:\n TspData: instance data.\n\n \"\"\"\n name = ''\n coord = None\n with open(filename) as infile:\n coord_section = False\n for line in infile:\n if line.startswith('NAME'):\n name = line.split(':')[1]\n name.strip()\n elif line.startswith('TYPE'):\n typ = line.split(':')[1]\n typ.strip()\n if typ != 'TSP':\n logger.warning('This supports only \"TSP\" type. Actual: {}'.format(typ))\n elif line.startswith('DIMENSION'):\n dim = int(line.split(':')[1])\n coord = np.zeros((dim, 2))\n elif line.startswith('EDGE_WEIGHT_TYPE'):\n typ = line.split(':')[1]\n typ.strip()\n if typ != 'EUC_2D':\n logger.warning('This supports only \"EUC_2D\" edge weight. Actual: {}'.format(typ))\n elif line.startswith('NODE_COORD_SECTION'):\n coord_section = True\n elif coord_section:\n v = line.split()\n index = int(v[0]) - 1\n coord[index][0] = float(v[1])\n coord[index][1] = float(v[2])\n return calc_distance(coord, name)\n\n\ndef get_tsp_qubitops(ins, penalty=1e5):\n \"\"\"Generate Hamiltonian for TSP of a graph.\n\n Args:\n ins (TspData) : TSP data including coordinates and distances.\n penalty (float) : Penalty coefficient for the constraints\n\n Returns:\n operator.Operator, float: operator for the Hamiltonian and a\n constant shift for the obj function.\n\n \"\"\"\n num_nodes = ins.dim\n num_qubits = num_nodes ** 2\n zero = np.zeros(num_qubits)\n pauli_list = []\n shift = 0\n for i in range(num_nodes):\n for j in range(num_nodes):\n if i == j:\n continue\n for p in range(num_nodes):\n q = (p + 1) % num_nodes\n shift += ins.w[i, j] / 4\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n pauli_list.append([-ins.w[i, j] / 4, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[j * num_nodes + q] = 1\n pauli_list.append([-ins.w[i, j] / 4, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n vp[j * num_nodes + q] = 1\n pauli_list.append([ins.w[i, j] / 4, Pauli(vp, zero)])\n\n for i in range(num_nodes):\n for p in range(num_nodes):\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n pauli_list.append([penalty, Pauli(vp, zero)])\n shift += -penalty\n\n for p in range(num_nodes):\n for i in range(num_nodes):\n for j in range(i):\n shift += penalty / 2\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n pauli_list.append([-penalty / 2, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[j * num_nodes + p] = 1\n pauli_list.append([-penalty / 2, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n vp[j * num_nodes + p] = 1\n pauli_list.append([penalty / 2, Pauli(vp, zero)])\n\n for i in range(num_nodes):\n for p in range(num_nodes):\n for q in range(p):\n shift += penalty / 2\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n pauli_list.append([-penalty / 2, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + q] = 1\n pauli_list.append([-penalty / 2, Pauli(vp, zero)])\n\n vp = np.zeros(num_qubits)\n vp[i * num_nodes + p] = 1\n vp[i * num_nodes + q] = 1\n pauli_list.append([penalty / 2, Pauli(vp, zero)])\n shift += 2 * penalty * num_nodes\n return Operator(paulis=pauli_list), shift\n\n\ndef tsp_value(z, w):\n \"\"\"Compute the TSP value of a solution.\n\n Args:\n z (list[int]): list of cities.\n w (numpy.ndarray): adjacency matrix.\n\n Returns:\n float: value of the cut.\n \"\"\"\n ret = 0.0\n for i in range(len(z) - 1):\n ret += w[z[i], z[i + 1]]\n ret += w[z[-1], z[0]]\n return ret\n\n\ndef tsp_feasible(x):\n \"\"\"Check whether a solution is feasible or not.\n\n Args:\n x (numpy.ndarray) : binary string as numpy array.\n\n Returns:\n bool: feasible or not.\n \"\"\"\n n = int(np.sqrt(len(x)))\n y = np.zeros((n, n))\n for i in range(n):\n for p in range(n):\n y[i, p] = x[i * n + p]\n for i in range(n):\n if sum(y[i, p] for p in range(n)) != 1:\n return False\n for p in range(n):\n if sum(y[i, p] for i in range(n)) != 1:\n return False\n return True\n\n\ndef get_tsp_solution(x):\n \"\"\"Get graph solution from binary string.\n\n Args:\n x (numpy.ndarray) : binary string as numpy array.\n\n Returns:\n list[int]: sequence of cities to traverse.\n \"\"\"\n n = int(np.sqrt(len(x)))\n z = []\n for p in range(n):\n for i in range(n):\n if x[i * n + p] >= 0.999:\n assert len(z) == p\n z.append(i)\n return z\n\n\ndef sample_most_likely(state_vector):\n \"\"\"Compute the most likely binary string from state vector.\n\n Args:\n state_vector (numpy.ndarray or dict): state vector or counts.\n\n Returns:\n numpy.ndarray: binary string as numpy.ndarray of ints.\n \"\"\"\n if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict):\n # get the binary string with the largest count\n binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0]\n x = np.asarray([int(y) for y in reversed(list(binary_string))])\n return x\n else:\n n = int(np.log2(state_vector.shape[0]))\n k = np.argmax(np.abs(state_vector))\n x = np.zeros(n)\n for i in range(n):\n x[i] = k % 2\n k >>= 1\n return x\n"
]
| [
[
"numpy.zeros",
"numpy.random.seed",
"numpy.random.uniform",
"numpy.hypot",
"numpy.abs",
"numpy.log2"
]
]
|
PVirie/aknowthai | [
"922ab4a7a5c799e67073d36a5366daac76beda43"
]
| [
"src/util.py"
]
| [
"import numpy as np\nimport math\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n\"\"\"We use PIL for representing images.\"\"\"\n\n\ndef image_to_numpy(img):\n return np.array(img) / 255.0\n\n\ndef rgb2gray(rgb):\n return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])\n\n\ndef image_to_FC1(img):\n return rgb2gray(image_to_numpy(img))\n\n\ndef image_to_invFC1(img):\n return 1.0 - rgb2gray(image_to_numpy(img))\n\n\ndef numpy_to_image(mat):\n return Image.fromarray(np.uint8(mat * 255))\n\n\ndef plot_1D(mat):\n plt.plot(xrange(mat.shape[0]), mat, 'ro')\n plt.ion()\n plt.show()\n\n\ndef cvtColorGrey2RGB(mat):\n last_dim = len(mat.shape)\n return np.repeat(np.expand_dims(mat, last_dim), 3, last_dim)\n\n\ndef make_tile(mat, rows, cols, flip):\n b = mat.shape[0]\n r = mat.shape[2] if flip else mat.shape[1]\n c = mat.shape[1] if flip else mat.shape[2]\n canvas = np.zeros((rows, cols, 3 if len(mat.shape) > 3 else 1), dtype=mat.dtype)\n step = int(max(1, math.floor(b * (r * c) / (rows * cols))))\n i = 0\n for x in xrange(int(math.floor(rows / r))):\n for y in xrange(int(math.floor(cols / c))):\n canvas[(x * r):((x + 1) * r), (y * c):((y + 1) * c), :] = np.transpose(mat[i, ...], (1, 0, 2)) if flip else mat[i, ...]\n i = (i + step) % b\n\n return canvas\n\n\ndef save_txt(mat, name):\n np.savetxt(name, mat, delimiter=\",\", fmt=\"%.2e\")\n"
]
| [
[
"matplotlib.pyplot.ion",
"numpy.dot",
"numpy.savetxt",
"numpy.array",
"numpy.uint8",
"numpy.transpose",
"matplotlib.pyplot.show",
"numpy.expand_dims"
]
]
|
PredOptwithSoftConstraint/PredOptwithSoftConstraint | [
"c0ec41a8c2c48034851cf04cd848013ceba1dd40"
]
| [
"resource_provisioning/calc.py"
]
| [
"import numpy as np\nfrom config import *\nimport gurobipy\nfrom scipy.optimize import minimize, LinearConstraint\nfrom util import *\nfrom torch.optim import SGD\nfrom torch.autograd import Variable\nimport gurobipy as gp\nfrom gurobipy import GRB\nimport torch.nn as nn\nimport cvxpy as cp\nfrom cvxpylayers.torch import CvxpyLayer\n\n\nclass quad_surro_tensor(torch.autograd.Function): # with gradient.\n @staticmethod\n def forward(ctx, *args):\n Ctensor, Ctrue, inver, diaga, alpha, C, d, delta, gamma = args\n # This matrix C is from Ctensor.\n # Ctrue is merged from label.\n # note: this delta and diaga is not determined from predicted C, but from real C!\n inver, diaga, alpha, C, d, delta, gamma = torch.from_numpy(inver).double().to(device), diaga.double().to(device), torch.from_numpy(alpha).double().to(device), torch.from_numpy(C).double().to(device), torch.from_numpy(d).double().to(device), delta.double().to(device), gamma.double().to(device)\n Ctrue = torch.from_numpy(Ctrue).double().to(device)\n # x = (C^T * delta * diaga * C)^(-1) * (theta + C^T * delta * diaga * d - C^T * (1/4k * delta + gamma) * alpha)\n x = inver @ (C.t() @ delta @ diaga @ d - C.t() @ (1.0 / (4 * QUAD_SOFT_K) * delta + gamma) @ alpha)\n z = Ctrue @ x - d\n result = - alpha.t() @ (delta / 2.0 @ ((z + 1.0 / (4.0 * QUAD_SOFT_K)) ** 2) + gamma @ z)\n ctx.save_for_backward(Ctensor, Ctrue, inver, diaga, alpha, C, d, delta, gamma, x)\n return result\n\n @staticmethod\n def backward(ctx, *grad_output):\n t1 = time.time()\n torch.set_printoptions(precision=8) # for debugging.\n Ctensor, Ctrue, inver, diaga, alpha, C, d, delta, gamma, x = ctx.saved_tensors\n z_true = Ctrue @ x - d\n df_dC = torch.zeros(C.shape)\n # dx_dC = torch.zeros(alpha1.shape[0], C.shape[0], C.shape[1])\n eta = delta @ diaga @ d - (delta / (4 * QUAD_SOFT_K) + gamma) @ alpha\n beta = C.t() @ delta @ diaga @ d - C.t() @ (delta / (4 * QUAD_SOFT_K) + gamma) @ alpha\n assert C.shape[0] == eta.shape[0], \"Shape Mismatch!\"\n\n true_delta, true_gamma = np.zeros_like(delta), np.zeros_like(gamma)\n for i in range(delta.shape[0]):\n if z_true[i] >= 1 / (4 * QUAD_SOFT_K):\n true_gamma[i, i] = 1\n elif z_true[i] >= -1 / (4 * QUAD_SOFT_K):\n true_delta[i, i] = 2 * QUAD_SOFT_K\n\n df_dx = - Ctrue.t() @ true_delta @ diaga @ z_true - Ctrue.t() @ (true_delta / (4 * QUAD_SOFT_K) + true_gamma) @ alpha\n\n idx_linear_B, idx_quad_B = [], []\n for i in range(d.shape[0]):\n if z_true[i] >= 1 / (4 * QUAD_SOFT_K):\n idx_linear_B.append(i)\n elif z_true[i] >= - 1 / (4 * QUAD_SOFT_K):\n idx_quad_B.append(i)\n # print(\"idx_linear_B:\", idx_linear_B)\n # print(\"idx_quad_B:\", idx_quad_B)\n # df_dx = -Ctrue.t() @ delta_true @ diaga @ z_true - Ctrue.t() @ (delta_true / (4 * QUAD_SOFT_K) + gamma_true) @ alpha\n\n gamma1, gamma2, gamma3 = delta @ diaga @ C @ inver @ beta, inver @ C.t() @ delta @ diaga, inver @ beta\n S1 = torch.cat([inver.unsqueeze(-1) for k in range(C.shape[0])], dim=2) # i * l * k\n S2 = torch.cat([gamma2.unsqueeze(-1) for l in range(C.shape[1])], dim=2) # i * k * l\n\n for k in range(C.shape[0]):\n S1[:, :, k] *= (eta[k] - gamma1[k, 0])\n for l in range(C.shape[1]):\n S2[:, :, l] *= gamma3[l, 0]\n dx_dC = S1.permute(0, 2, 1) - S2\n \"\"\"\n A slower version\n dx_dC = torch.zeros(x.shape[0], C.shape[0], C.shape[1])\n for i in range(x.shape[0]): # 20\n for k in range(C.shape[0]): # 60\n for l in range(C.shape[1]): # 20\n dx_dC[i, k, l] = -(gamma1[k, 0] * inver[i, l] + gamma3[l, 0] * gamma2[i, k]) + inver[i, l] * eta[k]\n # = (eta[k] - gamma1[k, 0]) * inver[i, l] - gamma3[l, 0] * gamma2[i, k]\n \"\"\"\n for k in range(C.shape[0]):\n df_dC[k, :] = df_dx.t() @ dx_dC[:, k, :].view(dx_dC.shape[0], dx_dC.shape[2])\n # df_dx.t(): 1 * 20\n # dx_dc: 20 * 60 * 20\n # df_dc: (1*) 60 * 20 df_dc[k, :] = 1 * 20 df_dx.t(): 1 * 20 dx_dC[:, k, :] = 20 * 20\n grd = grad_output[0] * df_dC\n return grd[:Ctensor.shape[0], :] - grd[Ctensor.shape[0]:2*Ctensor.shape[0], :], None, None, None, None, None, None, None, None, None\n\nbuffer_C, buffer_d, buffer_alpha = None, None, None\n\ndef getopt(alpha1, alpha2, A0, b0, C0, d0): # get optimal true value.\n # note: theta is actually alpha1 and alpha0 is actually alpha2.\n global buffer_C, buffer_d, buffer_alpha\n x0 = np.zeros(A0.shape[1]) # 并不是起始点的问题。\n # TODO: optimization and cut duplicated code.\n # C0 is prediction and will change!\n C, d, alpha = merge_constraints(A0, b0, C0, d0, alpha1, alpha2)\n ev = gp.Env(empty=True)\n ev.setParam('OutputFlag', 0)\n ev.start()\n m = gp.Model(\"matrix1\", env=ev)\n # solve twice: first solve the naked problem, then solve it again to get the surrogate optimal.\n x = m.addMVar(shape=C0.shape[1], vtype=GRB.CONTINUOUS, name='x')\n z = m.addMVar(shape=d0.shape[0], vtype=GRB.CONTINUOUS, name='z')\n w = m.addMVar(shape=d0.shape[0], vtype=GRB.CONTINUOUS, name='w')\n m.setObjective(-alpha1.T @ z - alpha2.T @ w, GRB.MAXIMIZE)\n m.addConstr(z >= 0, name=\"c1\")\n m.addConstr(z >= C0 @ x - d0.squeeze(), name='c2')\n m.addConstr(w >= 0, name=\"c1\")\n m.addConstr(w >= d0.squeeze() - C0 @ x, name='c3')\n m.addConstr(x >= 0, name=\"c3\")\n m.addConstr(A0 @ x <= b0.squeeze(), name='c4')\n m.optimize()\n naked_x = x.getAttr('x')\n return getval_twoalpha(naked_x, alpha1, alpha2, A0, b0, C0, d0), naked_x\n\ndef resetbuffer():\n global buffer_C, buffer_d, buffer_alpha\n buffer_C, buffer_d, buffer_alpha = None, None, None\n\ndef getopt_surro(ground_truth_C, Ctensor, alpha1, alpha2, A0, b0, d0, nograd=False, backlog=None): # the surrogate function\n global buffer_C, buffer_d, buffer_alpha\n C0 = Ctensor.cpu().detach().numpy()\n C, d, alpha_merged = merge_constraints(A0, b0, C0, d0, alpha1, alpha2)\n Ctrue, _, __ = merge_constraints(A0, b0, ground_truth_C, d0, alpha1, alpha2)\n # print(\"alpha1:\",alpha1.shape, \"alpha2:\",alpha2.shape, \"A0:\",A0.shape, \"b0:\", b0.shape, \"C0:\", C0.shape,\"d0:\", d0.shape)\n _, x = getopt(alpha1, alpha2, A0, b0, C0, d0)\n # print(_)\n idx_none, idx_quad, idx_linear = [], [], []\n soft_constr = np.matmul(C, x.reshape(-1, 1)) - d\n for i in range(C.shape[0]):\n if -1.0 / (4 * QUAD_SOFT_K) < soft_constr[i] and soft_constr[i] <= 1.0 / (4 * QUAD_SOFT_K):\n idx_quad.append(i)\n elif soft_constr[i] > 1.0 / (4 * QUAD_SOFT_K):\n idx_linear.append(i)\n else: idx_none.append(i)\n # print(\"idx_quad_A:\", idx_quad, \"idx_quad_linear:\", idx_linear)\n L = d.shape[0]\n delta, gamma = torch.zeros((L, L)), torch.zeros((L, L))\n diagz = torch.zeros((L, L))\n diaga = torch.zeros((L, L))\n for i in idx_quad: delta[i, i] = 2 * QUAD_SOFT_K\n for i in idx_linear: gamma[i, i] = 1\n for i in range(L): diagz[i, i], diaga[i, i] = soft_constr[i, 0], alpha_merged[i, 0]\n try:\n inver = np.linalg.inv(np.matmul(np.matmul(C.T, np.matmul(delta.cpu().numpy(), diaga.cpu().numpy())), C))\n except np.linalg.LinAlgError:\n # print('LinAlgError!', delta, diaga)\n exit(0)\n\n grd = None if nograd else quad_surro_tensor.apply(Ctensor, Ctrue, inver, diaga, alpha_merged, C, d, delta, gamma)\n # C is the concatenation of Ctensor and others.\n val = getval_twoalpha(x, alpha1, alpha2, A0, b0, C0, d0)\n\n return val, grd # grd is the objective value with real theta, while val is the objective value with predicted theta.\n\ndef getval(x, alpha0, A0, b0, C0, d0):\n return -alpha0.T.dot(np.maximum(np.matmul(C0, x.reshape(-1, 1)) - d0, 0))\n\ndef getval_twoalpha(x, alpha0, alpha1, A0, b0, C0, d0):\n return -(alpha0.T.dot(np.maximum(np.matmul(C0, x.reshape(-1, 1)) - d0, 0)) + alpha1.T.dot(np.maximum(d0 - np.matmul(C0, x.reshape(-1, 1)), 0)))\n"
]
| [
[
"numpy.zeros_like",
"numpy.zeros"
]
]
|
KingShark1/pytorch_RVAE | [
"953b458bca0fe608bccebf5dba6655f37cbdbeba"
]
| [
"train.py"
]
| [
"import argparse\nimport os\n\nimport numpy as np\nimport torch as t\nfrom torch.optim import Adam\n\nfrom utils.batch_loader import BatchLoader\nfrom utils.parameters import Parameters\nfrom model.rvae import RVAE\n\nif __name__ == \"__main__\":\n\n if not os.path.exists('data/word_embeddings.npy'):\n raise FileNotFoundError(\"word embeddings file was't found\")\n\n parser = argparse.ArgumentParser(description='RVAE')\n parser.add_argument('--num-iterations', type=int, default=120000, metavar='NI',\n help='num iterations (default: 120000)')\n parser.add_argument('--batch-size', type=int, default=32, metavar='BS',\n help='batch size (default: 32)')\n parser.add_argument('--use-cuda', type=bool, default=True, metavar='CUDA',\n help='use cuda (default: True)')\n parser.add_argument('--learning-rate', type=float, default=0.00005, metavar='LR',\n help='learning rate (default: 0.00005)')\n parser.add_argument('--dropout', type=float, default=0.3, metavar='DR',\n help='dropout (default: 0.3)')\n parser.add_argument('--use-trained', type=bool, default=False, metavar='UT',\n help='load pretrained model (default: False)')\n parser.add_argument('--ce-result', default='', metavar='CE',\n help='ce result path (default: '')')\n parser.add_argument('--kld-result', default='', metavar='KLD',\n help='ce result path (default: '')')\n\n args = parser.parse_args()\n\n batch_loader = BatchLoader('')\n parameters = Parameters(batch_loader.max_word_len,\n batch_loader.max_seq_len,\n batch_loader.words_vocab_size,\n batch_loader.chars_vocab_size)\n\n rvae = RVAE(parameters)\n if args.use_trained:\n rvae.load_state_dict(t.load('trained_RVAE'))\n if args.use_cuda:\n rvae = rvae.cuda()\n\n optimizer = Adam(rvae.learnable_parameters(), args.learning_rate)\n\n train_step = rvae.trainer(optimizer, batch_loader)\n validate = rvae.validater(batch_loader)\n\n ce_result = []\n kld_result = []\n\n for iteration in range(args.num_iterations):\n\n cross_entropy, kld, coef = train_step(iteration, args.batch_size, args.use_cuda, args.dropout)\n\n if iteration % 5 == 0:\n print('\\n')\n print('------------TRAIN-------------')\n print('----------ITERATION-----------')\n print(iteration)\n print('--------CROSS-ENTROPY---------')\n print(cross_entropy.data.cpu().numpy()[0])\n print('-------------KLD--------------')\n print(kld.data.cpu().numpy()[0])\n print('-----------KLD-coef-----------')\n print(coef)\n print('------------------------------')\n\n if iteration % 10 == 0:\n cross_entropy, kld = validate(args.batch_size, args.use_cuda)\n\n cross_entropy = cross_entropy.data.cpu().numpy()[0]\n kld = kld.data.cpu().numpy()[0]\n\n print('\\n')\n print('------------VALID-------------')\n print('--------CROSS-ENTROPY---------')\n print(cross_entropy)\n print('-------------KLD--------------')\n print(kld)\n print('------------------------------')\n\n ce_result += [cross_entropy]\n kld_result += [kld]\n\n if iteration % 20 == 0:\n seed = np.random.normal(size=[1, parameters.latent_variable_size])\n\n sample = rvae.sample(batch_loader, 50, seed, args.use_cuda)\n\n print('\\n')\n print('------------SAMPLE------------')\n print('------------------------------')\n print(sample)\n print('------------------------------')\n\n t.save(rvae.state_dict(), 'trained_RVAE')\n\n np.save('ce_result_{}.npy'.format(args.ce_result), np.array(ce_result))\n np.save('kld_result_npy_{}'.format(args.kld_result), np.array(kld_result))\n"
]
| [
[
"numpy.random.normal",
"numpy.array",
"torch.load"
]
]
|
corbt/city-weather | [
"e188e2655d3e641ec9551af2ec799f47f25fab50"
]
| [
"cluster.py"
]
| [
"import numpy as np\nimport pandas as pd\nimport re\nfrom sklearn.cluster import MiniBatchKMeans\n\ndef reverse_south(dataset):\n # The following code reverses the year for the southern hemisphere.\n # This allows northern and southern climates to be compared\n cols = dataset.columns\n first_months = [col for col in cols if re.match('[1-6]_', col)]\n last_months = [col for col in cols if re.match('\\d+_', col) and col not in first_months]\n\n south_data = dataset[dataset.lat < 0]\n first_months_data = south_data[first_months]\n south_data[first_months] = south_data[last_months]\n south_data[last_months] = first_months_data\n\n dataset.loc[south_data.index] = south_data\n return dataset\n\n\ndata = pd.read_csv(\"data/csv/data.csv\").set_index('id')\n\ndata = reverse_south(data)\nprediction_data = data.drop(['lat','long','name','country'],axis=1).fillna(20)\n\nd = MiniBatchKMeans(n_clusters=10).fit(prediction_data)\n\ndata['category'] = d.predict(prediction_data)\n\ndata = reverse_south(data)\n\ndata.to_csv(\"data/csv/categories.csv\")"
]
| [
[
"pandas.read_csv",
"sklearn.cluster.MiniBatchKMeans"
]
]
|
LuyaoXu/text | [
"1a054e2b2babeb7d95c2eb463dbc2db221a21f16"
]
| [
"tensorflow_text/python/ops/wordpiece_tokenizer.py"
]
| [
"# coding=utf-8\n# Copyright 2020 TF.Text Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Ops to tokenize words into subwords.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.eager import monitoring\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged.ragged_tensor import RaggedTensor\nfrom tensorflow_text.python.ops.tokenization import TokenizerWithOffsets\n\n# pylint: disable=g-bad-import-order\nfrom tensorflow.python.framework import load_library\nfrom tensorflow.python.platform import resource_loader\ngen_wordpiece_tokenizer = load_library.load_op_library(resource_loader.get_path_to_datafile('_wordpiece_tokenizer.so'))\n\n_tf_text_wordpiece_tokenizer_op_create_counter = monitoring.Counter(\n '/nlx/api/python/wordpiece_tokenizer_create_counter',\n 'Counter for number of WordpieceTokenizers created in Python.')\n\n\nclass WordpieceTokenizer(TokenizerWithOffsets):\n \"\"\"Tokenizes a tensor of UTF-8 string tokens into subword pieces.\"\"\"\n\n def __init__(self,\n vocab_lookup_table,\n suffix_indicator='##',\n max_bytes_per_word=100,\n max_chars_per_token=None,\n token_out_type=dtypes.int64,\n unknown_token='[UNK]',\n split_unknown_characters=False):\n \"\"\"Initializes the WordpieceTokenizer.\n\n Args:\n vocab_lookup_table: A lookup table implementing the LookupInterface\n containing the vocabulary of subwords.\n suffix_indicator: (optional) The characters prepended to a wordpiece to\n indicate that it is a suffix to another subword. Default is '##'.\n max_bytes_per_word: (optional) Max size of input token. Default is 100.\n max_chars_per_token: (optional) Max size of subwords, excluding suffix\n indicator. If known, providing this improves the efficiency of decoding\n long words.\n token_out_type: (optional) The type of the token to return. This can be\n `tf.int64` IDs, or `tf.string` subwords. The default is `tf.int64`.\n unknown_token: (optional) The value to use when an unknown token is found.\n Default is \"[UNK]\". If this is set to a string, and `token_out_type` is\n `tf.int64`, the `vocab_lookup_table` is used to convert the\n `unknown_token` to an integer. If this is set to `None`,\n out-of-vocabulary tokens are left as is.\n split_unknown_characters: (optional) Whether to split out single unknown\n characters as subtokens. If False (default), words containing unknown\n characters will be treated as single unknown tokens.\n \"\"\"\n super(WordpieceTokenizer, self).__init__()\n _tf_text_wordpiece_tokenizer_op_create_counter.get_cell().increase_by(1)\n self._vocab_lookup_table = vocab_lookup_table\n self._suffix_indicator = suffix_indicator\n self._max_bytes_per_word = max_bytes_per_word\n self._max_chars_per_token = (\n 0 if max_chars_per_token is None\n else max_chars_per_token)\n self._token_out_type = token_out_type\n self._unknown_token = unknown_token if unknown_token else '[UNK]'\n self._use_unknown_token = True if unknown_token else False\n self._split_unknown_characters = split_unknown_characters\n\n def tokenize(self, input): # pylint: disable=redefined-builtin\n \"\"\"Tokenizes a tensor of UTF-8 string tokens further into subword tokens.\n\n ### Example:\n ```python\n >>> tokens = [[\"they're\", \"the\", \"greatest\"]],\n >>> tokenizer = WordpieceTokenizer(vocab, token_out_type=tf.string)\n >>> tokenizer.tokenize(tokens)\n [[['they', \"##'\", '##re'], ['the'], ['great', '##est']]]\n ```\n\n Args:\n input: An N-dimensional `Tensor` or `RaggedTensor` of UTF-8 strings.\n\n Returns:\n A `RaggedTensor` of tokens where `tokens[i1...iN, j]` is the string\n contents (or ID in the vocab_lookup_table representing that string)\n of the `jth` token in `input[i1...iN]`\n \"\"\"\n subword, _, _ = self.tokenize_with_offsets(input)\n return subword\n\n def tokenize_with_offsets(self, input): # pylint: disable=redefined-builtin\n \"\"\"Tokenizes a tensor of UTF-8 string tokens further into subword tokens.\n\n ### Example:\n\n ```python\n >>> tokens = [[\"they're\", \"the\", \"greatest\"]],\n >>> tokenizer = WordpieceTokenizer(vocab, token_out_type=tf.string)\n >>> result = tokenizer.tokenize_with_offsets(tokens)\n >>> result[0].to_list() # subwords\n [[['they', \"##'\", '##re'], ['the'], ['great', '##est']]]\n >>> result[1].to_list() # offset starts\n [[[0, 4, 5], [0], [0, 5]]]\n >>> result[2].to_list() # offset limits\n [[[4, 5, 7], [3], [5, 8]]]\n ```\n\n Args:\n input: An N-dimensional `Tensor` or `RaggedTensor` of UTF-8 strings.\n\n Returns:\n A tuple `(tokens, start_offsets, limit_offsets)` where:\n\n * `tokens[i1...iN, j]` is a `RaggedTensor` of the string contents (or ID\n in the vocab_lookup_table representing that string) of the `jth` token\n in `input[i1...iN]`.\n * `start_offsets[i1...iN, j]` is a `RaggedTensor` of the byte offsets\n for the start of the `jth` token in `input[i1...iN]`.\n * `limit_offsets[i1...iN, j]` is a `RaggedTensor` of the byte offsets\n for the end of the `jth` token in `input[i`...iN]`.\n \"\"\"\n name = None\n if not isinstance(self._vocab_lookup_table, lookup_ops.LookupInterface):\n raise TypeError('vocab_lookup_table must be a LookupInterface')\n with ops.name_scope(\n name, 'WordpieceTokenizeWithOffsets',\n [input, self._vocab_lookup_table, self._suffix_indicator]):\n # Check that the types are expected and the ragged rank is appropriate.\n tokens = ragged_tensor.convert_to_tensor_or_ragged_tensor(input)\n rank = tokens.shape.ndims\n if rank is None:\n raise ValueError('input must have a known rank.')\n\n if rank == 0:\n wordpieces, starts, limits = self.tokenize_with_offsets(\n array_ops.stack([tokens]))\n return wordpieces.values, starts.values, limits.values\n\n elif rank > 1:\n if not ragged_tensor.is_ragged(tokens):\n tokens = ragged_tensor.RaggedTensor.from_tensor(\n tokens, ragged_rank=rank - 1)\n wordpieces, starts, limits = self.tokenize_with_offsets(\n tokens.flat_values)\n wordpieces = wordpieces.with_row_splits_dtype(tokens.row_splits.dtype)\n starts = starts.with_row_splits_dtype(tokens.row_splits.dtype)\n limits = limits.with_row_splits_dtype(tokens.row_splits.dtype)\n return (tokens.with_flat_values(wordpieces),\n tokens.with_flat_values(starts),\n tokens.with_flat_values(limits))\n\n if compat.forward_compatible(2019, 8, 25):\n kwargs = dict(output_row_partition_type='row_splits')\n from_row_partition = RaggedTensor.from_row_splits\n else:\n kwargs = {}\n from_row_partition = RaggedTensor.from_row_lengths\n\n # Tokenize the tokens into subwords\n values, row_splits, starts, limits = (\n gen_wordpiece_tokenizer.wordpiece_tokenize_with_offsets(\n input_values=tokens,\n vocab_lookup_table=self._vocab_lookup_table.resource_handle,\n suffix_indicator=self._suffix_indicator,\n use_unknown_token=self._use_unknown_token,\n max_bytes_per_word=self._max_bytes_per_word,\n max_chars_per_token=self._max_chars_per_token,\n unknown_token=self._unknown_token,\n split_unknown_characters=self._split_unknown_characters,\n **kwargs))\n\n # If ids are desired, look them up in the vocab table. Otherwise just\n # return the string values.\n if self._token_out_type == dtypes.int64:\n values = self._vocab_lookup_table.lookup(values)\n\n wordpieces = from_row_partition(values, row_splits, validate=False)\n starts = from_row_partition(starts, row_splits, validate=False)\n limits = from_row_partition(limits, row_splits, validate=False)\n\n return wordpieces, starts, limits\n"
]
| [
[
"tensorflow.python.compat.compat.forward_compatible",
"tensorflow.python.ops.ragged.ragged_tensor.is_ragged",
"tensorflow.python.eager.monitoring.Counter",
"tensorflow.python.ops.ragged.ragged_tensor.convert_to_tensor_or_ragged_tensor",
"tensorflow.python.ops.array_ops.stack",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_tensor",
"tensorflow.python.platform.resource_loader.get_path_to_datafile"
]
]
|
fishmingyu/cogdl | [
"f6f33c666feb874f13eb43a8adc5db7c918778ec",
"f6f33c666feb874f13eb43a8adc5db7c918778ec"
]
| [
"examples/custom_dataset.py",
"cogdl/datasets/han_data.py"
]
| [
"import torch\n\nfrom cogdl.experiments import experiment\nfrom cogdl.data import Graph\nfrom cogdl.datasets import NodeDataset, generate_random_graph\n\n\nclass MyNodeClassificationDataset(NodeDataset):\n def __init__(self, path=\"data.pt\"):\n super(MyNodeClassificationDataset, self).__init__(path)\n\n def process(self):\n num_nodes, num_edges, feat_dim = 100, 300, 30\n\n # load or generate your dataset\n edge_index = torch.randint(0, num_nodes, (2, num_edges))\n x = torch.randn(num_nodes, feat_dim)\n y = torch.randint(0, 2, (num_nodes,))\n\n # set train/val/test mask in node_classification task\n train_mask = torch.zeros(num_nodes).bool()\n train_mask[0 : int(0.3 * num_nodes)] = True\n val_mask = torch.zeros(num_nodes).bool()\n val_mask[int(0.3 * num_nodes) : int(0.7 * num_nodes)] = True\n test_mask = torch.zeros(num_nodes).bool()\n test_mask[int(0.7 * num_nodes) :] = True\n data = Graph(x=x, edge_index=edge_index, y=y, train_mask=train_mask, val_mask=val_mask, test_mask=test_mask)\n return data\n\n\nif __name__ == \"__main__\":\n # Train customized dataset via defining a new class\n dataset = MyNodeClassificationDataset()\n experiment(dataset=dataset, model=\"gcn\")\n\n # Train customized dataset via feeding the graph data to NodeDataset\n data = generate_random_graph(num_nodes=100, num_edges=300, num_feats=30)\n dataset = NodeDataset(data=data)\n experiment(dataset=dataset, model=\"gcn\")\n",
"import os.path as osp\n\nimport numpy as np\nimport scipy.io as sio\nimport torch\nfrom cogdl.data import Graph, Dataset\nfrom cogdl.utils import download_url, untar\n\n\ndef sample_mask(idx, length):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(length)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\n\nclass HANDataset(Dataset):\n r\"\"\"The network datasets \"ACM\", \"DBLP\" and \"IMDB\" from the\n `\"Heterogeneous Graph Attention Network\"\n <https://arxiv.org/abs/1903.07293>`_ paper.\n\n Args:\n root (string): Root directory where the dataset should be saved.\n name (string): The name of the dataset (:obj:`\"han-acm\"`,\n :obj:`\"han-dblp\"`, :obj:`\"han-imdb\"`).\n \"\"\"\n\n def __init__(self, root, name):\n self.name = name\n self.url = f\"https://github.com/cenyk1230/han-data/blob/master/{name}.zip?raw=true\"\n super(HANDataset, self).__init__(root)\n self.data = torch.load(self.processed_paths[0])\n self.num_edge = len(self.data.adj)\n self.num_nodes = self.data.x.shape[0]\n\n @property\n def raw_file_names(self):\n names = [\"data.mat\"]\n return names\n\n @property\n def processed_file_names(self):\n return [\"data.pt\"]\n\n @property\n def num_classes(self):\n return torch.max(self.data.train_target).item() + 1\n\n def read_gtn_data(self, folder):\n data = sio.loadmat(osp.join(folder, \"data.mat\"))\n if self.name == \"han-acm\" or self.name == \"han-imdb\":\n truelabels, truefeatures = data[\"label\"], data[\"feature\"].astype(float)\n elif self.name == \"han-dblp\":\n truelabels, truefeatures = data[\"label\"], data[\"features\"].astype(float)\n num_nodes = truefeatures.shape[0]\n if self.name == \"han-acm\":\n rownetworks = [data[\"PAP\"] - np.eye(num_nodes), data[\"PLP\"] - np.eye(num_nodes)]\n elif self.name == \"han-dblp\":\n rownetworks = [\n data[\"net_APA\"] - np.eye(num_nodes),\n data[\"net_APCPA\"] - np.eye(num_nodes),\n data[\"net_APTPA\"] - np.eye(num_nodes),\n ]\n elif self.name == \"han-imdb\":\n rownetworks = [\n data[\"MAM\"] - np.eye(num_nodes),\n data[\"MDM\"] - np.eye(num_nodes),\n data[\"MYM\"] - np.eye(num_nodes),\n ]\n\n y = truelabels\n train_idx = data[\"train_idx\"]\n val_idx = data[\"val_idx\"]\n test_idx = data[\"test_idx\"]\n\n train_mask = sample_mask(train_idx, y.shape[0])\n val_mask = sample_mask(val_idx, y.shape[0])\n test_mask = sample_mask(test_idx, y.shape[0])\n\n y_train = np.argmax(y[train_mask, :], axis=1)\n y_val = np.argmax(y[val_mask, :], axis=1)\n y_test = np.argmax(y[test_mask, :], axis=1)\n\n data = Graph()\n A = []\n for i, edge in enumerate(rownetworks):\n edge_tmp = torch.from_numpy(np.vstack((edge.nonzero()[0], edge.nonzero()[1]))).type(torch.LongTensor)\n value_tmp = torch.ones(edge_tmp.shape[1]).type(torch.FloatTensor)\n A.append((edge_tmp, value_tmp))\n edge_tmp = torch.stack((torch.arange(0, num_nodes), torch.arange(0, num_nodes))).type(torch.LongTensor)\n value_tmp = torch.ones(num_nodes).type(torch.FloatTensor)\n A.append((edge_tmp, value_tmp))\n data.adj = A\n\n data.x = torch.from_numpy(truefeatures).type(torch.FloatTensor)\n\n data.train_node = torch.from_numpy(train_idx[0]).type(torch.LongTensor)\n data.train_target = torch.from_numpy(y_train).type(torch.LongTensor)\n data.valid_node = torch.from_numpy(val_idx[0]).type(torch.LongTensor)\n data.valid_target = torch.from_numpy(y_val).type(torch.LongTensor)\n data.test_node = torch.from_numpy(test_idx[0]).type(torch.LongTensor)\n data.test_target = torch.from_numpy(y_test).type(torch.LongTensor)\n\n y = np.zeros((num_nodes), dtype=int)\n x_index = torch.cat((data.train_node, data.valid_node, data.test_node))\n y_index = torch.cat((data.train_target, data.valid_target, data.test_target))\n y[x_index.numpy()] = y_index.numpy()\n data.y = torch.from_numpy(y)\n\n self.data = data\n\n def get(self, idx):\n assert idx == 0\n return self.data\n\n def apply_to_device(self, device):\n self.data.x = self.data.x.to(device)\n self.data.y = self.data.y.to(device)\n\n self.data.train_node = self.data.train_node.to(device)\n self.data.valid_node = self.data.valid_node.to(device)\n self.data.test_node = self.data.test_node.to(device)\n\n self.data.train_target = self.data.train_target.to(device)\n self.data.valid_target = self.data.valid_target.to(device)\n self.data.test_target = self.data.test_target.to(device)\n\n new_adj = []\n for (t1, t2) in self.data.adj:\n new_adj.append((t1.to(device), t2.to(device)))\n self.data.adj = new_adj\n\n def download(self):\n download_url(self.url, self.raw_dir, name=self.name + \".zip\")\n untar(self.raw_dir, self.name + \".zip\")\n\n def process(self):\n self.read_gtn_data(self.raw_dir)\n torch.save(self.data, self.processed_paths[0])\n\n def __repr__(self):\n return \"{}()\".format(self.name)\n\n\nclass ACM_HANDataset(HANDataset):\n def __init__(self, data_path=\"data\"):\n dataset = \"han-acm\"\n path = osp.join(data_path, dataset)\n super(ACM_HANDataset, self).__init__(path, dataset)\n\n\nclass DBLP_HANDataset(HANDataset):\n def __init__(self, data_path=\"data\"):\n dataset = \"han-dblp\"\n path = osp.join(data_path, dataset)\n super(DBLP_HANDataset, self).__init__(path, dataset)\n\n\nclass IMDB_HANDataset(HANDataset):\n def __init__(self, data_path=\"data\"):\n dataset = \"han-imdb\"\n path = osp.join(data_path, dataset)\n super(IMDB_HANDataset, self).__init__(path, dataset)\n"
]
| [
[
"torch.zeros",
"torch.randint",
"torch.randn"
],
[
"numpy.array",
"torch.cat",
"numpy.zeros",
"torch.max",
"torch.arange",
"torch.save",
"torch.from_numpy",
"torch.ones",
"numpy.eye",
"numpy.argmax",
"torch.load"
]
]
|
honeypotz-eu/cortex | [
"7c2b5b07f9dbf9bf56def8a6e3a60763e271bd39"
]
| [
"examples/pytorch/iris-classifier/model.py"
]
| [
"# WARNING: you are on the master branch; please refer to examples on the branch corresponding to your `cortex version` (e.g. for version 0.19.*, run `git checkout -b 0.19` or switch to the `0.19` branch on GitHub)\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\nclass IrisNet(nn.Module):\n def __init__(self):\n super(IrisNet, self).__init__()\n self.fc1 = nn.Linear(4, 100)\n self.fc2 = nn.Linear(100, 100)\n self.fc3 = nn.Linear(100, 3)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, X):\n X = F.relu(self.fc1(X))\n X = self.fc2(X)\n X = self.fc3(X)\n X = self.softmax(X)\n return X\n\n\nif __name__ == \"__main__\":\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)\n\n train_X = Variable(torch.Tensor(X_train).float())\n test_X = Variable(torch.Tensor(X_test).float())\n train_y = Variable(torch.Tensor(y_train).long())\n test_y = Variable(torch.Tensor(y_test).long())\n\n model = IrisNet()\n\n criterion = nn.CrossEntropyLoss()\n\n optimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\n for epoch in range(1000):\n optimizer.zero_grad()\n out = model(train_X)\n loss = criterion(out, train_y)\n loss.backward()\n optimizer.step()\n\n if epoch % 100 == 0:\n print(\"number of epoch {} loss {}\".format(epoch, loss))\n\n predict_out = model(test_X)\n _, predict_y = torch.max(predict_out, 1)\n\n print(\"prediction accuracy {}\".format(accuracy_score(test_y.data, predict_y.data)))\n\n torch.save(model.state_dict(), \"weights.pth\")\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.Softmax",
"torch.max",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.train_test_split",
"torch.Tensor",
"torch.nn.CrossEntropyLoss",
"sklearn.datasets.load_iris"
]
]
|
winnerineast/morph-net | [
"620eeb07f47ea1d40c105a96d5fea639d329c6ff"
]
| [
"morph_net/framework/conv_source_op_handler_test.py"
]
| [
"\"\"\"Tests for regularizers.framework.conv_source_op_handler.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom absl.testing import parameterized\n\nimport mock\nfrom morph_net.framework import conv_source_op_handler\nfrom morph_net.framework import op_regularizer_manager as orm\nimport tensorflow as tf\n\nlayers = tf.contrib.layers\n\n_DEFAULT_THRESHOLD = 0.001\n\n\nclass ConvsSourceOpHandlerTest(parameterized.TestCase, tf.test.TestCase):\n\n def _build(self, conv_type):\n assert conv_type in ['Conv2D', 'Conv3D']\n if conv_type == 'Conv2D':\n inputs = tf.zeros([2, 4, 4, 3])\n conv_fn = layers.conv2d\n else:\n inputs = tf.zeros([2, 4, 4, 4, 3])\n conv_fn = layers.conv3d\n\n c1 = conv_fn(\n inputs, num_outputs=5, kernel_size=3, scope='conv1', normalizer_fn=None)\n conv_fn(c1, num_outputs=6, kernel_size=3, scope='conv2', normalizer_fn=None)\n\n g = tf.get_default_graph()\n\n # Declare OpSlice and OpGroup for ops of interest.\n self.conv1_op = g.get_operation_by_name('conv1/' + conv_type)\n self.conv1_op_slice = orm.OpSlice(self.conv1_op, orm.Slice(0, 5))\n self.conv1_op_group = orm.OpGroup(\n self.conv1_op_slice, omit_source_op_slices=[self.conv1_op_slice])\n\n self.relu1_op = g.get_operation_by_name('conv1/Relu')\n self.relu1_op_slice = orm.OpSlice(self.relu1_op, orm.Slice(0, 5))\n self.relu1_op_group = orm.OpGroup(\n self.relu1_op_slice, omit_source_op_slices=[self.relu1_op_slice])\n\n self.conv2_op = g.get_operation_by_name('conv2/' + conv_type)\n self.conv2_op_slice = orm.OpSlice(self.conv2_op, orm.Slice(0, 6))\n self.conv2_op_group = orm.OpGroup(\n self.conv2_op_slice, omit_source_op_slices=[self.conv2_op_slice])\n\n self.conv2_weights_op = g.get_operation_by_name('conv2/weights/read')\n self.conv2_weights_op_slice = orm.OpSlice(\n self.conv2_weights_op, orm.Slice(0, 6))\n self.conv2_weights_op_group = orm.OpGroup(\n self.conv2_weights_op_slice,\n omit_source_op_slices=[self.conv2_weights_op_slice])\n\n self.relu2_op = g.get_operation_by_name('conv2/Relu')\n self.relu2_op_slice = orm.OpSlice(self.relu2_op, orm.Slice(0, 6))\n self.relu2_op_group = orm.OpGroup(\n self.relu2_op_slice, omit_source_op_slices=[self.relu2_op_slice])\n\n # Create mock OpRegularizerManager with custom mapping of OpSlice and\n # OpGroup.\n self.mock_op_reg_manager = mock.create_autospec(orm.OpRegularizerManager)\n\n def get_op_slices(op):\n return self.op_slice_dict.get(op, [])\n\n def get_op_group(op_slice):\n return self.op_group_dict.get(op_slice)\n\n def is_passthrough(op):\n if op in [self.conv1_op, self.conv2_op]:\n h = conv_source_op_handler.ConvSourceOpHandler(_DEFAULT_THRESHOLD)\n return h.is_passthrough\n else:\n return False\n\n self.mock_op_reg_manager.get_op_slices.side_effect = get_op_slices\n self.mock_op_reg_manager.get_op_group.side_effect = get_op_group\n self.mock_op_reg_manager.is_source_op.return_value = False\n self.mock_op_reg_manager.is_passthrough.side_effect = is_passthrough\n self.mock_op_reg_manager.ops = [\n self.conv1_op, self.relu1_op, self.conv2_op, self.relu2_op,\n self.conv2_weights_op]\n\n @parameterized.named_parameters(('_conv2d', 'Conv2D'), ('_conv3d', 'Conv3D'))\n def testAssignGrouping_GroupWithOutputOnly(self, conv_type):\n self._build(conv_type)\n # Map ops to slices.\n self.op_slice_dict = {\n self.conv1_op: [self.conv1_op_slice],\n self.relu1_op: [self.relu1_op_slice],\n self.conv2_op: [self.conv2_op_slice],\n self.relu2_op: [self.relu2_op_slice],\n }\n\n # Map each slice to a group. Corresponding op slices have the same group.\n self.op_group_dict = {\n self.conv2_op_slice: self.conv2_op_group,\n }\n\n # Call handler to assign grouping.\n handler = conv_source_op_handler.ConvSourceOpHandler(_DEFAULT_THRESHOLD)\n handler.assign_grouping(self.conv2_op, self.mock_op_reg_manager)\n\n # Verify manager looks up op slice for ops of interest.\n self.mock_op_reg_manager.get_op_slices.assert_any_call(self.conv2_op)\n\n # Verify manager does not slice any ops.\n self.mock_op_reg_manager.slice_op.assert_not_called()\n\n # Verify manager adds inputs to process queue.\n self.mock_op_reg_manager.process_ops.assert_called_once_with(\n [self.relu1_op])\n\n @parameterized.named_parameters(('_conv2d', 'Conv2D'), ('_conv3d', 'Conv3D'))\n def testCreateRegularizer(self, conv_type):\n self._build(conv_type)\n # Call handler to create regularizer.\n handler = conv_source_op_handler.ConvSourceOpHandler(_DEFAULT_THRESHOLD)\n regularizer = handler.create_regularizer(self.conv2_op_slice)\n\n # Verify regularizer produces correctly shaped tensors.\n # Most of the regularizer testing is in group_lasso_regularizer_test.py\n expected_norm_dim = self.conv2_op.inputs[1].shape.as_list()[-1]\n self.assertEqual(expected_norm_dim,\n regularizer.regularization_vector.shape.as_list()[0])\n\n @parameterized.named_parameters(('_conv2d', 'Conv2D'), ('_conv3d', 'Conv3D'))\n def testCreateRegularizer_Sliced(self, conv_type):\n self._build(conv_type)\n # Call handler to create regularizer.\n handler = conv_source_op_handler.ConvSourceOpHandler(_DEFAULT_THRESHOLD)\n conv2_op_slice = orm.OpSlice(self.conv2_op, orm.Slice(0, 3))\n regularizer = handler.create_regularizer(conv2_op_slice)\n\n # Verify regularizer produces correctly shaped tensors.\n # Most of the regularizer testing is in group_lasso_regularizer_test.py\n expected_norm_dim = 3\n self.assertEqual(expected_norm_dim,\n regularizer.regularization_vector.shape.as_list()[0])\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
]
| [
[
"tensorflow.zeros",
"tensorflow.test.main",
"tensorflow.get_default_graph"
]
]
|
doublechenching/hpi | [
"68675bbd06497e41593526d7d4f58001d758c29d"
]
| [
"hpi_keras/train_inception_resnet.py"
]
| [
"#encoding: utf-8\nfrom __future__ import print_function\nfrom keras import backend as K\nfrom config import config as cfg\nfrom training import init_env, get_number_of_steps\ngpus = '0'\ninit_env(gpus)\nn_gpus = len(gpus.split(','))\ncfg.batch_size = cfg.batch_size * n_gpus\nimport os\nimport numpy as np\nfrom proc.data import load_train_csv, split_train_val, load_extra_csv\nfrom proc.gennerator import BaseGenerator, BaseExtraDataGenerator\nfrom model.inception_resnet_v2 import InceptionResNetV2, preprocess_input\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau\nfrom training.callback import MultiGPUCheckpoint\nfrom utils import makedir\nfrom keras.utils import multi_gpu_model\nfrom utils import schedule_steps, find_best_weights\nfrom keras import optimizers as KO\nfrom metrics import f1_score\nimport tensorflow as tf\nimport random\n\n\ndef load_extra_data_gen(target_shape=(512, 512)):\n train_val_df = load_extra_csv(cfg)\n train_df, val_df = split_train_val(train_val_df, 0.15, seed=42)\n train_gen = BaseExtraDataGenerator(train_df, cfg.extra_data_dir, \n batch_size=cfg.batch_size,\n aug_args=cfg.aug_args.copy(),\n target_shape=target_shape,\n use_yellow=False,\n preprocessing_function=preprocess_input)\n \n val_gen = BaseExtraDataGenerator(val_df, cfg.extra_data_dir, \n batch_size=cfg.batch_size,\n aug_args=cfg.aug_args.copy(),\n target_shape=target_shape,\n use_yellow=False,\n preprocessing_function=preprocess_input)\n\n return train_df, val_df, train_gen, val_gen\n\n\ndef load_local_gen(target_shape):\n train_val_df = load_train_csv(cfg)\n train_df, val_df = split_train_val(train_val_df, 0.25, seed=42)\n train_gen = BaseGenerator(train_df, cfg.train_dir, \n batch_size=cfg.batch_size,\n aug_args=cfg.aug_args.copy(),\n target_shape=target_shape,\n use_yellow=False,\n preprocessing_function=preprocess_input)\n\n val_gen = BaseGenerator(val_df, cfg.train_dir, \n batch_size=cfg.batch_size,\n aug_args=cfg.aug_args.copy(),\n target_shape=target_shape,\n use_yellow=False,\n preprocessing_function=preprocess_input)\n\n return train_df, val_df, train_gen, val_gen \n\n\ndef train(task_name='base_inception',\n epochs=6,\n target_shape=(512, 512),\n lr_schedule=None,\n weights='imagenet',\n trainable=True,\n seed=42,\n save_best_only=True,\n initial_epoch=0,\n use_extra_data=False):\n\n np.random.seed(seed + 111)\n random.seed(seed + 111)\n tf.set_random_seed(seed + 111)\n if not use_extra_data:\n train_df, val_df, train_gen, val_gen = load_local_gen(target_shape)\n else:\n train_df, val_df, train_gen, val_gen = load_extra_data_gen(target_shape)\n\n if n_gpus > 1:\n print('use multi gpu')\n with tf.device('/cpu:0'):\n cpu_model = InceptionResNetV2(input_shape=list(target_shape) + [3], \n classes=len(cfg.label_names), \n trainable=trainable)\n if weights == \"imagenet\":\n cpu_model.load_weights(cfg.inception_imagenet_weights, by_name=True, skip_mismatch=True)\n else:\n cpu_model.load_weights(weights)\n model = multi_gpu_model(cpu_model, gpus=n_gpus)\n else:\n print('use single gpu')\n model = InceptionResNetV2(input_shape=cfg.input_shape, classes=len(\n cfg.label_names), trainable=False)\n if weights == \"imagenet\":\n cpu_model.load_weights(cfg.inception_imagenet_weights, by_name=True, skip_mismatch=True)\n else:\n cpu_model.load_weights(weights)\n print('load weights from ', weights)\n\n model.compile(optimizer=KO.Adam(lr=lr_schedule[0][0], amsgrad=True), \n loss='binary_crossentropy',\n metrics=['binary_accuracy', 'mae'])\n log_dir = os.path.join(cfg.log_dir, task_name)\n makedir(log_dir)\n weights_path = os.path.join(log_dir, cfg.weights_file)\n checkpoint = ModelCheckpoint(weights_path, \n monitor='f1_score', \n verbose=1, \n mode='max',\n save_best_only=save_best_only,\n save_weights_only=True)\n\n if n_gpus > 1:\n del checkpoint\n checkpoint = MultiGPUCheckpoint(weights_path, cpu_model, \n monitor='f1_score',\n mode='max',\n save_best_only=save_best_only)\n\n callbacks = [checkpoint]\n callbacks += [LearningRateScheduler(lambda epoch: schedule_steps(epoch, lr_schedule))]\n train_steps = get_number_of_steps(len(train_df), cfg.batch_size) * 4\n val_steps = get_number_of_steps(len(val_df), cfg.batch_size) * 4\n model.fit_generator(train_gen,\n epochs=epochs,\n steps_per_epoch=train_steps,\n callbacks=callbacks,\n validation_data=val_gen,\n workers=cfg.n_works,\n max_queue_size=cfg.n_queue,\n use_multiprocessing=True,\n validation_steps=val_steps,\n initial_epoch=initial_epoch)\n del model\n del checkpoint\n K.clear_session()\n\n\nif __name__ == \"__main__\":\n print(cfg)\n # pretrain\n task_name = 'pretrain_inception_res'\n train(task_name=task_name, epochs=6, lr_schedule=[(1e-5, 2), (3e-3, 4), (1e-3, 6)], weights='xception_imagenet.hdf5',\n seed=41, trainable=False, save_best_only=False)\n # train\n weights = find_best_weights(os.path.join(cfg.log_dir, task_name))\n task_name = 'pretrain_inception_res'\n train(task_name=task_name, epochs=70,\n lr_schedule=[(5e-5, 2), (3e-3, 10), (1e-3, 40), (5e-4, 55), (1e-4, 65), (1e-5, 70)],\n weights=weights, seed=42)\n weights = find_best_weights(os.path.join(cfg.log_dir, task_name))\n train(task_name=task_name, epochs=100, lr_schedule=[(1e-5, 72), (3e-4, 80), (1e-4, 90), (1e-5, 100)],\n weights=weights, seed=43, initial_epoch=70)\n weights = find_best_weights(os.path.join(cfg.log_dir, task_name))\n # fintune\n task_name = 'pretrain_inception_res'\n train(task_name=task_name, epochs=25, lr_schedule=[(5e-5, 0), (5e-5, 2), (1e-4, 10), (1e-5, 20), (1e-6, 25)],\n weights=weights, seed=44, initial_epoch=70)"
]
| [
[
"numpy.random.seed",
"tensorflow.set_random_seed",
"tensorflow.device"
]
]
|
wuhaoqiu/engr597-stable | [
"284ab9efae8361c139d330313abb831bfea9e5b9"
]
| [
"mysite/mlmodels/chatbot/model_chatbot.py"
]
| [
"#author:Haoqiu Wu Time 19.3.11\nimport pickle\nimport os\n\n\nfile_qrDict = 'qrDict.pk'\nfile_sentenceTokens = 'sentenceTokens.pk'\nfile_ql = 'ql.pk'\n\n# read local serialized clean dataset\nwith open(os.path.join(os.path.dirname(__file__), '../picklized_files/'+file_qrDict) ,'rb') as f:\n qrDict = pickle.load(f)\n\nwith open(os.path.join(os.path.dirname(__file__), '../picklized_files/'+file_sentenceTokens) ,'rb') as f:\n sentenceTokens = pickle.load(f)\n\nwith open(os.path.join(os.path.dirname(__file__), '../picklized_files/'+file_ql) ,'rb') as f:\n ql = pickle.load(f)\n\n\"\"\"\ngenerate Response\n\"\"\"\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nfrom nltk.stem import WordNetLemmatizer\nimport string\n\n\n\ndef sanitize_questions(question):\n sanitized_question = question.translate(str.maketrans('', '', string.punctuation)).rstrip().lstrip()\n return sanitized_question\n\n# for a given sentence,return a lemmatized sentence\ndef lemTokens(tokens):\n lemmatizer = WordNetLemmatizer()\n return [lemmatizer.lemmatize(token) for token in tokens]\n\n\ndef generateResponse(userInput, sentences, askResponseDict, ql, similarityThredhold=0.7):\n # prevent bad input\n if ((similarityThredhold > 1) or (similarityThredhold < 0)):\n similarityThredhold = 0.7\n sentences.append(userInput)\n # vetorize sentences and userinput for fllowing similarity calculation\n vertorizedSentences = TfidfVectorizer(tokenizer=lemTokens, stop_words='english').fit_transform(sentences)\n vals = cosine_similarity(vertorizedSentences[-1], vertorizedSentences)\n # find index of sentences that has highest similarity with input\n valsWithoutLast = vals[0, :-1]\n idx = np.argmax(valsWithoutLast, axis=0)\n # return response\n if (vals[0][idx] < similarityThredhold):\n robotResponse = [\"Your input keywords donot exist in my knowledge\",\"I donot know what you are talking\",'Sorry I have no idea','Sorry I donot understand'\n ,'Sorry I can not reply',\"Pls change a topic\",\"Looks like I still need to learn more\"]\n import random\n index=random.randint(0,8)\n sentences.remove(userInput)\n return robotResponse[index]\n else:\n question = ql[idx]\n print(\"matched from db:\"+question)\n robotResponse = '' + askResponseDict.get(question)\n sentences.remove(userInput)\n return robotResponse\n\n\n\ndef reply(userInput):\n userInput = sanitize_questions(userInput.lower())\n return generateResponse(userInput, sentenceTokens, qrDict, ql)\n\n\nif __name__=='__main__':\n flag = True\n print(\"ROBO: Hello, I am a chatbot. Type Bye to exit\")\n while (flag == True):\n userInput = input()\n userInput = sanitize_questions(userInput.lower())\n if (userInput != 'bye'):\n if (userInput == 'thanks' or userInput == 'thank you'):\n flag = False\n print(\"ROBO: You are welcome..\")\n else:\n print(\"ROBO: \" + reply(userInput))\n # sentenceTokens.remove(userInput)\n else:\n flag = False\n print(\"ROBO: Bye! take care..\")\n"
]
| [
[
"numpy.argmax",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.metrics.pairwise.cosine_similarity"
]
]
|
Johnathan-Xie/CenterTrack | [
"273e4090239a53fedee49da6d3e33c3c82c517d1"
]
| [
"src/tools/convert_nuScenes.py"
]
| [
"# Copyright (c) Xingyi Zhou. All Rights Reserved\n'''\nnuScenes pre-processing script.\nThis file convert the nuScenes annotation into COCO format.\n'''\nimport json\nimport numpy as np\nfrom tqdm import tqdm\nimport os\nimport cv2\nimport copy\nimport matplotlib.pyplot as plt\nfrom nuscenes.nuscenes import NuScenes\nfrom nuscenes.utils.geometry_utils import BoxVisibility, transform_matrix\nfrom nuScenes_lib.utils_kitti import KittiDB\nfrom nuscenes.eval.detection.utils import category_to_detection_name\nfrom pyquaternion import Quaternion\n\nimport _init_paths\nfrom utils.ddd_utils import compute_box_3d, project_to_image, alpha2rot_y\nfrom utils.ddd_utils import draw_box_3d, unproject_2d_to_3d\n\nDATA_PATH = '../../data/nuscenes/'\nOUT_PATH = DATA_PATH + 'annotations/'\nSPLITS = {\n 'val': 'v1.0-trainval', \n 'train': 'v1.0-trainval', \n #'test': 'v1.0-test'\n }\nDEBUG = False\nCATS = ['car', 'truck', 'bus', 'trailer', 'construction_vehicle', \n 'pedestrian', 'motorcycle', 'bicycle',\n 'traffic_cone', 'barrier']\nSENSOR_ID = {'RADAR_FRONT': 7, 'RADAR_FRONT_LEFT': 9, \n 'RADAR_FRONT_RIGHT': 10, 'RADAR_BACK_LEFT': 11, \n 'RADAR_BACK_RIGHT': 12, 'LIDAR_TOP': 8, \n 'CAM_FRONT': 1, 'CAM_FRONT_RIGHT': 2, \n 'CAM_BACK_RIGHT': 3, 'CAM_BACK': 4, 'CAM_BACK_LEFT': 5,\n 'CAM_FRONT_LEFT': 6}\n\nUSED_SENSOR = ['CAM_FRONT', 'CAM_FRONT_RIGHT', \n 'CAM_BACK_RIGHT', 'CAM_BACK', 'CAM_BACK_LEFT',\n 'CAM_FRONT_LEFT']\nCAT_IDS = {v: i + 1 for i, v in enumerate(CATS)}\n\ndef _rot_y2alpha(rot_y, x, cx, fx):\n \"\"\"\n Get rotation_y by alpha + theta - 180\n alpha : Observation angle of object, ranging [-pi..pi]\n x : Object center x to the camera center (x-W/2), in pixels\n rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi]\n \"\"\"\n alpha = rot_y - np.arctan2(x - cx, fx)\n if alpha > np.pi:\n alpha -= 2 * np.pi\n if alpha < -np.pi:\n alpha += 2 * np.pi\n return alpha\n\ndef _bbox_inside(box1, box2):\n return box1[0] > box2[0] and box1[0] + box1[2] < box2[0] + box2[2] and \\\n box1[1] > box2[1] and box1[1] + box1[3] < box2[1] + box2[3] \n\nATTRIBUTE_TO_ID = {\n '': 0, 'cycle.with_rider' : 1, 'cycle.without_rider' : 2,\n 'pedestrian.moving': 3, 'pedestrian.standing': 4, \n 'pedestrian.sitting_lying_down': 5,\n 'vehicle.moving': 6, 'vehicle.parked': 7, \n 'vehicle.stopped': 8}\n\ndef main():\n SCENE_SPLITS['mini-val'] = SCENE_SPLITS['val']\n if not os.path.exists(OUT_PATH):\n os.mkdir(OUT_PATH)\n for split in SPLITS:\n data_path = DATA_PATH\n nusc = NuScenes(\n version=SPLITS[split], dataroot=data_path, verbose=True)\n \n out_path = OUT_PATH + '{}.json'.format(split)\n categories_info = [{'name': CATS[i], 'id': i + 1} for i in range(len(CATS))]\n ret = {'images': [], 'annotations': [], 'categories': categories_info, \n 'videos': [], 'attributes': ATTRIBUTE_TO_ID}\n num_images = 0\n num_anns = 0\n num_videos = 0\n\n # A \"sample\" in nuScenes refers to a timestamp with 6 cameras and 1 LIDAR.\n for sample in tqdm(nusc.sample):\n scene_name = nusc.get('scene', sample['scene_token'])['name']\n if not (split in ['mini', 'test']) and \\\n not (scene_name in SCENE_SPLITS[split]):\n continue\n if sample['prev'] == '':\n #print('scene_name', scene_name)\n num_videos += 1\n ret['videos'].append({'id': num_videos, 'file_name': scene_name})\n frame_ids = {k: 0 for k in sample['data']}\n track_ids = {}\n # We decompose a sample into 6 images in our case.\n for sensor_name in sample['data']:\n if sensor_name in USED_SENSOR:\n image_token = sample['data'][sensor_name]\n image_data = nusc.get('sample_data', image_token)\n num_images += 1\n\n # Complex coordinate transform. This will take time to understand.\n sd_record = nusc.get('sample_data', image_token)\n cs_record = nusc.get(\n 'calibrated_sensor', sd_record['calibrated_sensor_token'])\n pose_record = nusc.get('ego_pose', sd_record['ego_pose_token'])\n global_from_car = transform_matrix(pose_record['translation'],\n Quaternion(pose_record['rotation']), inverse=False)\n car_from_sensor = transform_matrix(\n cs_record['translation'], Quaternion(cs_record['rotation']),\n inverse=False)\n trans_matrix = np.dot(global_from_car, car_from_sensor)\n _, boxes, camera_intrinsic = nusc.get_sample_data(\n image_token, box_vis_level=BoxVisibility.ANY)\n calib = np.eye(4, dtype=np.float32)\n calib[:3, :3] = camera_intrinsic\n calib = calib[:3]\n frame_ids[sensor_name] += 1\n\n # image information in COCO format\n image_info = {'id': num_images,\n 'file_name': image_data['filename'],\n 'calib': calib.tolist(), \n 'video_id': num_videos,\n 'frame_id': frame_ids[sensor_name],\n 'sensor_id': SENSOR_ID[sensor_name],\n 'sample_token': sample['token'],\n 'trans_matrix': trans_matrix.tolist(),\n 'width': sd_record['width'],\n 'height': sd_record['height'],\n 'pose_record_trans': pose_record['translation'],\n 'pose_record_rot': pose_record['rotation'],\n 'cs_record_trans': cs_record['translation'],\n 'cs_record_rot': cs_record['rotation']}\n ret['images'].append(image_info)\n anns = []\n for box in boxes:\n det_name = category_to_detection_name(box.name)\n if det_name is None:\n continue\n num_anns += 1\n v = np.dot(box.rotation_matrix, np.array([1, 0, 0]))\n yaw = -np.arctan2(v[2], v[0])\n box.translate(np.array([0, box.wlh[2] / 2, 0]))\n category_id = CAT_IDS[det_name]\n\n amodel_center = project_to_image(\n np.array([box.center[0], box.center[1] - box.wlh[2] / 2, box.center[2]], \n np.float32).reshape(1, 3), calib)[0].tolist()\n sample_ann = nusc.get(\n 'sample_annotation', box.token)\n instance_token = sample_ann['instance_token']\n if not (instance_token in track_ids):\n track_ids[instance_token] = len(track_ids) + 1\n attribute_tokens = sample_ann['attribute_tokens']\n attributes = [nusc.get('attribute', att_token)['name'] \\\n for att_token in attribute_tokens]\n att = '' if len(attributes) == 0 else attributes[0]\n if len(attributes) > 1:\n print(attributes)\n import pdb; pdb.set_trace()\n track_id = track_ids[instance_token]\n vel = nusc.box_velocity(box.token) # global frame\n vel = np.dot(np.linalg.inv(trans_matrix), \n np.array([vel[0], vel[1], vel[2], 0], np.float32)).tolist()\n \n # instance information in COCO format\n ann = {\n 'id': num_anns,\n 'image_id': num_images,\n 'category_id': category_id,\n 'dim': [box.wlh[2], box.wlh[0], box.wlh[1]],\n 'location': [box.center[0], box.center[1], box.center[2]],\n 'depth': box.center[2],\n 'occluded': 0,\n 'truncated': 0,\n 'rotation_y': yaw,\n 'amodel_center': amodel_center,\n 'iscrowd': 0,\n 'track_id': track_id,\n 'attributes': ATTRIBUTE_TO_ID[att],\n 'velocity': vel\n }\n\n bbox = KittiDB.project_kitti_box_to_image(\n copy.deepcopy(box), camera_intrinsic, imsize=(1600, 900))\n alpha = _rot_y2alpha(yaw, (bbox[0] + bbox[2]) / 2, \n camera_intrinsic[0, 2], camera_intrinsic[0, 0])\n ann['bbox'] = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]\n ann['area'] = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])\n ann['alpha'] = alpha\n anns.append(ann)\n\n # Filter out bounding boxes outside the image\n visable_anns = []\n for i in range(len(anns)):\n vis = True\n for j in range(len(anns)):\n if anns[i]['depth'] - min(anns[i]['dim']) / 2 > \\\n anns[j]['depth'] + max(anns[j]['dim']) / 2 and \\\n _bbox_inside(anns[i]['bbox'], anns[j]['bbox']):\n vis = False\n break\n if vis:\n visable_anns.append(anns[i])\n else:\n pass\n\n for ann in visable_anns:\n ret['annotations'].append(ann)\n if DEBUG:\n img_path = data_path + image_info['file_name']\n img = cv2.imread(img_path)\n img_3d = img.copy()\n for ann in visable_anns:\n bbox = ann['bbox']\n cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), \n (int(bbox[2] + bbox[0]), int(bbox[3] + bbox[1])), \n (0, 0, 255), 3, lineType=cv2.LINE_AA)\n box_3d = compute_box_3d(ann['dim'], ann['location'], ann['rotation_y'])\n box_2d = project_to_image(box_3d, calib)\n img_3d = draw_box_3d(img_3d, box_2d)\n\n pt_3d = unproject_2d_to_3d(ann['amodel_center'], ann['depth'], calib)\n pt_3d[1] += ann['dim'][0] / 2\n print('location', ann['location'])\n print('loc model', pt_3d)\n pt_2d = np.array([(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2],\n dtype=np.float32)\n pt_3d = unproject_2d_to_3d(pt_2d, ann['depth'], calib)\n pt_3d[1] += ann['dim'][0] / 2\n print('loc ', pt_3d)\n cv2.imshow('img', img)\n cv2.imshow('img_3d', img_3d)\n cv2.waitKey()\n nusc.render_sample_data(image_token)\n plt.show()\n print('reordering images')\n images = ret['images']\n video_sensor_to_images = {}\n for image_info in images:\n tmp_seq_id = image_info['video_id'] * 20 + image_info['sensor_id']\n if tmp_seq_id in video_sensor_to_images:\n video_sensor_to_images[tmp_seq_id].append(image_info)\n else:\n video_sensor_to_images[tmp_seq_id] = [image_info]\n ret['images'] = []\n for tmp_seq_id in sorted(video_sensor_to_images):\n ret['images'] = ret['images'] + video_sensor_to_images[tmp_seq_id]\n\n print('{} {} images {} boxes'.format(\n split, len(ret['images']), len(ret['annotations'])))\n print('out_path', out_path)\n json.dump(ret, open(out_path, 'w'))\n\n# Official train/ val split from \n# https://github.com/nutonomy/nuscenes-devkit/blob/master/python-sdk/nuscenes/utils/splits.py\nSCENE_SPLITS = {\n'train':\n ['scene-0001', 'scene-0002', 'scene-0004', 'scene-0005', 'scene-0006', 'scene-0007', 'scene-0008', 'scene-0009',\n 'scene-0010', 'scene-0011', 'scene-0019', 'scene-0020', 'scene-0021', 'scene-0022', 'scene-0023', 'scene-0024',\n 'scene-0025', 'scene-0026', 'scene-0027', 'scene-0028', 'scene-0029', 'scene-0030', 'scene-0031', 'scene-0032',\n 'scene-0033', 'scene-0034', 'scene-0041', 'scene-0042', 'scene-0043', 'scene-0044', 'scene-0045', 'scene-0046',\n 'scene-0047', 'scene-0048', 'scene-0049', 'scene-0050', 'scene-0051', 'scene-0052', 'scene-0053', 'scene-0054',\n 'scene-0055', 'scene-0056', 'scene-0057', 'scene-0058', 'scene-0059', 'scene-0060', 'scene-0061', 'scene-0062',\n 'scene-0063', 'scene-0064', 'scene-0065', 'scene-0066', 'scene-0067', 'scene-0068', 'scene-0069', 'scene-0070',\n 'scene-0071', 'scene-0072', 'scene-0073', 'scene-0074', 'scene-0075', 'scene-0076', 'scene-0120', 'scene-0121',\n 'scene-0122', 'scene-0123', 'scene-0124', 'scene-0125', 'scene-0126', 'scene-0127', 'scene-0128', 'scene-0129',\n 'scene-0130', 'scene-0131', 'scene-0132', 'scene-0133', 'scene-0134', 'scene-0135', 'scene-0138', 'scene-0139',\n 'scene-0149', 'scene-0150', 'scene-0151', 'scene-0152', 'scene-0154', 'scene-0155', 'scene-0157', 'scene-0158',\n 'scene-0159', 'scene-0160', 'scene-0161', 'scene-0162', 'scene-0163', 'scene-0164', 'scene-0165', 'scene-0166',\n 'scene-0167', 'scene-0168', 'scene-0170', 'scene-0171', 'scene-0172', 'scene-0173', 'scene-0174', 'scene-0175',\n 'scene-0176', 'scene-0177', 'scene-0178', 'scene-0179', 'scene-0180', 'scene-0181', 'scene-0182', 'scene-0183',\n 'scene-0184', 'scene-0185', 'scene-0187', 'scene-0188', 'scene-0190', 'scene-0191', 'scene-0192', 'scene-0193',\n 'scene-0194', 'scene-0195', 'scene-0196', 'scene-0199', 'scene-0200', 'scene-0202', 'scene-0203', 'scene-0204',\n 'scene-0206', 'scene-0207', 'scene-0208', 'scene-0209', 'scene-0210', 'scene-0211', 'scene-0212', 'scene-0213',\n 'scene-0214', 'scene-0218', 'scene-0219', 'scene-0220', 'scene-0222', 'scene-0224', 'scene-0225', 'scene-0226',\n 'scene-0227', 'scene-0228', 'scene-0229', 'scene-0230', 'scene-0231', 'scene-0232', 'scene-0233', 'scene-0234',\n 'scene-0235', 'scene-0236', 'scene-0237', 'scene-0238', 'scene-0239', 'scene-0240', 'scene-0241', 'scene-0242',\n 'scene-0243', 'scene-0244', 'scene-0245', 'scene-0246', 'scene-0247', 'scene-0248', 'scene-0249', 'scene-0250',\n 'scene-0251', 'scene-0252', 'scene-0253', 'scene-0254', 'scene-0255', 'scene-0256', 'scene-0257', 'scene-0258',\n 'scene-0259', 'scene-0260', 'scene-0261', 'scene-0262', 'scene-0263', 'scene-0264', 'scene-0283', 'scene-0284',\n 'scene-0285', 'scene-0286', 'scene-0287', 'scene-0288', 'scene-0289', 'scene-0290', 'scene-0291', 'scene-0292',\n 'scene-0293', 'scene-0294', 'scene-0295', 'scene-0296', 'scene-0297', 'scene-0298', 'scene-0299', 'scene-0300',\n 'scene-0301', 'scene-0302', 'scene-0303', 'scene-0304', 'scene-0305', 'scene-0306', 'scene-0315', 'scene-0316',\n 'scene-0317', 'scene-0318', 'scene-0321', 'scene-0323', 'scene-0324', 'scene-0328', 'scene-0347', 'scene-0348',\n 'scene-0349', 'scene-0350', 'scene-0351', 'scene-0352', 'scene-0353', 'scene-0354', 'scene-0355', 'scene-0356',\n 'scene-0357', 'scene-0358', 'scene-0359', 'scene-0360', 'scene-0361', 'scene-0362', 'scene-0363', 'scene-0364',\n 'scene-0365', 'scene-0366', 'scene-0367', 'scene-0368', 'scene-0369', 'scene-0370', 'scene-0371', 'scene-0372',\n 'scene-0373', 'scene-0374', 'scene-0375', 'scene-0376', 'scene-0377', 'scene-0378', 'scene-0379', 'scene-0380',\n 'scene-0381', 'scene-0382', 'scene-0383', 'scene-0384', 'scene-0385', 'scene-0386', 'scene-0388', 'scene-0389',\n 'scene-0390', 'scene-0391', 'scene-0392', 'scene-0393', 'scene-0394', 'scene-0395', 'scene-0396', 'scene-0397',\n 'scene-0398', 'scene-0399', 'scene-0400', 'scene-0401', 'scene-0402', 'scene-0403', 'scene-0405', 'scene-0406',\n 'scene-0407', 'scene-0408', 'scene-0410', 'scene-0411', 'scene-0412', 'scene-0413', 'scene-0414', 'scene-0415',\n 'scene-0416', 'scene-0417', 'scene-0418', 'scene-0419', 'scene-0420', 'scene-0421', 'scene-0422', 'scene-0423',\n 'scene-0424', 'scene-0425', 'scene-0426', 'scene-0427', 'scene-0428', 'scene-0429', 'scene-0430', 'scene-0431',\n 'scene-0432', 'scene-0433', 'scene-0434', 'scene-0435', 'scene-0436', 'scene-0437', 'scene-0438', 'scene-0439',\n 'scene-0440', 'scene-0441', 'scene-0442', 'scene-0443', 'scene-0444', 'scene-0445', 'scene-0446', 'scene-0447',\n 'scene-0448', 'scene-0449', 'scene-0450', 'scene-0451', 'scene-0452', 'scene-0453', 'scene-0454', 'scene-0455',\n 'scene-0456', 'scene-0457', 'scene-0458', 'scene-0459', 'scene-0461', 'scene-0462', 'scene-0463', 'scene-0464',\n 'scene-0465', 'scene-0467', 'scene-0468', 'scene-0469', 'scene-0471', 'scene-0472', 'scene-0474', 'scene-0475',\n 'scene-0476', 'scene-0477', 'scene-0478', 'scene-0479', 'scene-0480', 'scene-0499', 'scene-0500', 'scene-0501',\n 'scene-0502', 'scene-0504', 'scene-0505', 'scene-0506', 'scene-0507', 'scene-0508', 'scene-0509', 'scene-0510',\n 'scene-0511', 'scene-0512', 'scene-0513', 'scene-0514', 'scene-0515', 'scene-0517', 'scene-0518', 'scene-0525',\n 'scene-0526', 'scene-0527', 'scene-0528', 'scene-0529', 'scene-0530', 'scene-0531', 'scene-0532', 'scene-0533',\n 'scene-0534', 'scene-0535', 'scene-0536', 'scene-0537', 'scene-0538', 'scene-0539', 'scene-0541', 'scene-0542',\n 'scene-0543', 'scene-0544', 'scene-0545', 'scene-0546', 'scene-0566', 'scene-0568', 'scene-0570', 'scene-0571',\n 'scene-0572', 'scene-0573', 'scene-0574', 'scene-0575', 'scene-0576', 'scene-0577', 'scene-0578', 'scene-0580',\n 'scene-0582', 'scene-0583', 'scene-0584', 'scene-0585', 'scene-0586', 'scene-0587', 'scene-0588', 'scene-0589',\n 'scene-0590', 'scene-0591', 'scene-0592', 'scene-0593', 'scene-0594', 'scene-0595', 'scene-0596', 'scene-0597',\n 'scene-0598', 'scene-0599', 'scene-0600', 'scene-0639', 'scene-0640', 'scene-0641', 'scene-0642', 'scene-0643',\n 'scene-0644', 'scene-0645', 'scene-0646', 'scene-0647', 'scene-0648', 'scene-0649', 'scene-0650', 'scene-0651',\n 'scene-0652', 'scene-0653', 'scene-0654', 'scene-0655', 'scene-0656', 'scene-0657', 'scene-0658', 'scene-0659',\n 'scene-0660', 'scene-0661', 'scene-0662', 'scene-0663', 'scene-0664', 'scene-0665', 'scene-0666', 'scene-0667',\n 'scene-0668', 'scene-0669', 'scene-0670', 'scene-0671', 'scene-0672', 'scene-0673', 'scene-0674', 'scene-0675',\n 'scene-0676', 'scene-0677', 'scene-0678', 'scene-0679', 'scene-0681', 'scene-0683', 'scene-0684', 'scene-0685',\n 'scene-0686', 'scene-0687', 'scene-0688', 'scene-0689', 'scene-0695', 'scene-0696', 'scene-0697', 'scene-0698',\n 'scene-0700', 'scene-0701', 'scene-0703', 'scene-0704', 'scene-0705', 'scene-0706', 'scene-0707', 'scene-0708',\n 'scene-0709', 'scene-0710', 'scene-0711', 'scene-0712', 'scene-0713', 'scene-0714', 'scene-0715', 'scene-0716',\n 'scene-0717', 'scene-0718', 'scene-0719', 'scene-0726', 'scene-0727', 'scene-0728', 'scene-0730', 'scene-0731',\n 'scene-0733', 'scene-0734', 'scene-0735', 'scene-0736', 'scene-0737', 'scene-0738', 'scene-0739', 'scene-0740',\n 'scene-0741', 'scene-0744', 'scene-0746', 'scene-0747', 'scene-0749', 'scene-0750', 'scene-0751', 'scene-0752',\n 'scene-0757', 'scene-0758', 'scene-0759', 'scene-0760', 'scene-0761', 'scene-0762', 'scene-0763', 'scene-0764',\n 'scene-0765', 'scene-0767', 'scene-0768', 'scene-0769', 'scene-0786', 'scene-0787', 'scene-0789', 'scene-0790',\n 'scene-0791', 'scene-0792', 'scene-0803', 'scene-0804', 'scene-0805', 'scene-0806', 'scene-0808', 'scene-0809',\n 'scene-0810', 'scene-0811', 'scene-0812', 'scene-0813', 'scene-0815', 'scene-0816', 'scene-0817', 'scene-0819',\n 'scene-0820', 'scene-0821', 'scene-0822', 'scene-0847', 'scene-0848', 'scene-0849', 'scene-0850', 'scene-0851',\n 'scene-0852', 'scene-0853', 'scene-0854', 'scene-0855', 'scene-0856', 'scene-0858', 'scene-0860', 'scene-0861',\n 'scene-0862', 'scene-0863', 'scene-0864', 'scene-0865', 'scene-0866', 'scene-0868', 'scene-0869', 'scene-0870',\n 'scene-0871', 'scene-0872', 'scene-0873', 'scene-0875', 'scene-0876', 'scene-0877', 'scene-0878', 'scene-0880',\n 'scene-0882', 'scene-0883', 'scene-0884', 'scene-0885', 'scene-0886', 'scene-0887', 'scene-0888', 'scene-0889',\n 'scene-0890', 'scene-0891', 'scene-0892', 'scene-0893', 'scene-0894', 'scene-0895', 'scene-0896', 'scene-0897',\n 'scene-0898', 'scene-0899', 'scene-0900', 'scene-0901', 'scene-0902', 'scene-0903', 'scene-0945', 'scene-0947',\n 'scene-0949', 'scene-0952', 'scene-0953', 'scene-0955', 'scene-0956', 'scene-0957', 'scene-0958', 'scene-0959',\n 'scene-0960', 'scene-0961', 'scene-0975', 'scene-0976', 'scene-0977', 'scene-0978', 'scene-0979', 'scene-0980',\n 'scene-0981', 'scene-0982', 'scene-0983', 'scene-0984', 'scene-0988', 'scene-0989', 'scene-0990', 'scene-0991',\n 'scene-0992', 'scene-0994', 'scene-0995', 'scene-0996', 'scene-0997', 'scene-0998', 'scene-0999', 'scene-1000',\n 'scene-1001', 'scene-1002', 'scene-1003', 'scene-1004', 'scene-1005', 'scene-1006', 'scene-1007', 'scene-1008',\n 'scene-1009', 'scene-1010', 'scene-1011', 'scene-1012', 'scene-1013', 'scene-1014', 'scene-1015', 'scene-1016',\n 'scene-1017', 'scene-1018', 'scene-1019', 'scene-1020', 'scene-1021', 'scene-1022', 'scene-1023', 'scene-1024',\n 'scene-1025', 'scene-1044', 'scene-1045', 'scene-1046', 'scene-1047', 'scene-1048', 'scene-1049', 'scene-1050',\n 'scene-1051', 'scene-1052', 'scene-1053', 'scene-1054', 'scene-1055', 'scene-1056', 'scene-1057', 'scene-1058',\n 'scene-1074', 'scene-1075', 'scene-1076', 'scene-1077', 'scene-1078', 'scene-1079', 'scene-1080', 'scene-1081',\n 'scene-1082', 'scene-1083', 'scene-1084', 'scene-1085', 'scene-1086', 'scene-1087', 'scene-1088', 'scene-1089',\n 'scene-1090', 'scene-1091', 'scene-1092', 'scene-1093', 'scene-1094', 'scene-1095', 'scene-1096', 'scene-1097',\n 'scene-1098', 'scene-1099', 'scene-1100', 'scene-1101', 'scene-1102', 'scene-1104', 'scene-1105', 'scene-1106',\n 'scene-1107', 'scene-1108', 'scene-1109', 'scene-1110'],\n'val':\n ['scene-0003', 'scene-0012', 'scene-0013', 'scene-0014', 'scene-0015', 'scene-0016', 'scene-0017', 'scene-0018',\n 'scene-0035', 'scene-0036', 'scene-0038', 'scene-0039', 'scene-0092', 'scene-0093', 'scene-0094', 'scene-0095',\n 'scene-0096', 'scene-0097', 'scene-0098', 'scene-0099', 'scene-0100', 'scene-0101', 'scene-0102', 'scene-0103',\n 'scene-0104', 'scene-0105', 'scene-0106', 'scene-0107', 'scene-0108', 'scene-0109', 'scene-0110', 'scene-0221',\n 'scene-0268', 'scene-0269', 'scene-0270', 'scene-0271', 'scene-0272', 'scene-0273', 'scene-0274', 'scene-0275',\n 'scene-0276', 'scene-0277', 'scene-0278', 'scene-0329', 'scene-0330', 'scene-0331', 'scene-0332', 'scene-0344',\n 'scene-0345', 'scene-0346', 'scene-0519', 'scene-0520', 'scene-0521', 'scene-0522', 'scene-0523', 'scene-0524',\n 'scene-0552', 'scene-0553', 'scene-0554', 'scene-0555', 'scene-0556', 'scene-0557', 'scene-0558', 'scene-0559',\n 'scene-0560', 'scene-0561', 'scene-0562', 'scene-0563', 'scene-0564', 'scene-0565', 'scene-0625', 'scene-0626',\n 'scene-0627', 'scene-0629', 'scene-0630', 'scene-0632', 'scene-0633', 'scene-0634', 'scene-0635', 'scene-0636',\n 'scene-0637', 'scene-0638', 'scene-0770', 'scene-0771', 'scene-0775', 'scene-0777', 'scene-0778', 'scene-0780',\n 'scene-0781', 'scene-0782', 'scene-0783', 'scene-0784', 'scene-0794', 'scene-0795', 'scene-0796', 'scene-0797',\n 'scene-0798', 'scene-0799', 'scene-0800', 'scene-0802', 'scene-0904', 'scene-0905', 'scene-0906', 'scene-0907',\n 'scene-0908', 'scene-0909', 'scene-0910', 'scene-0911', 'scene-0912', 'scene-0913', 'scene-0914', 'scene-0915',\n 'scene-0916', 'scene-0917', 'scene-0919', 'scene-0920', 'scene-0921', 'scene-0922', 'scene-0923', 'scene-0924',\n 'scene-0925', 'scene-0926', 'scene-0927', 'scene-0928', 'scene-0929', 'scene-0930', 'scene-0931', 'scene-0962',\n 'scene-0963', 'scene-0966', 'scene-0967', 'scene-0968', 'scene-0969', 'scene-0971', 'scene-0972', 'scene-1059',\n 'scene-1060', 'scene-1061', 'scene-1062', 'scene-1063', 'scene-1064', 'scene-1065', 'scene-1066', 'scene-1067',\n 'scene-1068', 'scene-1069', 'scene-1070', 'scene-1071', 'scene-1072', 'scene-1073']\n}\nif __name__ == '__main__':\n main()\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.eye",
"numpy.arctan2",
"matplotlib.pyplot.show",
"numpy.linalg.inv"
]
]
|
taroogura/Person_reID_baseline_pytorch | [
"45db6f990aad49fc218089f59500364b83cd3f79"
]
| [
"demo.py"
]
| [
"import argparse\nimport scipy.io\nimport torch\nimport numpy as np\nimport os\nfrom torchvision import datasets\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport subprocess\n#######################################################################\n# Evaluate\nparser = argparse.ArgumentParser(description='Demo')\nparser.add_argument('--query_index', default=777, type=int, help='test_image_index')\nparser.add_argument('--test_dir',default='./data/Market/pytorch',type=str, help='./test_data')\nopts = parser.parse_args()\n\ndata_dir = opts.test_dir\nimage_datasets = {x: datasets.ImageFolder( os.path.join(data_dir,x) ) for x in ['gallery','query']}\n\n#####################################################################\n#Show result\ndef imshow(path, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n im = plt.imread(path)\n plt.imshow(im)\n if title is not None:\n plt.title(title)\n plt.pause(0.001) # pause a bit so that plots are updated\n\n######################################################################\n# result = scipy.io.loadmat('pytorch_result.mat')\nresult = scipy.io.loadmat('test1_20190820_pytorch_result.mat')\nquery_feature = torch.FloatTensor(result['query_f'])\nquery_cam = result['query_cam'][0]\nquery_label = result['query_label'][0]\ngallery_feature = torch.FloatTensor(result['gallery_f'])\ngallery_cam = result['gallery_cam'][0]\ngallery_label = result['gallery_label'][0]\n\nmulti = os.path.isfile('multi_query.mat')\n\nif multi:\n m_result = scipy.io.loadmat('multi_query.mat')\n mquery_feature = torch.FloatTensor(m_result['mquery_f'])\n mquery_cam = m_result['mquery_cam'][0]\n mquery_label = m_result['mquery_label'][0]\n mquery_feature = mquery_feature.cuda()\n\nquery_feature = query_feature.cuda()\ngallery_feature = gallery_feature.cuda()\n\n#######################################################################\n# sort the images\ndef sort_img(qf, ql, qc, gf, gl, gc):\n query = qf.view(-1,1)\n # print(query.shape)\n score = torch.mm(gf,query)\n score = score.squeeze(1).cpu()\n score = score.numpy()\n # predict index\n index = np.argsort(score) #from small to large\n index = index[::-1]\n # index = index[0:2000]\n # good index\n query_index = np.argwhere(gl==ql)\n #same camera\n camera_index = np.argwhere(gc==qc)\n\n #good_index = np.setdiff1d(query_index, camera_index, assume_unique=True)\n junk_index1 = np.argwhere(gl==-1)\n junk_index2 = np.intersect1d(query_index, camera_index)\n junk_index = np.append(junk_index2, junk_index1) \n\n mask = np.in1d(index, junk_index, invert=True)\n index = index[mask]\n return index\n\n\n\n# max_i = opts.query_index\n\ni = opts.query_index\nindex = sort_img(query_feature[i],query_label[i],query_cam[i],gallery_feature,gallery_label,gallery_cam)\n\n########################################################################\n# Visualize the rank result\n\nquery_path, _ = image_datasets['query'].imgs[i]\nquery_label = query_label[i]\nprint(query_path)\nprint('Top 10 images are as follow:')\ntry: # Visualize Ranking Result \n # Graphical User Interface is needed\n fig = plt.figure(figsize=(16,4))\n ax = plt.subplot(1,11,1)\n ax.axis('off')\n imshow(query_path,'query')\n for i in range(10):\n ax = plt.subplot(1,11,i+2)\n ax.axis('off')\n img_path, _ = image_datasets['gallery'].imgs[index[i]]\n label = gallery_label[index[i]]\n imshow(img_path)\n if label == query_label:\n ax.set_title('%d'%(i+1), color='green')\n else:\n ax.set_title('%d'%(i+1), color='red')\n print(img_path)\nexcept RuntimeError:\n for i in range(10):\n img_path = image_datasets.imgs[index[i]]\n print(img_path[0])\n print('If you want to see the visualization of the ranking result, graphical user interface is needed.')\n\ndemo_dir = \"demo_results\"\nquery_dir = os.path.join(demo_dir, query_label)\nsubprocess.call([\"mkdir\", \"-p\", query_dir]);\nresult_path = os.path.join(query_dir, query_index+\".png\")\n\nfig.savefig(result_path)\n"
]
| [
[
"matplotlib.use",
"numpy.append",
"matplotlib.pyplot.subplot",
"torch.FloatTensor",
"matplotlib.pyplot.title",
"torch.mm",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.pause",
"numpy.argsort",
"numpy.argwhere",
"numpy.intersect1d",
"numpy.in1d",
"matplotlib.pyplot.imread",
"matplotlib.pyplot.imshow"
]
]
|
Timothy102/Brain-FMRI | [
"25ae74d4537c698930db455ccf494454f7f3d542"
]
| [
"visualize.py"
]
| [
"import torch\nimport os\nimport sys\nimport cv2\nimport shutil\nimport matplotlib.pyplot as plt\n\nfrom torch.cuda import init\n\nfrom Code.utils.initialize import initfolder \nfrom Code.utils.data_loader import transformation\n\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--entry_path\", type=str, default= PATH,\n help=\"File path to the folder containing the data\")\n parser.add_argument(\"--model_path\", type = str, default = SAVED_MODEL_PATH,\n help = \"Folder path containing the model (pth)\")\n parser.add_argument(\"--store_path\", type = str, default = VIS_PATH,\n help = \"Set the root path to store the brain segmentations\")\n args = parser.parse_args()\n initfolder(args.entry_path), initfolder(args.store_path)\n \n return args\n\ndef restore_model(path):\n model = att_autoencoder().to(device)\n model.load_state_dict(torch.load(path))\n model.eval()\n return model\n\ndef visualize(model, entry_path, store_path):\n f = cv2.imread(entry_path)\n f = transformation(f)\n segmented = model(f)\n\n plt.plot(segmented)\n plt.show()\n cv2.imwrite(store_path, segmented)\n shutil.rmtree(store_path)\n\n\ndef main(args = sys.argv[1:]):\n args = parseArguments()\n model = restore_model(args.model_path)\n visualize(model, args.entry_path, args.store)\n \nif __name__ == '__main__':\n main()"
]
| [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"torch.load"
]
]
|
heholek/librephotos | [
"4f41a61d9685a3165c857b695a2440895d8746dd"
]
| [
"api/places365/places365.py"
]
| [
"# PlacesCNN to predict the scene category, attribute, and class activation map in a single pass\n# by Bolei Zhou, sep 2, 2017\n# last modified date: Dec. 27, 2017, migrating everything to python36 and latest pytorch and torchvision\nimport os\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.autograd import Variable as V\nfrom torch.nn import functional as F\nfrom torchvision import transforms as trn\n\nimport ownphotos.settings\nimport wideresnet\nfrom api.util import logger\n\n# import warnings\n\ntorch.nn.Module.dump_patches = True\ndir_places365_model = ownphotos.settings.PLACES365_ROOT\n\n\nclass Places365:\n labels_and_model_are_load = False\n\n def unload(self):\n self.model = None\n self.classes = None\n self.W_attribute = None\n self.labels_IO = None\n self.labels_attribute = None\n self.labels_and_model_are_load = False\n\n def load(self):\n self.load_model()\n self.load_labels()\n self.labels_and_model_are_load = True\n\n def load_model(self):\n # this model has a last conv feature map as 14x14\n def hook_feature(module, input, output):\n self.features_blobs.append(np.squeeze(output.data.cpu().numpy()))\n\n model_file = os.path.join(dir_places365_model, \"wideresnet18_places365.pth.tar\")\n self.model = wideresnet.resnet18(num_classes=365)\n checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage)\n state_dict = {\n str.replace(k, \"module.\", \"\"): v\n for k, v in checkpoint[\"state_dict\"].items()\n }\n self.model.load_state_dict(state_dict)\n self.model.eval()\n # hook the feature extractor\n features_names = [\n \"layer4\",\n \"avgpool\",\n ] # this is the last conv layer of the resnet\n for name in features_names:\n self.model._modules.get(name).register_forward_hook(hook_feature)\n\n def load_labels(self):\n # prepare all the labels\n # scene category relevant\n file_path_category = os.path.join(\n dir_places365_model, \"categories_places365.txt\"\n )\n self.classes = list()\n with open(file_path_category) as class_file:\n for line in class_file:\n self.classes.append(line.strip().split(\" \")[0][3:])\n self.classes = tuple(self.classes)\n\n # indoor and outdoor relevant\n file_path_IO = os.path.join(dir_places365_model, \"IO_places365.txt\")\n with open(file_path_IO) as f:\n lines = f.readlines()\n self.labels_IO = []\n for line in lines:\n items = line.rstrip().split()\n self.labels_IO.append(int(items[-1]) - 1) # 0 is indoor, 1 is outdoor\n self.labels_IO = np.array(self.labels_IO)\n\n # scene attribute relevant\n file_path_attribute = os.path.join(\n dir_places365_model, \"labels_sunattribute.txt\"\n )\n with open(file_path_attribute) as f:\n lines = f.readlines()\n self.labels_attribute = [item.rstrip() for item in lines]\n\n file_path_W = os.path.join(\n dir_places365_model, \"W_sceneattribute_wideresnet18.npy\"\n )\n self.W_attribute = np.load(file_path_W)\n self.labels_are_load = True\n\n def returnTF(self):\n # load the image transformer\n tf = trn.Compose(\n [\n trn.Resize((224, 224)),\n trn.ToTensor(),\n trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n return tf\n\n def remove_nonspace_separators(self, text):\n return \" \".join(\" \".join(\" \".join(text.split(\"_\")).split(\"/\")).split(\"-\"))\n\n def inference_places365(self, img_path, confidence):\n \"\"\"\n @param img_path: path to the image to generate labels from\n @param confidence: minimum confidence before an category is selected\n @return: {'environment': 'indoor'/'outdoor', 'categories': [...], 'attributes': [...]}\n \"\"\"\n try:\n if not self.labels_and_model_are_load:\n self.load()\n\n # load the model\n self.features_blobs = []\n\n # load the transformer\n tf = self.returnTF() # image transformer\n\n # get the softmax weight\n params = list(self.model.parameters())\n weight_softmax = params[-2].data.numpy()\n weight_softmax[weight_softmax < 0] = 0\n\n # load the test image\n # img_url = 'http://places2.csail.mit.edu/imgs/3.jpg'\n # os.system('wget %s -q -O test.jpg' % img_url)\n img = Image.open(img_path)\n # Normalize the image for processing\n input_img = V(tf(img).unsqueeze(0))\n\n # forward pass\n logit = self.model.forward(input_img)\n h_x = F.softmax(logit, 1).data.squeeze()\n probs, idx = h_x.sort(0, True)\n probs = probs.numpy()\n idx = idx.numpy()\n\n res = {}\n\n # output the IO prediction\n # labels_IO[idx[:10]] returns a list of 0's and 1's: 0 -> inside, 1 -> outside\n # Determine the mean to reach a consensus\n io_image = np.mean(self.labels_IO[idx[:10]])\n if io_image < 0.5:\n res[\"environment\"] = \"indoor\"\n else:\n res[\"environment\"] = \"outdoor\"\n\n # output the prediction of scene category\n # idx[i] returns a index number for which class it corresponds to\n # classes[idx[i]], thus returns the class name\n # idx is sorted together with probs, with highest probabilities first\n res[\"categories\"] = []\n for i in range(0, 5):\n if probs[i] > confidence:\n res[\"categories\"].append(\n self.remove_nonspace_separators(self.classes[idx[i]])\n )\n else:\n break\n # TODO Should be replaced with more meaningful tags in the future\n # output the scene attributes\n # This is something I don't quiet grasp yet\n # Probs is not usable here anymore, we're not processing our input_image\n # Take the dot product of out W_attribute model and the feature blobs\n # And sort it along the -1 axis\n # This results in idx_a, with the last elements the index numbers of attributes, we have the most confidence in\n # Can't seem to get any confidence values, also all the attributes it detect are not really meaningful i.m.o.\n responses_attribute = self.W_attribute.dot(self.features_blobs[1])\n idx_a = np.argsort(responses_attribute)\n res[\"attributes\"] = []\n for i in range(-1, -10, -1):\n res[\"attributes\"].append(\n self.remove_nonspace_separators(self.labels_attribute[idx_a[i]])\n )\n\n return res\n except Exception:\n logger.exception(\"Error:\")\n\n\nplace365_instance = Places365()\n"
]
| [
[
"numpy.array",
"torch.nn.functional.softmax",
"numpy.load",
"numpy.mean",
"numpy.argsort",
"torch.load"
]
]
|
tomash1234/robot-arm-filler | [
"ebce0d7a89c2512d3672522227c53d1a7ef6f74d"
]
| [
"python/arm_controller.py"
]
| [
"\"\"\"\nArm Controller Module\n\n This module contains classes to communication with the board and basic inverse kinematics.\n\n https://github.com/tomash1234/robot-arm-filler\n\"\"\"\n\nimport socket\nimport numpy as np\n\nfrom kinematics import Kinematics\n\n\"\"\" Servo motors indexes \"\"\"\nSERVO_BASE = 0\nSERVO_SHOULDER = 1\nSERVO_ELBOW = 2\n\n\nclass ArmCommunicator:\n \"\"\" Arm Communicator allows to send UDP packets to the board.\n\n Attributes:\n address: string, IP address of the board\n port: integer, board port for communication\n address2: string, IP address of the second board (pump controller)\n port2: integer, board port for communication with the second board (pump controller)\n\n socket: socket for UPD communication\n \"\"\"\n\n def __init__(self, ip_address, port=5051):\n \"\"\" Inits the instance with ip address of board and its port\"\"\"\n self.address = ip_address\n self.port = port\n self.address2 = None\n self.port2 = None\n\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n def set_pump_ip(self, ip_address, port=5051):\n \"\"\"Sets the second board (pump controller) address and its port\"\"\"\n self.address2 = ip_address\n self.port2 = port\n\n def send_pump(self, on):\n \"\"\"Starts / Stops pump. Sends UDP packet to the second board\n Args:\n on: boolean, True turns the pump on and False turns it off\n \"\"\"\n if self.address2 is None:\n return\n mes = [255 if on else 0]\n print(mes, self.address2, self.port2)\n self.socket.sendto(bytes(mes), (self.address2, self.port2))\n\n def send_angles(self, angles):\n \"\"\"Sends all angles to the board which should set the servos\n to the specific angles. Angles are in degrees in the range [0, 255]\n\n Args:\n angles: list of 3 integers, [base angle, shoulder angle, elbow angle] in degrees\n \"\"\"\n self.send_packet(angles)\n\n def send_packet(self, message):\n \"\"\"Sends message to the first board (address and port from contractor)\n Args:\n message: list of byte values\n \"\"\"\n self.socket.sendto(bytes(message), (self.address, self.port))\n\n\ndef find_circles_interceptions(c1, r1, c2, r2):\n \"\"\"Finds interceptions of two circles.\n\n Args:\n c1: center of the first circle (x, y)\n r1: float, radius of the first circle\n c2: center of the second circle (x, y)\n r2: float, radius of the second circle\n\n Returns:\n list of interceptions or None if there is no interceptions\n\n \"\"\"\n R = np.linalg.norm(c2 - c1)\n if R > r1 + r2:\n return None\n f = (c1 + c2) / 2\n diff = c1 - c2\n\n res = f + (c2 - c1) * (r1 ** 2 - r2 ** 2) / (2 * R ** 2)\n g = (R + r1 + r2) * (R + r1 - r2) * (R - r1 + r2) * (- R + r1 + r2)\n if g < 0:\n return None\n e = 0.25 * np.sqrt(g)\n t = 2 * e * (np.array([diff[1], diff[0]])) / R ** 2\n\n inters = [[res[0] - t[0], res[1] + t[1]], [res[0] + t[0], res[1] - t[1]]]\n\n return inters\n\n\ndef angles_bet_vec(u, v):\n \"\"\"Find signed angle between two vectors\n Args:\n u: vector 1\n v: vector 2\n\n Returns:\n float, signed angle in radians\n\n \"\"\"\n if u[1] - v[1] == 0:\n sign = 1\n else:\n sign = (v[1] - u[1]) / np.abs(v[1] - u[1])\n c = np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))\n return sign * np.arccos(c)\n\n\ndef convert_point_2_local_slice(point, cor_angle):\n r = 1 * (point[0] ** 2 + point[2] ** 2) ** 0.5\n return np.array([r - np.cos(np.deg2rad(cor_angle)), point[1]])\n\n\ndef convert_local_slice_2_point(raw_angle, x, y):\n new_point = np.array([x * np.cos(np.deg2rad(raw_angle)), y,\n -x * np.sin(np.deg2rad(raw_angle))])\n return new_point\n\n\nclass ArmDriver:\n\n \"\"\" Arm Driver class implements basic inverse kinematics function\n and also calculates position of arm end based on given angles.\n\n Attributes:\n dim: ArmDimensions, dimensions of arm\n kim: Kinematics, instance of kinematics class\n \"\"\"\n\n def __init__(self, dimensions):\n \"\"\"Inits Arm Driver instance from given dimensions\"\"\"\n self.dim = dimensions\n self.kim = Kinematics(dimensions)\n\n def find_valid_angle(self, interceptions, point, shoulder, base_angle):\n if not self.dim.get_joint(0).is_valid_angle(base_angle):\n print('No valid angles b')\n return None\n\n arm = [interceptions[0] - shoulder[0:2], interceptions[1] - shoulder[0:2]]\n shoulder_angles = [angles_bet_vec(np.array([1, 0]), arm[0]), angles_bet_vec(np.array([1, 0]), arm[1])]\n shoulder_angles_deg = np.rad2deg(shoulder_angles - self.dim.shoulder_corr_angle)\n\n valid_indexes = [1, 0]\n # Check if angle is invalid\n shoulder_valid = []\n for i in valid_indexes:\n if self.dim.get_joint(1).is_valid_angle(shoulder_angles_deg[i]):\n shoulder_valid.append(i)\n\n if len(valid_indexes) == 0:\n print('No valid angles s')\n return None\n\n forearm = [point[:2] - interceptions[0], point[:2] - interceptions[1]]\n elbow_angles = [angles_bet_vec(arm[0], forearm[0]), angles_bet_vec(arm[1], forearm[1])]\n elbow_angles_deg = np.rad2deg(elbow_angles)\n\n all_valid = []\n for i in shoulder_valid:\n if self.dim.get_joint(2).is_valid_angle(elbow_angles_deg[i]):\n all_valid.append(i)\n\n if len(all_valid) == 0:\n print('No valid angles e')\n return None\n\n chosen_index = all_valid[0]\n return base_angle, shoulder_angles_deg[chosen_index], elbow_angles_deg[chosen_index], interceptions[\n chosen_index]\n\n def get_points(self, angles):\n \"\"\"Returns the list of 3D points corresponding with\n shoulder position, end of arm, elbow position and tip of roboarm\n Args:\n angles: list of 3 angles in degress [base_angle, shoulder angle, elbow angle]\n Returns:\n list of 3D position of shoulder pos, arm end, elbow and end of roboarm\n \"\"\"\n base = np.deg2rad(angles[0])\n shoulder = np.deg2rad(angles[1])\n elbow = np.deg2rad(angles[2])\n return self.kim.calculate(base, shoulder, elbow)\n\n def find_base_rotation(self, point):\n \"\"\"Find angle of base servo to reach point\n Args:\n point: destination point\n Returns:\n angle in degrees with and without correction\n (angle + correction, angle)\n \"\"\"\n point2d = np.array([point[0], point[2]])\n dis_x = self.dim.shoulder_h_o + self.dim.elbow_h_o\n correction_angle = np.arctan(dis_x / np.linalg.norm(point2d))\n angle = np.arctan2(-point[2], point[0])\n deg = np.rad2deg(angle + correction_angle)\n return deg, np.rad2deg(angle)\n\n def find_angles_with_threshold(self, point, threshold_y):\n \"\"\"Find all 3 angles to reach destination point but allows threshold in y axis\n Args:\n point: (x, y, z) destination point\n threshold_y: float, threshold in y axis\n Returns:\n Dictionary where the keys are angles, shoulder, raw_angle and values are the angles,\n shoulder position and raw angle withou correction\n \"\"\"\n ret = self.find_angles(point)\n if ret is None:\n p = (point[0], point[1] - threshold_y, point[2])\n ret = self.find_angles(p)\n\n if ret is None:\n p = (point[0], point[1] + threshold_y, point[2])\n ret = self.find_angles(p)\n\n return ret\n\n def find_angles(self, point):\n \"\"\"Finds angles for all 3 servos to reach the destination point\n Args:\n point: (x, y, z) destination point\n Returns:\n Dictionary where keys are angles, shoulder, raw_angle and values\n are a list of angles in degrees, shoulder position (x, y, z) and angle without correction\n\n \"\"\"\n base_angle, raw_angle = self.find_base_rotation(point)\n shoulder_pos = self.kim.calculate_shoulder_pos(base_angle, 'xy')\n\n projected_start = np.array([self.dim.shoulder_o, self.dim.base_h])\n projected_point = convert_point_2_local_slice(point, base_angle - raw_angle)\n interceptions = find_circles_interceptions(projected_start,\n self.dim.arm_radius,\n projected_point, self.dim.elbow_l)\n\n if interceptions is None:\n print('Un reachable point |')\n return None\n\n ret = self.find_valid_angle(interceptions, projected_point, projected_start, base_angle)\n if ret is None:\n print('Un reachable point')\n return None\n angles = ret[:3]\n\n print('Found', angles)\n ret = {'angles': angles, 'shoulder': shoulder_pos, 'raw_base': raw_angle}\n return ret\n\n def convert_angles(self, angles):\n \"\"\"Converts angles to angles ready to send into the board\n Args:\n angles: list of 3 float angles in degrees\n Returns:\n list of integer angles ready for the board\n \"\"\"\n base = self.dim.get_joint(0).convert_angle(angles[0])\n shoulder = self.dim.get_joint(1).convert_angle(angles[1])\n elbow = self.dim.get_joint(2).convert_angle(angles[2])\n return [int(base), int(shoulder), int(elbow)]\n"
]
| [
[
"numpy.array",
"numpy.arccos",
"numpy.linalg.norm",
"numpy.dot",
"numpy.rad2deg",
"numpy.arctan2",
"numpy.sqrt",
"numpy.abs",
"numpy.deg2rad"
]
]
|
Grayson-Orr/grade-pdf-generator | [
"17279281a70c015fd4e7950741495b415883174c"
]
| [
"graphs/checkpoint_graph.py"
]
| [
"import sys\nimport json\nimport matplotlib.pyplot as plt\n\n\ndef label(bar):\n for b in bar:\n height = b.get_height()\n plt.text(b.get_x() + b.get_width() / 2, height,\n height, ha='center', va='bottom')\n\n\njson_input = sys.argv[1]\nstdnt_cp_total = []\ntitle = {'prog-four-grades.json': ['Programming 4', 'prog-four', 23, 17],\n 'web-one-grades.json': ['Web 1', 'web-one', 11, 37]}\n\nwith open(f'../json/{json_input}', 'r') as f:\n data = json.load(f)\n\n for idx in range(1, title[json_input][2]):\n total = 0\n for d in range(len(data)):\n total += int(data[d]['checkpoint' + str(idx)])\n stdnt_cp_total.append(total)\n\nnum_of_cps = tuple(idx for idx in range(1, title[json_input][2]))\nplt.figure(figsize=(6, 6))\nplt.title(f'{title[json_input][0]} - Completed Checkpoints')\nlabel(plt.bar(num_of_cps, stdnt_cp_total, align='center', color='r'))\nplt.xticks(num_of_cps)\nplt.yticks(tuple(idx for idx in range(1, title[json_input][3], 2)))\nplt.xlabel('Checkpoint')\nplt.ylabel('No. of students')\nplt.savefig(f'../public/img/{title[json_input][1]}-cp-completion.png')\n"
]
| [
[
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xticks"
]
]
|
AlanJie/Spders | [
"f1324a948b4753dfdc2d69acc49639373b36852d"
]
| [
"apple/visualize.py"
]
| [
"import jieba\nfrom PIL import Image\nimport numpy as np\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\nMASK_IMG = 'apple.jpg'\nFONT_PATH = 'font/simsun.ttc'\nFILE_PATH = 'comments.txt'\n\ndef cut_word():\n with open(FILE_PATH, encoding='utf8') as f:\n comments = f.read()\n word_list = jieba.cut(comments, cut_all=True)\n wl = \" \".join(word_list)\n print(wl)\n return wl\n\ndef create_word_cloud():\n img_mask = np.array(Image.open(MASK_IMG))\n wc = WordCloud(background_color='white', max_words=2000, mask=img_mask,\n scale=4, max_font_size=50, random_state=2019, font_path=FONT_PATH)\n\n wc.generate(cut_word())\n plt.axis('off')\n plt.imshow(wc, interpolation='bilinear')\n plt.savefig('apple_wc.jpg')\n plt.show()\n\nif __name__ == '__main__':\n create_word_cloud()\n"
]
| [
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.imshow"
]
]
|
luoxier/CycleGAN_Tensorlayer | [
"38faad7ea1e0657e2570caa1d928d71182521535"
]
| [
"main.py"
]
| [
"import os\nimport pprint\nimport numpy as np\nimport tensorflow as tf\nimport tensorlayer as tl\nfrom tensorlayer.layers import *\nfrom tensorlayer.prepro import *\nfrom random import shuffle\n# from model_upsampling import *\nfrom model_deconv import *\n\nimport argparse\nfrom collections import namedtuple\n\npp = pprint.PrettyPrinter()\nflags = tf.app.flags\nflags.DEFINE_integer(\"epoch\", 200, \"Epoch to train [100]\")\nflags.DEFINE_float(\"learning_rate\", 0.0002, \"Learning rate of for adam [0.0002]\")\nflags.DEFINE_float(\"beta1\", 0.5, \"Momentum term of adam [0.5]\")\nflags.DEFINE_float(\"weight_decay\", 1e-5, \"Weight decay for l2 loss\")\nflags.DEFINE_float(\"pool_size\", 50, 'size of image buffer that stores previously generated images, default: 50')\nflags.DEFINE_integer(\"train_size\", np.inf, \"The size of train images [np.inf]\")\nflags.DEFINE_integer(\"batch_size\", 1, \"The number of batch images [1] if we use InstanceNormLayer !\")\nflags.DEFINE_integer(\"image_size\", 256, \"The size of image to use (will be center cropped) [256]\")\nflags.DEFINE_integer(\"gf_dim\", 32, \"Size of generator filters in first layer\")\nflags.DEFINE_integer(\"df_dim\", 64, \"Size of discriminator filters in first layer\")\n# flags.DEFINE_integer(\"class_embedding_size\", 5, \"Size of class embedding\")\nflags.DEFINE_integer(\"output_size\", 256, \"The size of the output images to produce [64]\")\nflags.DEFINE_integer(\"sample_size\", 64, \"The number of sample images [64]\")\nflags.DEFINE_integer(\"c_dim\", 3, \"Dimension of image color. [3]\")\nflags.DEFINE_integer(\"sample_step\", 500, \"The interval of generating sample. [500]\")\nflags.DEFINE_integer(\"save_step\", 200, \"The interval of saveing checkpoints. [200]\")\nflags.DEFINE_string(\"dataset_dir\", \"horse2zebra\", \"The name of dataset [horse2zebra, apple2orange, sunflower2daisy and etc]\")\nflags.DEFINE_string(\"checkpoint_dir\", \"checkpoint\", \"Directory name to save the checkpoints [checkpoint]\")\nflags.DEFINE_string(\"sample_dir\", \"samples\", \"Directory name to save the image samples [samples]\")\nflags.DEFINE_string(\"direction\", \"forward\", \"The direction of generator [forward, backward]\")\nflags.DEFINE_string(\"test_dir\", \"./test\", \"The direction of test\")\nflags.DEFINE_boolean(\"is_train\", True, \"True for training, False for testing [False]\")\nflags.DEFINE_boolean(\"is_crop\", False, \"True for training, False for testing [False]\")\n# flags.DEFINE_boolean(\"visualize\", False, \"True for visualizing, False for nothing [False]\")\nFLAGS = flags.FLAGS\n\nsess = tf.Session()\n\nni = int(np.sqrt(FLAGS.batch_size))\n\ndef train_cyclegan():\n lamda = 10\n # num_fake = 0\n\n ni = int(np.sqrt(FLAGS.batch_size))\n h, w = 256, 256\n\n ## data augmentation\n def prepro(x):\n x = tl.prepro.flip_axis(x, axis=1, is_random=True)\n x = tl.prepro.rotation(x, rg=16, is_random=True, fill_mode='nearest')\n x = tl.prepro.imresize(x, size=[int(h * 1.2), int(w * 1.2)], interp='bicubic', mode=None)\n x = tl.prepro.crop(x, wrg=h, hrg=w, is_random=True)\n x = x / (255. / 2.)\n x = x - 1.\n return x\n\n def rescale(x):\n x = x / (255. / 2.)\n x = x - 1.\n return x\n\n real_A = tf.placeholder(tf.float32, [None, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='real_A')\n real_B = tf.placeholder(tf.float32, [None, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='real_B')\n fake_A_pool = tf.placeholder(tf.float32, [FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='fake_A')\n fake_B_pool = tf.placeholder(tf.float32, [FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='fake_B')\n\n gen_B, gen_B_out = cyclegan_generator_resnet(real_A, 9, is_train=True, reuse=False, name='gen_A2B')\n gen_A, gen_A_out = cyclegan_generator_resnet(real_B, 9, is_train=True, reuse=False, name='gen_B2A')\n cyc_B, cyc_B_out = cyclegan_generator_resnet(gen_A_out, 9, is_train=True, reuse=True, name='gen_A2B')\n cyc_A, cyc_A_out = cyclegan_generator_resnet(gen_B_out, 9, is_train=True, reuse=True, name='gen_B2A')\n\n d_real_A, d_real_A_logits = cyclegan_discriminator_patch(real_A, is_train=True, reuse=False, name='dis_A') # dx\n d_real_B, d_real_B_logits = cyclegan_discriminator_patch(real_B, is_train=True, reuse=False, name='dis_B') # dy\n d_fake_A, d_fake_A_logits = cyclegan_discriminator_patch(gen_A_out, is_train=True, reuse=True, name='dis_A') # d_fy\n d_fake_B, d_fake_B_logits = cyclegan_discriminator_patch(gen_B_out, is_train=True, reuse=True, name='dis_B') # d_gx\n\n d_A_pool, d_A_pool_logits = cyclegan_discriminator_patch(fake_A_pool, is_train=True, reuse=True, name='dis_A') # d_fakex\n d_B_pool, d_B_pool_logits = cyclegan_discriminator_patch(fake_B_pool, is_train=True, reuse=True, name='dis_B') # d_fakey\n\n ## test inference\n # gen_B_test, gen_B_test_logits = cyclegan_generator_resnet(real_A, 9, is_train=False, reuse=True, name='gen_A2B')\n # gen_A_test, gen_A_test_logits = cyclegan_generator_resnet(real_B, 9, is_train=False, reuse=True, name='gen_B2A')\n\n ## calculate cycle loss\n cyc_loss = tf.reduce_mean(tf.abs(cyc_A_out - real_A)) + tf.reduce_mean(tf.abs(cyc_B_out - real_B))\n # cyc_loss = tf.reduce_mean(tf.reduce_mean(tf.abs(cyc_A - real_A), [1, 2, 3])) + tf.reduce_mean(\n # tf.reduce_mean(tf.abs(cyc_B - real_B), [1, 2, 3]))\n\n ## calculate adversial loss\n g_loss_A2B = tf.reduce_mean(tf.squared_difference(d_fake_B_logits, tf.ones_like(d_fake_B_logits)), name='g_loss_b')\n # g_loss_A2B = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(d_fake_B, tf.ones_like(d_fake_B)), [1, 2, 3]), name='g_loss_b')\n\n g_loss_B2A = tf.reduce_mean(tf.squared_difference(d_fake_A_logits, tf.ones_like(d_fake_A_logits)),name='g_loss_a')\n # g_loss_B2A = tf.reduce_mean(tf.reduce_mean(tf.squared_difference(d_fake_A, tf.ones_like(d_fake_A)), [1, 2, 3]), name='g_loss_a')\n\n ## calculate totalloss of generator\n g_a2b_loss = lamda * cyc_loss + g_loss_A2B # forward\n g_b2a_loss = lamda * cyc_loss + g_loss_B2A # backward\n\n ## calculate discriminator loss\n d_a_loss = (tf.reduce_mean(tf.squared_difference(d_real_A_logits, tf.ones_like(d_real_A_logits))) + tf.reduce_mean(tf.square(d_fake_A_logits))) / 2.0\n # d_a_loss = (tf.reduce_mean(\n # tf.reduce_mean(tf.squared_difference(d_real_A, tf.ones_like(d_real_A)), [1, 2, 3])) + tf.reduce_mean(\n # tf.reduce_mean(tf.square(d_fake_A), [1, 2, 3]))) / 2.0\n d_b_loss = (tf.reduce_mean(tf.squared_difference(d_real_B_logits, tf.ones_like(d_real_B_logits))) + tf.reduce_mean(tf.square(d_fake_B_logits))) / 2.0\n # d_b_loss = (tf.reduce_mean(\n # tf.reduce_mean(tf.squared_difference(d_real_B, tf.ones_like(d_real_B)), [1, 2, 3])) + tf.reduce_mean(\n # tf.reduce_mean(tf.square(d_fake_B), [1, 2, 3]))) / 2.0\n\n # t_vars = tf.trainable_variables()\n\n g_A2B_vars = tl.layers.get_variables_with_name('gen_A2B', True, True)\n g_B2A_vars = tl.layers.get_variables_with_name('gen_B2A', True, True)\n d_A_vars = tl.layers.get_variables_with_name('dis_A', True, True)\n d_B_vars = tl.layers.get_variables_with_name('dis_B', True, True)\n\n # with tf.device('/gpu:0'):\n with tf.variable_scope('learning_rate'):\n lr_v = tf.Variable(FLAGS.learning_rate, trainable=False)\n g_a2b_optim = tf.train.AdamOptimizer(lr_v, beta1=FLAGS.beta1).minimize(g_a2b_loss, var_list=g_A2B_vars)\n g_b2a_optim = tf.train.AdamOptimizer(lr_v, beta1=FLAGS.beta1).minimize(g_b2a_loss, var_list=g_B2A_vars)\n d_a_optim = tf.train.AdamOptimizer(lr_v, beta1=FLAGS.beta1).minimize(d_a_loss, var_list=d_A_vars)\n d_b_optim = tf.train.AdamOptimizer(lr_v, beta1=FLAGS.beta1).minimize(d_b_loss, var_list=d_B_vars)\n\n ## init params\n tl.layers.initialize_global_variables(sess)\n\n net_g_A2B_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_g_A2B.npz'.format(FLAGS.dataset_dir))\n net_g_B2A_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_g_B2A.npz'.format(FLAGS.dataset_dir))\n net_d_A_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_d_A.npz'.format(FLAGS.dataset_dir))\n net_d_B_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_d_B.npz'.format(FLAGS.dataset_dir))\n\n tl.files.load_and_assign_npz(sess=sess, name=net_g_A2B_name, network=gen_B)\n tl.files.load_and_assign_npz(sess=sess, name=net_g_B2A_name, network=gen_A)\n tl.files.load_and_assign_npz(sess=sess, name=net_d_A_name, network=d_fake_A)\n tl.files.load_and_assign_npz(sess=sess, name=net_d_B_name, network=d_fake_B)\n\n ##========================= TRAIN MODELS ================================##\n iter_counter = 1\n start_time = time.time()\n\n dataA, dataB, im_test_A, im_test_B = tl.files.load_cyclegan_dataset(filename=FLAGS.dataset_dir, path='datasets')\n\n sample_A = np.asarray(dataA[0: 16])\n sample_B = np.asarray(dataB[0: 16])\n sample_A = tl.prepro.threading_data(sample_A, fn=rescale)\n sample_B = tl.prepro.threading_data(sample_B, fn=rescale)\n\n tl.vis.save_images(sample_A, [4, 4], './{}/sample_A.jpg'.format(FLAGS.sample_dir))\n tl.vis.save_images(sample_B, [4, 4], './{}/sample_B.jpg'.format(FLAGS.sample_dir))\n\n shuffle(dataA)\n shuffle(dataB)\n\n for epoch in range(FLAGS.epoch):\n ## change learning rate\n if epoch >= 100:\n new_lr = FLAGS.learning_rate - FLAGS.learning_rate * (epoch - 100) / 100\n sess.run(tf.assign(lr_v, new_lr))\n print(\"New learning rate %f\" % new_lr)\n\n batch_idxs = min(min(len(dataA), len(dataB)), FLAGS.train_size) // FLAGS.batch_size\n for idx in range(0, batch_idxs):\n batch_imgA = tl.prepro.threading_data(dataA[idx * FLAGS.batch_size:(idx + 1) * FLAGS.batch_size], fn=prepro)\n batch_imgB = tl.prepro.threading_data(dataB[idx * FLAGS.batch_size:(idx + 1) * FLAGS.batch_size], fn=prepro)\n\n gen_A_temp_out, gen_B_temp_out = sess.run([gen_A_out, gen_B_out],\n feed_dict={real_A: batch_imgA, real_B: batch_imgB})\n\n ## update forward network\n _, errGA2B = sess.run([g_a2b_optim, g_a2b_loss],\n feed_dict={real_A: batch_imgA, real_B: batch_imgB})\n ## update DB network\n _, errDB = sess.run([d_b_optim, d_b_loss],\n feed_dict={real_A: batch_imgA, real_B: batch_imgB, fake_B_pool: gen_B_temp_out})\n ## update (backword) network\n _, errGB2A = sess.run([g_b2a_optim, g_b2a_loss],\n feed_dict={real_A: batch_imgA, real_B: batch_imgB})\n ## update DA network\n _, errDA = sess.run([d_a_optim, d_a_loss],\n feed_dict={real_A: batch_imgA, real_B: batch_imgB, fake_A_pool: gen_A_temp_out})\n\n print(\"Epoch: [%2d/%2d] [%4d/%4d] time: %4.4fs, d_a_loss: %.8f, d_b_loss: %.8f, g_a2b_loss: %.8f, g_b2a_loss: %.8f\" \\\n % (epoch, FLAGS.epoch, idx, batch_idxs, time.time() - start_time, errDA, errDB, errGA2B, errGB2A))\n\n iter_counter += 1\n # num_fake += 1\n\n if np.mod(iter_counter, 500) == 0:\n oA, oB = sess.run([gen_A_out, gen_B_out],\n feed_dict={real_A: sample_A, real_B: sample_B})\n tl.vis.save_images(oA, [4, 4],\n './{}/B2A_{:02d}_{:04d}.jpg'.format(FLAGS.sample_dir, epoch, idx))\n print(\"save image gen_A, Epoch: %2d idx:%4d\" % (epoch, idx))\n tl.vis.save_images(oB, [4, 4],\n './{}/A2B_{:02d}_{:04d}.jpg'.format(FLAGS.sample_dir, epoch, idx))\n print(\"save image gen_B, Epoch: %2d idx:%4d\" % (epoch, idx))\n\n if (epoch != 0) and (epoch % 10) == 0:\n tl.files.save_npz(gen_B.all_params, name=net_g_A2B_name, sess=sess)\n tl.files.save_npz(gen_A.all_params, name=net_g_B2A_name, sess=sess)\n tl.files.save_npz(d_fake_A.all_params, name=net_d_A_name, sess=sess)\n tl.files.save_npz(d_fake_B.all_params, name=net_d_B_name, sess=sess)\n print(\"[*] Save checkpoints SUCCESS!\")\n\n\ndef test_cyclegan():\n \"\"\"Test cyclegan\"\"\"\n\n def pro(x):\n x = x / (255. / 2.)\n x = x - 1.\n return x\n\n test_A = tf.placeholder(tf.float32, [FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='test_x')\n test_B = tf.placeholder(tf.float32, [FLAGS.batch_size, FLAGS.image_size, FLAGS.image_size, FLAGS.c_dim],\n name='test_y')\n # testB = cyclegan_generator_resnet(test_A, options, True, name=\"gen_forward\")\n # testA = cyclegan_generator_resnet(test_B, options, True, name=\"gen_backward\")\n test_gen_A2B, test_gen_A2B_logits = cyclegan_generator_resnet(test_A, 9, is_train=False, reuse=False, name='gen_A2B')\n test_gen_B2A, test_gen_B2A_logits = cyclegan_generator_resnet(test_B, 9, is_train=False, reuse=False, name='gen_B2A')\n\n out_var, in_var = (test_B, test_A) if FLAGS.direction == 'forward' else (test_A, test_B)\n\n sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n tl.layers.initialize_global_variables(sess)\n\n net_g_A2B_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_g_A2B.npz'.format(FLAGS.dataset_dir))\n net_g_B2A_name = os.path.join(FLAGS.checkpoint_dir, '{}_net_g_B2A.npz'.format(FLAGS.dataset_dir))\n tl.files.load_and_assign_npz(sess=sess, name=net_g_A2B_name, network=test_gen_A2B)\n tl.files.load_and_assign_npz(sess=sess, name=net_g_B2A_name, network=test_gen_B2A)\n\n dataA, dataB, im_test_A, im_test_B = tl.files.load_cyclegan_dataset(filename=FLAGS.dataset_dir, path='datasets')\n\n if FLAGS.direction == 'forward':\n sample_files = im_test_A\n net_g_logits = test_gen_A2B_logits\n\n elif FLAGS.direction == 'backward':\n sample_files = im_test_B\n net_g_logits = test_gen_B2A_logits\n else:\n raise Exception('--direction must be forward or backward')\n\n batch_idxs = (len(sample_files)) // FLAGS.batch_size\n for idx in range(0, batch_idxs):\n sample_image = threading_data(sample_files[idx * FLAGS.batch_size:(idx + 1) * FLAGS.batch_size],fn=pro)\n fake_img = sess.run(net_g_logits, feed_dict={in_var: sample_image})\n tl.vis.save_images(fake_img, [ni, ni], './{}/A2B_{}_{:04d}.jpg'.format(FLAGS.test_dir, FLAGS.direction, idx))\n\n\ndef main(_):\n parser = argparse.ArgumentParser()\n parser.add_argument('--phase', dest='phase', default='train', help='train, test')\n args = parser.parse_args()\n\n if not os.path.exists(FLAGS.checkpoint_dir):\n os.makedirs(FLAGS.checkpoint_dir)\n if not os.path.exists(FLAGS.sample_dir):\n os.makedirs(FLAGS.sample_dir)\n if not os.path.exists(FLAGS.test_dir):\n os.makedirs(FLAGS.test_dir)\n\n # if args.phase == 'train':\n # train_cyclegan()\n # elif args.phase == 'test':\n # test_cyclegan()\n train_cyclegan()\n # test_cyclegan()\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
]
| [
[
"tensorflow.abs",
"tensorflow.train.AdamOptimizer",
"numpy.asarray",
"tensorflow.assign",
"tensorflow.Session",
"tensorflow.Variable",
"tensorflow.ones_like",
"tensorflow.ConfigProto",
"tensorflow.variable_scope",
"tensorflow.placeholder",
"numpy.sqrt",
"tensorflow.app.run",
"tensorflow.square",
"numpy.mod"
]
]
|
NovaSBE-DSKC/predict-campaing-sucess-rate | [
"fec339aee7c883f55d64130eb69e490f765ee27d"
]
| [
"src/data_curation/pre_processing/country.py"
]
| [
"import pycountry\nimport numpy as np\nimport pandas as pd\nimport json\nimport settings\n\nfrom dskc import dskc_clean\n\ndef reduce_cardinality(data, colname, percentile):\n series = pd.value_counts(data[colname])\n mask = (series/series.sum() * 100).lt(percentile)\n\n return np.where(data[colname].isin(series[mask].index), 'Others', data[colname])\n\n\ndef get_countries(location):\n location = location.lower().strip()\n\n if 'moçambique' in location:\n return 'Mozambique'\n elif 'são tomé e príncipe' in location or 'são tomé e principe' in location:\n return 'Sao tome and principe'\n elif 'lisboa' in location:\n return 'Portugal'\n else:\n if ',' in location:\n city = location.split(',')[0].strip()\n location = location.split(',')[1].strip()\n\n try:\n country = pycountry.countries.lookup(location).name\n except:\n country = 'Others'\n\n if country == 'Others':\n try:\n country = pycountry.countries.search_fuzzy(location)[0].name\n except:\n try:\n country = pycountry.countries.search_fuzzy(city)[0].name\n except:\n country = 'Others'\n\n return country.capitalize()\n\n\ndef set_countries(df):\n df['COUNTRY'] = None\n df['COUNTRY'] = df.apply(lambda x: get_countries(x['LOCATION']), axis=1)\n df['COUNTRY_REDUCED'] = reduce_cardinality(df, colname='COUNTRY', percentile=0.5)\n\n countries_list = list(df[\"COUNTRY_REDUCED\"].unique())\n\n with open(settings.COUNTRIES_LIST_PATH, 'w') as f:\n json.dump(countries_list, f)\n\n df.drop('COUNTRY', axis=1, inplace=True)\n df = dskc_clean.one_hot_encode(df, \"COUNTRY_REDUCED\")\n\n return df\n"
]
| [
[
"pandas.value_counts"
]
]
|
MrXJC/deepspeech.pytorch | [
"6379c18d3f56cad8896a51d45166ea979423e0bf"
]
| [
"data/Chinese/primewords_md_2018_set1.py"
]
| [
"# -*- coding: utf-8 -*-\nimport argparse\nimport os\nimport io\nimport shutil\nimport tarfile\nimport wget\nimport pandas as pd\nfrom pypinyin import pinyin, lazy_pinyin, Style\nimport subprocess\nimport json\nDATA = 'primewords_md_2018_set1'\nDATA_URL = ''\nDATA_TGZ = DATA + '.tar.gz'\nMANIFESTS = 'manifests'\nDATA_CSV = os.path.join(MANIFESTS, DATA + '_manifest.csv')\n\nparser = argparse.ArgumentParser(description='Processes and downloads ' + DATA)\nparser.add_argument('--target-dir', default='.', help='Path to save dataset')\nargs = parser.parse_args()\n\ndef main():\n target_path = os.path.join(args.target_dir, DATA)\n if not os.path.exists(target_path):\n tar_path = os.path.join(args.target_dir, DATA_TGZ)\n if not os.path.exists(tar_path):\n wget.download(DATA_URL, out=args.target_dir)\n tar = tarfile.open(tar_path)\n tar.extractall(args.target_dir)\n if not os.path.exists(MANIFESTS):\n os.makedirs(MANIFESTS)\n prefix = len(args.target_dir) if args.target_dir[-1] == '/' or args.target_dir[-1] == '\\\\' else len(args.target_dir) + 1\n data_path = os.path.join(target_path, 'set1_transcript.json')\n data = json.load(open(data_path, 'r'))\n df = pd.DataFrame(data)\n audio_path = os.path.join(target_path, 'audio_files')\n df['path'] = df['file'].map(lambda x: os.path.join(os.path.join(os.path.join(audio_path, x[0]), x[:2]), x)[prefix:])\n df['text'] = df['text'].map(lambda x: x.replace(' ',''))\n df['pinyin'] = df['text'].map(lambda x: ' '.join([y[0] for y in pinyin(x, style=Style.TONE3)]))\n df['duration'] = df['length']\n df[['path', 'pinyin', 'text', 'duration']].to_csv(DATA_CSV, header=None, index=None)\n# # _construct_data(target_path, 'dev', data)\n # _construct_data(target_path, 'test', data)\n # _construct_data(target_path, 'train', data)\n # pd.DataFrame(data, columns=['path', 'pinyin', 'text', 'duration']).to_csv(DATA_CSV, header=None, index=None)\n# os.remove(target_path)\nif __name__ == '__main__':\n main()\n\n"
]
| [
[
"pandas.DataFrame"
]
]
|
HalforcNull/Research_PatternRecognition | [
"e9cbe8df75ae775e0ed813ac4956973b4e857979"
]
| [
"Code/human_cellline_ExcludeOne_NormalizedTraining.py"
]
| [
"from os import listdir\nfrom os.path import isfile, isdir, join\nfrom sklearn.naive_bayes import GaussianNB\n\nimport csv\nimport datetime\nimport numpy as np\nimport pickle\n\ndataFolder = '/home/yaor/research/human_matrix_cell_line/'\nmodelFolder = '/home/yaor/research/models_human_matrix_cell_line/'\n\ndef normalization(sample):\n \"\"\"one sample pass in\"\"\"\n sample = sample + 100\n # 2^20 = 1048576\n return np.log2(sample * 1048576/np.sum(sample))\n\n\n\nlog = open('celllinelog.txt', 'a')\n\n\nlog.write('=============== ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\nlog.write('=============== New Log Start by ' + 'cell line')\n\n\ntumorList = listdir(dataFolder)\nDataSet = {}\nsampleCount = 0\nfor t in tumorList:\n if not isdir(t): \n log.write(t + ' is not a folder.')\n subList = listdir(join(dataFolder, t))\n for f in subList:\n fullFile = join(dataFolder, t, f)\n if isfile(fullFile) and f.rsplit('.', 1)[1].lower() == 'csv': \n lb = t + '.' + f.replace('_expression_matrix.csv', '')\n with open(fullFile, 'rt') as csvfile:\n datas = csv.reader(csvfile, delimiter = '\\t')\n numData = []\n for row in datas:\n if row is None or len(row) == 0:\n continue\n r = map(float,row[0].replace('\\'', '').split(','))\n log.write(str(r))\n numData.append(r)\n sampleCount = sampleCount + 1 # we don't want count empty lines into samples\n DataSet[lb] = numData\n \n \nlog.write('Data Load Finished.')\nlog.write('labels we collected: '+ str(len(DataSet)))\nlog.write('samples we coolected: ' + str(sampleCount))\n\nlabels = DataSet.keys()\nfor l in labels:\n model = GaussianNB() \n log.write('building pickle for: ' + l + ' excluded.' )\n Data = []\n Label = []\n for j in labels:\n if l != j:\n Data = Data + DataSet[j]\n Label = Label + [j] * len(DataSet[j])\n \n testTraining = np.array(Data).astype(np.float)\n # do normalization here\n testTraining = np.apply_along_axis(normalization, 1, testTraining )\n testlabeling = np.array(Label)\n model.fit(testTraining,testlabeling)\n\n with open('./normalizedmodel/cell_line/excludeOne/'+l+'.pkl', 'wb') as tr:\n pickle.dump(model, tr, pickle.HIGHEST_PROTOCOL)\n"
]
| [
[
"numpy.sum",
"numpy.array",
"numpy.apply_along_axis",
"sklearn.naive_bayes.GaussianNB"
]
]
|
Milton-Hu/Human-Pose-Estimation-and-Evaluation-for-Rehabilitation | [
"d559ac1a43041e4dc6bf9452d47860c1afe0ce56"
]
| [
"datasets/coco.py"
]
| [
"import copy\nimport json\nimport math\nimport os\nimport pickle\n\nimport cv2\nimport numpy as np\nimport pycocotools\n\nfrom torch.utils.data.dataset import Dataset\n\n# BODY_PARTS_KPT_IDS = [[1, 8], [8, 9], [9, 10], [1, 11], [11, 12], [12, 13], [1, 2], [2, 3], [3, 4], [2, 16],\n# [1, 5], [5, 6], [6, 7], [5, 17], [1, 0], [0, 14], [0, 15], [14, 16], [15, 17]]\nBODY_PARTS_KPT_IDS = [[1, 8], [8, 9], [9, 10], [10, 11], [10, 12], [12, 13], [1, 14], [14, 15], [15, 16],\n [16, 17], [16, 18], [18, 19], [1, 2], [2, 3], [3, 4], [2, 22], [1, 5], [5, 6], [6, 7],\n [5, 23], [1, 0], [0, 20], [0, 21], [20, 22], [21, 23]]\n\n\ndef get_mask(segmentations, mask):\n for segmentation in segmentations:\n rle = pycocotools.mask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])\n mask[pycocotools.mask.decode(rle) > 0.5] = 0\n return mask\n\n\nclass CocoTrainDataset(Dataset):\n def __init__(self, labels, images_folder, stride, sigma, paf_thickness, transform=None):\n super().__init__()\n self._images_folder = images_folder\n self._stride = stride\n self._sigma = sigma\n self._paf_thickness = paf_thickness\n self._transform = transform\n with open(labels, 'rb') as f:\n self._labels = pickle.load(f)\n\n def __getitem__(self, idx):\n label = copy.deepcopy(self._labels[idx]) # label modified in transform\n image = cv2.imread(os.path.join(self._images_folder, label['img_paths']), cv2.IMREAD_COLOR)\n mask = np.ones(shape=(label['img_height'], label['img_width']), dtype=np.float32)\n mask = get_mask(label['segmentations'], mask)\n sample = {\n 'label': label,\n 'image': image,\n 'mask': mask\n }\n if self._transform:\n sample = self._transform(sample)\n\n mask = cv2.resize(sample['mask'], dsize=None, fx=1/self._stride, fy=1/self._stride, interpolation=cv2.INTER_AREA)\n keypoint_maps = self._generate_keypoint_maps(sample)\n sample['keypoint_maps'] = keypoint_maps\n keypoint_mask = np.zeros(shape=keypoint_maps.shape, dtype=np.float32)\n for idx in range(keypoint_mask.shape[0]):\n keypoint_mask[idx] = mask\n sample['keypoint_mask'] = keypoint_mask\n\n paf_maps = self._generate_paf_maps(sample)\n sample['paf_maps'] = paf_maps\n paf_mask = np.zeros(shape=paf_maps.shape, dtype=np.float32)\n for idx in range(paf_mask.shape[0]):\n paf_mask[idx] = mask\n sample['paf_mask'] = paf_mask\n\n image = sample['image'].astype(np.float32)\n image = (image - 128) / 256\n sample['image'] = image.transpose((2, 0, 1))\n del sample['label']\n return sample\n\n def __len__(self):\n return len(self._labels)\n\n def _generate_keypoint_maps(self, sample):\n # n_keypoints = 18\n n_keypoints = 24\n n_rows, n_cols, _ = sample['image'].shape\n keypoint_maps = np.zeros(shape=(n_keypoints + 1,\n n_rows // self._stride, n_cols // self._stride), dtype=np.float32) # +1 for bg\n\n label = sample['label']\n for keypoint_idx in range(n_keypoints):\n keypoint = label['keypoints'][keypoint_idx]\n if keypoint[2] <= 1:\n self._add_gaussian(keypoint_maps[keypoint_idx], keypoint[0], keypoint[1], self._stride, self._sigma)\n for another_annotation in label['processed_other_annotations']:\n keypoint = another_annotation['keypoints'][keypoint_idx]\n if keypoint[2] <= 1:\n self._add_gaussian(keypoint_maps[keypoint_idx], keypoint[0], keypoint[1], self._stride, self._sigma)\n keypoint_maps[-1] = 1 - keypoint_maps.max(axis=0)\n return keypoint_maps\n\n def _add_gaussian(self, keypoint_map, x, y, stride, sigma):\n n_sigma = 4\n tl = [int(x - n_sigma * sigma), int(y - n_sigma * sigma)]\n tl[0] = max(tl[0], 0)\n tl[1] = max(tl[1], 0)\n\n br = [int(x + n_sigma * sigma), int(y + n_sigma * sigma)]\n map_h, map_w = keypoint_map.shape\n br[0] = min(br[0], map_w * stride)\n br[1] = min(br[1], map_h * stride)\n\n shift = stride / 2 - 0.5\n for map_y in range(tl[1] // stride, br[1] // stride):\n for map_x in range(tl[0] // stride, br[0] // stride):\n d2 = (map_x * stride + shift - x) * (map_x * stride + shift - x) + \\\n (map_y * stride + shift - y) * (map_y * stride + shift - y)\n exponent = d2 / 2 / sigma / sigma\n if exponent > 4.6052: # threshold, ln(100), ~0.01\n continue\n keypoint_map[map_y, map_x] += math.exp(-exponent)\n if keypoint_map[map_y, map_x] > 1:\n keypoint_map[map_y, map_x] = 1\n\n def _generate_paf_maps(self, sample):\n n_pafs = len(BODY_PARTS_KPT_IDS)\n n_rows, n_cols, _ = sample['image'].shape\n paf_maps = np.zeros(shape=(n_pafs * 2, n_rows // self._stride, n_cols // self._stride), dtype=np.float32)\n\n label = sample['label']\n for paf_idx in range(n_pafs):\n keypoint_a = label['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][0]]\n keypoint_b = label['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][1]]\n if keypoint_a[2] <= 1 and keypoint_b[2] <= 1:\n self._set_paf(paf_maps[paf_idx * 2:paf_idx * 2 + 2],\n keypoint_a[0], keypoint_a[1], keypoint_b[0], keypoint_b[1],\n self._stride, self._paf_thickness)\n for another_annotation in label['processed_other_annotations']:\n keypoint_a = another_annotation['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][0]]\n keypoint_b = another_annotation['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][1]]\n if keypoint_a[2] <= 1 and keypoint_b[2] <= 1:\n self._set_paf(paf_maps[paf_idx * 2:paf_idx * 2 + 2],\n keypoint_a[0], keypoint_a[1], keypoint_b[0], keypoint_b[1],\n self._stride, self._paf_thickness)\n return paf_maps\n\n def _set_paf(self, paf_map, x_a, y_a, x_b, y_b, stride, thickness):\n x_a /= stride\n y_a /= stride\n x_b /= stride\n y_b /= stride\n x_ba = x_b - x_a\n y_ba = y_b - y_a\n _, h_map, w_map = paf_map.shape\n x_min = int(max(min(x_a, x_b) - thickness, 0))\n x_max = int(min(max(x_a, x_b) + thickness, w_map))\n y_min = int(max(min(y_a, y_b) - thickness, 0))\n y_max = int(min(max(y_a, y_b) + thickness, h_map))\n norm_ba = (x_ba * x_ba + y_ba * y_ba) ** 0.5\n if norm_ba < 1e-7: # Same points, no paf\n return\n x_ba /= norm_ba\n y_ba /= norm_ba\n\n for y in range(y_min, y_max):\n for x in range(x_min, x_max):\n x_ca = x - x_a\n y_ca = y - y_a\n d = math.fabs(x_ca * y_ba - y_ca * x_ba)\n if d <= thickness:\n paf_map[0, y, x] = x_ba\n paf_map[1, y, x] = y_ba\n\n\nclass CocoValDataset(Dataset):\n def __init__(self, labels, images_folder):\n super().__init__()\n with open(labels, 'r') as f:\n self._labels = json.load(f)\n self._images_folder = images_folder\n\n def __getitem__(self, idx):\n file_name = self._labels['images'][idx]['file_name']\n img = cv2.imread(os.path.join(self._images_folder, file_name), cv2.IMREAD_COLOR)\n return {\n 'img': img,\n 'file_name': file_name\n }\n\n def __len__(self):\n return len(self._labels['images'])\n"
]
| [
[
"numpy.ones",
"numpy.zeros"
]
]
|
wxmgcs/learn_computer_vision | [
"311df17a127a2388c9384202e420ea822b07bf63",
"311df17a127a2388c9384202e420ea822b07bf63"
]
| [
"ps/test23.py",
"chapter4/segmentation.py"
]
| [
"# (1)、nRGB = RGB + (RGB - Threshold) * Contrast / 255\n# 公式中,nRGB表示图像像素新的R、G、B分量,RGB表示图像像素R、G、B分量,\n# Threshold为给定的阈值,Contrast为处理过的对比度增量。\n# Photoshop对于对比度增量,是按给定值的正负分别处理的:\n# 当增量等于-255时,是图像对比度的下端极限,\n# 此时,图像RGB各分量都等于阈值,图像呈全灰色,灰度图上只有1条线,即阈值灰度;\nimport matplotlib.pyplot as plt\nfrom skimage import io\n\n\nfile_name='tripod.png'\nimg=io.imread(file_name)\n\nimg = img * 1.0\n\nthre = img.mean()\n\n# -100 - 100\ncontrast = -55.0\n\nimg_out = img * 1.0\n\nif contrast <= -255.0:\n img_out = (img_out >= 0) + thre -1\nelif contrast > -255.0 and contrast < 0:\n img_out = img + (img - thre) * contrast / 255.0\nelif contrast < 255.0 and contrast > 0:\n new_con = 255.0 *255.0 / (256.0-contrast) - 255.0\n img_out = img + (img - thre) * new_con / 255.0\nelse:\n mask_1 = img > thre\n img_out = mask_1 * 255.0\n\nimg_out = img_out / 255.0\n\n# 饱和处理\nmask_1 = img_out < 0\nmask_2 = img_out > 1\n\nimg_out = img_out * (1-mask_1)\nimg_out = img_out * (1-mask_2) + mask_2\n\n\nplt.figure()\nplt.imshow(img/255.0)\nplt.axis('off')\n\nplt.figure(2)\nplt.imshow(img_out)\nplt.axis('off')\nplt.show()",
"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nfrom sys import argv\n\nif len(argv) == 2:\n file_name = argv[1]\nelse:\n file_name = '/home/d3athmast3r/Pictures/livia.jpg'\n \nimg = cv2.imread(file_name)\nmask = np.zeros(img.shape[:2],np.uint8)\n\nbgdModel = np.zeros((1,65),np.float64)\nfgdModel = np.zeros((1,65),np.float64)\n\nrect = (0,250,2422,1920)\ncv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)\n\nmask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')\nimg = img*mask2[:,:,np.newaxis]\n\nplt.imshow(img, cmap = \"gray\"),plt.colorbar(),plt.show()"
]
| [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.colorbar",
"numpy.zeros",
"numpy.where",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow"
]
]
|
KonstantinKlepikov/Hands-On-Genetic-Algorithms-with-Python | [
"ee5e7c5f8274a7ce22c3b528f86fa2bb1695e686"
]
| [
"Chapter11/01-reconstruct-with-polygons.py"
]
| [
"from deap import base\nfrom deap import creator\nfrom deap import tools\n\nimport random\nimport numpy\nimport os\n\nimport image_test\nimport elitism_callback\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# problem related constants\nPOLYGON_SIZE = 3\nNUM_OF_POLYGONS = 100\n\n# calculate total number of params in chromosome:\n# For each polygon we have:\n# two coordinates per vertex, 3 color values, one alpha value\nNUM_OF_PARAMS = NUM_OF_POLYGONS * (POLYGON_SIZE * 2 + 4)\n\n# Genetic Algorithm constants:\nPOPULATION_SIZE = 200\nP_CROSSOVER = 0.9 # probability for crossover\nP_MUTATION = 0.5 # probability for mutating an individual\nMAX_GENERATIONS = 5000\nHALL_OF_FAME_SIZE = 20\nCROWDING_FACTOR = 10.0 # crowding factor for crossover and mutation\n\n# set the random seed:\nRANDOM_SEED = 42\nrandom.seed(RANDOM_SEED)\n\n# create the image test class instance:\nimageTest = image_test.ImageTest(\"images/Mona_Lisa_head.png\", POLYGON_SIZE)\n\n# calculate total number of params in chromosome:\n# For each polygon we have:\n# two coordinates per vertex, 3 color values, one alpha value\nNUM_OF_PARAMS = NUM_OF_POLYGONS * (POLYGON_SIZE * 2 + 4)\n\n# all parameter values are bound between 0 and 1, later to be expanded:\nBOUNDS_LOW, BOUNDS_HIGH = 0.0, 1.0 # boundaries for all dimensions\n\ntoolbox = base.Toolbox()\n\n# define a single objective, minimizing fitness strategy:\ncreator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\n\n# create the Individual class based on list:\ncreator.create(\"Individual\", list, fitness=creator.FitnessMin)\n\n# helper function for creating random real numbers uniformly distributed within a given range [low, up]\n# it assumes that the range is the same for every dimension\ndef randomFloat(low, up):\n return [random.uniform(l, u) for l, u in zip([low] * NUM_OF_PARAMS, [up] * NUM_OF_PARAMS)]\n\n# create an operator that randomly returns a float in the desired range:\ntoolbox.register(\"attrFloat\", randomFloat, BOUNDS_LOW, BOUNDS_HIGH)\n\n# create an operator that fills up an Individual instance:\ntoolbox.register(\"individualCreator\",\n tools.initIterate,\n creator.Individual,\n toolbox.attrFloat)\n\n# create an operator that generates a list of individuals:\ntoolbox.register(\"populationCreator\",\n tools.initRepeat,\n list,\n toolbox.individualCreator)\n\n\n# fitness calculation using MSE as difference metric:\ndef getDiff(individual):\n return imageTest.getDifference(individual, \"MSE\"),\n #return imageTest.getDifference(individual, \"SSIM\"),\n\ntoolbox.register(\"evaluate\", getDiff)\n\n\n# genetic operators:\ntoolbox.register(\"select\", tools.selTournament, tournsize=2)\n\ntoolbox.register(\"mate\",\n tools.cxSimulatedBinaryBounded,\n low=BOUNDS_LOW,\n up=BOUNDS_HIGH,\n eta=CROWDING_FACTOR)\n\ntoolbox.register(\"mutate\",\n tools.mutPolynomialBounded,\n low=BOUNDS_LOW,\n up=BOUNDS_HIGH,\n eta=CROWDING_FACTOR,\n indpb=1.0/NUM_OF_PARAMS)\n\n\n# save the best current drawing every 100 generations (used as a callback):\ndef saveImage(gen, polygonData):\n\n # only every 100 generations:\n if gen % 100 == 0:\n\n # create folder if does not exist:\n folder = \"images/results/run-{}-{}\".format(POLYGON_SIZE, NUM_OF_POLYGONS)\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n # save the image in the folder:\n imageTest.saveImage(polygonData,\n \"{}/after-{}-gen.png\".format(folder, gen),\n \"After {} Generations\".format(gen))\n\n# Genetic Algorithm flow:\ndef main():\n\n # create initial population (generation 0):\n population = toolbox.populationCreator(n=POPULATION_SIZE)\n\n # prepare the statistics object:\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"min\", numpy.min)\n stats.register(\"avg\", numpy.mean)\n\n # define the hall-of-fame object:\n hof = tools.HallOfFame(HALL_OF_FAME_SIZE)\n\n\n # perform the Genetic Algorithm flow with elitism and 'saveImage' callback:\n population, logbook = elitism_callback.eaSimpleWithElitismAndCallback(population,\n toolbox,\n cxpb=P_CROSSOVER,\n mutpb=P_MUTATION,\n ngen=MAX_GENERATIONS,\n callback=saveImage,\n stats=stats,\n halloffame=hof,\n verbose=True)\n\n # print best solution found:\n best = hof.items[0]\n print()\n print(\"Best Solution = \", best)\n print(\"Best Score = \", best.fitness.values[0])\n print()\n\n # draw best image next to reference image:\n imageTest.plotImages(imageTest.polygonDataToImage(best))\n\n # extract statistics:\n minFitnessValues, meanFitnessValues = logbook.select(\"min\", \"avg\")\n\n # plot statistics:\n sns.set_style(\"whitegrid\")\n plt.figure(\"Stats:\")\n plt.plot(minFitnessValues, color='red')\n plt.plot(meanFitnessValues, color='green')\n plt.xlabel('Generation')\n plt.ylabel('Min / Average Fitness')\n plt.title('Min and Average fitness over Generations')\n\n # show both plots:\n plt.savefig(\"img_rec_01.png\")\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel"
]
]
|
IbrahimBRammaha/cudf | [
"57ddd5ed0cd7a24500adfc208a08075843f70979"
]
| [
"python/cudf/cudf/tests/test_scan.py"
]
| [
"from itertools import product\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom cudf.core.dataframe import DataFrame, Series\nfrom cudf.tests.utils import assert_eq, gen_rand\n\nparams_dtype = [np.int8, np.int16, np.int32, np.int64, np.float32, np.float64]\n\nparams_sizes = [0, 1, 2, 5]\n\n\ndef _gen_params():\n for t, n in product(params_dtype, params_sizes):\n if (t == np.int8 or t == np.int16) and n > 20:\n # to keep data in range\n continue\n yield t, n\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cumsum(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cumsum(), ps.cumsum(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = DataFrame()\n gdf[\"a\"] = Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cumsum(), pdf.a.cumsum(), decimal=decimal\n )\n\n\ndef test_cumsum_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n int_types = [\"int8\", \"int16\", \"int32\", \"int64\"]\n\n for type_ in float_types:\n gs = Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cumsum(), ps.cumsum())\n\n for type_ in int_types:\n expected = pd.Series([1, 3, -1, 7, 12]).astype(\"int64\")\n gs = Series(data).astype(type_)\n assert_eq(gs.cumsum(), expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cummin(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cummin(), ps.cummin(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = DataFrame()\n gdf[\"a\"] = Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cummin(), pdf.a.cummin(), decimal=decimal\n )\n\n\ndef test_cummin_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n int_types = [\"int8\", \"int16\", \"int32\", \"int64\"]\n\n for type_ in float_types:\n gs = Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cummin(), ps.cummin())\n\n for type_ in int_types:\n expected = pd.Series([1, 1, -1, 1, 1]).astype(type_)\n gs = Series(data).astype(type_)\n assert_eq(gs.cummin(), expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cummax(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cummax(), ps.cummax(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = DataFrame()\n gdf[\"a\"] = Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cummax(), pdf.a.cummax(), decimal=decimal\n )\n\n\ndef test_cummax_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n int_types = [\"int8\", \"int16\", \"int32\", \"int64\"]\n\n for type_ in float_types:\n gs = Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cummax(), ps.cummax())\n\n for type_ in int_types:\n expected = pd.Series([1, 2, -1, 4, 5]).astype(type_)\n gs = Series(data).astype(type_)\n assert_eq(gs.cummax(), expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cumprod(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cumprod(), ps.cumprod(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = DataFrame()\n gdf[\"a\"] = Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cumprod(), pdf.a.cumprod(), decimal=decimal\n )\n\n\ndef test_cumprod_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n int_types = [\"int8\", \"int16\", \"int32\", \"int64\"]\n\n for type_ in float_types:\n gs = Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cumprod(), ps.cumprod())\n\n for type_ in int_types:\n expected = pd.Series([1, 2, -1, 8, 40]).astype(\"int64\")\n gs = Series(data).astype(type_)\n assert_eq(gs.cumprod(), expected)\n\n\ndef test_scan_boolean_cumsum():\n s = Series([0, -1, -300, 23, 4, -3, 0, 0, 100])\n\n # cumsum test\n got = (s > 0).cumsum()\n expect = (s > 0).to_pandas().cumsum()\n\n assert_eq(expect, got)\n\n\ndef test_scan_boolean_cumprod():\n s = Series([0, -1, -300, 23, 4, -3, 0, 0, 100])\n\n # cumprod test\n got = (s > 0).cumprod()\n expect = (s > 0).to_pandas().cumprod()\n\n assert_eq(expect, got)\n"
]
| [
[
"pandas.DataFrame",
"pandas.Series"
]
]
|
hannesbend/Coloring.AI-breathingAIwebdemo | [
"aa6824e3ed6af72eaae3c090921fd53d166f5fc4"
]
| [
"serverMediaPulse.py"
]
| [
"from socket import socket, AF_INET, SOCK_STREAM\nfrom threading import Thread\nimport numpy as np\nimport zlib\nimport struct\nimport cv2\nfrom detector.processor import getCustomPulseApp\n\nHOST = input(\"Enter Host IP\\n\")\nPORT_VIDEO = 3000\nPORT_AUDIO = 4000\nlnF = 640*480*3\nCHUNK = 1024\nBufferSize = 4096\naddressesAudio = {}\naddresses = {}\nthreads = {}\n\nclass Server:\n\n def __init__(self):\n args = {\n serial:\"\",\n baud:\"\",\n udp:\"\"\n }\n self.pulse = getPulseApp({})\n\n def ConnectionsVideo():\n while True:\n try:\n clientVideo, addr = serverVideo.accept()\n print(\"{} is connected!!\".format(addr))\n addresses[clientVideo] = addr\n if len(addresses) > 1:\n for sockets in addresses:\n if sockets not in threads:\n threads[sockets] = True\n sockets.send((\"start\").encode())\n Thread(target=ClientConnectionVideo, args=(sockets, )).start()\n else:\n continue\n except:\n continue\n\n def ConnectionsSound():\n while True:\n try:\n clientAudio, addr = serverAudio.accept()\n print(\"{} is connected!!\".format(addr))\n addressesAudio[clientAudio] = addr\n Thread(target=ClientConnectionSound, args=(clientAudio, )).start()\n except:\n continue\n\n def ClientConnectionVideo(clientVideo):\n\n while True:\n try:\n lengthbuf = recvall(clientVideo, 4)\n length, = struct.unpack('!I', lengthbuf)\n recvall(clientVideo, length)\n \n except:\n continue\n\n def ClientConnectionSound(clientAudio):\n while True:\n try:\n data = clientAudio.recv(BufferSize)\n broadcastSound(clientAudio, data)\n except:\n continue\n\n def recvall(clientVideo, BufferSize):\n databytes = b''\n i = 0\n while i != BufferSize:\n to_read = BufferSize - i\n if to_read > (1000 * CHUNK):\n databytes = clientVideo.recv(1000 * CHUNK)\n i += len(databytes)\n processVideo(clientVideo, databytes)\n else:\n if BufferSize == 4:\n databytes += clientVideo.recv(to_read)\n else:\n databytes = clientVideo.recv(to_read)\n i += len(databytes)\n if BufferSize != 4:\n processVideo(clientVideo, databytes)\n print(\"YES!!!!!!!!!\" if i == BufferSize else \"NO!!!!!!!!!!!!\")\n if BufferSize == 4:\n processVideo(clientVideo, databytes)\n return databytes\n\n def broadcastVideo(clientSocket, data_to_be_sent):\n for clientVideo in addresses:\n if clientVideo != clientSocket:\n clientVideo.sendall(data_to_be_sent)\n\n\n def processVideo(clientSocket, data_to_process):\n img = zlib.decompress(data_to_process)\n if len(databytes) == length:\n print(\"Recieving Media..\")\n print(\"Image Frame Size:- {}\".format(len(img)))\n img = np.array(list(img))\n img = np.array(img, dtype = np.uint8).reshape(480, 640, 3)\n frame = cv2.imdecode(img_array, 1)\n self.pulse.process(frame)\n else:\n print(\"Data CORRUPTED\")\n\n\n def broadcastSound(clientSocket, data_to_be_sent):\n for clientAudio in addressesAudio:\n if clientAudio != clientSocket:\n clientAudio.sendall(data_to_be_sent)\n\n serverVideo = socket(family=AF_INET, type=SOCK_STREAM)\n try:\n serverVideo.bind((HOST, PORT_VIDEO))\n except OSError:\n print(\"Server Busy\")\n\n serverAudio = socket(family=AF_INET, type=SOCK_STREAM)\n try:\n serverAudio.bind((HOST, PORT_AUDIO))\n except OSError:\n print(\"Server Busy\")\n\n serverAudio.listen(2)\n print(\"Waiting for connection..\")\n AcceptThreadAudio = Thread(target=ConnectionsSound)\n AcceptThreadAudio.start()\n\n\n serverVideo.listen(2)\n print(\"Waiting for connection..\")\n AcceptThreadVideo = Thread(target=ConnectionsVideo)\n AcceptThreadVideo.start()\n AcceptThreadVideo.join()\n serverVideo.close()\n"
]
| [
[
"numpy.array"
]
]
|
xiaoxstz/PyOpenGL-Tutorial | [
"f3f023fd20cbe6bda49a76ff66b5d5cefd8d5280"
]
| [
"Tut 01 Hello Triangle/tut1.py"
]
| [
"# Mario Rosasco, 2016\r\n# adapted from tut1.cpp, Copyright (C) 2010-2012 by Jason L. McKesson\r\n# This file is licensed under the MIT License.\r\n\r\nfrom OpenGL.GLUT import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GL import *\r\nfrom array import array\r\nimport numpy as np\r\nfrom framework import *\r\n\r\n# A 1-D array of 3 4-D vertices (X,Y,Z,W)\r\n# Note that this must be a numpy array, since as of \r\n# 170111 support for lists has not been implemented.\r\nvertexPositions = np.array(\r\n [0.75, 0.75, 0.0, 1.0,\r\n 0.75, -0.75, 0.0, 1.0, \r\n -0.75, -0.75, 0.0, 1.0],\r\n dtype='float32'\r\n)\r\n\r\nvertexDim = 4\r\nnVertices = 3\r\n\r\n# Function that creates and compiles shaders according to the given type (a GL enum value) and \r\n# shader program (a string containing a GLSL program).\r\ndef createShader(shaderType, shaderFile):\r\n shader = glCreateShader(shaderType)\r\n glShaderSource(shader, shaderFile) # note that this is a simpler function call than in C\r\n \r\n glCompileShader(shader)\r\n \r\n status = None\r\n glGetShaderiv(shader, GL_COMPILE_STATUS, status)\r\n if status == GL_FALSE:\r\n # Note that getting the error log is much simpler in Python than in C/C++\r\n # and does not require explicit handling of the string buffer\r\n strInfoLog = glGetShaderInforLog(shader)\r\n strShaderType = \"\"\r\n if shaderType is GL_VERTEX_SHADER:\r\n strShaderType = \"vertex\"\r\n elif shaderType is GL_GEOMETRY_SHADER:\r\n strShaderType = \"geometry\"\r\n elif shaderType is GL_FRAGMENT_SHADER:\r\n strShaderType = \"fragment\"\r\n \r\n print(\"Compilation failure for \" + strShaderType + \" shader:\\n\" + strInfoLog)\r\n \r\n return shader\r\n\r\n# String containing vertex shader program written in GLSL\r\nstrVertexShader = \"\"\"\r\n#version 330\r\n\r\nlayout(location = 0) in vec4 position;\r\nvoid main()\r\n{\r\n gl_Position = position;\r\n}\r\n\"\"\"\r\n\r\n# String containing fragment shader program written in GLSL\r\nstrFragmentShader = \"\"\"\r\n#version 330\r\n\r\nout vec4 outputColor;\r\nvoid main()\r\n{\r\n outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);\r\n}\r\n\"\"\"\r\n\r\n# Global variable to represent the compiled shader program, written in GLSL\r\ntheProgram = None\r\n\r\n# Global variable to represent the buffer that will hold the position vectors\r\npositionBufferObject = None\r\n\r\n\r\n\r\n# Set up the list of shaders, and call functions to compile them\r\ndef initializeProgram():\r\n shaderList = []\r\n \r\n shaderList.append(createShader(GL_VERTEX_SHADER, strVertexShader))\r\n shaderList.append(createShader(GL_FRAGMENT_SHADER, strFragmentShader))\r\n \r\n global theProgram \r\n theProgram = createProgram(shaderList)\r\n \r\n for shader in shaderList:\r\n glDeleteShader(shader)\r\n\r\n# Set up the vertex buffer that will store our vertex coordinates for OpenGL's access\r\ndef initializeVertexBuffer():\r\n global positionBufferObject\r\n positionBufferObject = glGenBuffers(1)\r\n \r\n glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject)\r\n glBufferData( # PyOpenGL allows for the omission of the size parameter\r\n GL_ARRAY_BUFFER,\r\n vertexPositions,\r\n GL_STATIC_DRAW\r\n )\r\n glBindBuffer(GL_ARRAY_BUFFER, 0)\r\n\r\n# Initialize the OpenGL environment\r\ndef init():\r\n initializeProgram()\r\n initializeVertexBuffer()\r\n glBindVertexArray(glGenVertexArrays(1))\r\n\r\n# Called to update the display. \r\n# Because we are using double-buffering, glutSwapBuffers is called at the end\r\n# to write the rendered buffer to the display.\r\ndef display():\r\n glClearColor(0.0, 0.0, 0.0, 0.0)\r\n glClear(GL_COLOR_BUFFER_BIT)\r\n \r\n glUseProgram(theProgram)\r\n \r\n glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject)\r\n glEnableVertexAttribArray(0)\r\n glVertexAttribPointer(0, vertexDim, GL_FLOAT, GL_FALSE, 0, None)\r\n \r\n glDrawArrays(GL_TRIANGLES, 0, nVertices)\r\n \r\n glDisableVertexAttribArray(0)\r\n glUseProgram(0)\r\n \r\n glutSwapBuffers()\r\n\r\n# keyboard input handler: exits the program if 'esc' is pressed\r\ndef keyboard(key, x, y):\r\n if ord(key) == 27: # ord() is needed to get the keycode\r\n glutLeaveMainLoop()\r\n return\r\n \r\n# Called whenever the window's size changes (including once when the program starts)\r\ndef reshape(w, h):\r\n glViewport(0, 0, w, h)\r\n\r\n# The main function\r\ndef main():\r\n glutInit()\r\n displayMode = GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH | GLUT_STENCIL;\r\n glutInitDisplayMode (displayMode)\r\n \r\n width = 500;\r\n height = 500;\r\n glutInitWindowSize (width, height)\r\n \r\n glutInitWindowPosition (300, 200)\r\n \r\n window = glutCreateWindow(\"Triangle Window: Tut1\")\r\n \r\n init()\r\n glutDisplayFunc(display) \r\n glutReshapeFunc(reshape)\r\n glutKeyboardFunc(keyboard)\r\n \r\n glutMainLoop(); \r\n\r\nif __name__ == '__main__':\r\n main()\r\n"
]
| [
[
"numpy.array"
]
]
|
fernandezcuesta/pySMSCMon | [
"625bbd967625992386befeb274a9506b0fe5bea1"
]
| [
"test/unit_tests/test_genreport.py"
]
| [
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\n*t4mon* - T4 monitoring **test functions** for gen_report.py\n\"\"\"\nfrom __future__ import absolute_import\n\nimport base64\nimport imghdr\nimport tempfile\n\nimport six\n\nimport pandas as pd\nfrom t4mon.gen_report import Report, gen_report\n\nfrom . import base\n\n\nclass TestGenReport(base.BaseTestClass):\n\n \"\"\" Test functions for gen_report.py \"\"\"\n\n def setUp(self):\n super(TestGenReport, self).setUp()\n self.my_container = self.orchestrator_test.clone()\n # fill it with some data\n self.my_container.data = self.test_data\n self.system = self.test_data.index.levels[1].unique()[0].upper()\n\n def test_genreport(self):\n \"\"\" Test function for gen_report \"\"\"\n\n html_rendered = ''.join((chunk for chunk in\n gen_report(self.my_container, self.system)))\n self.assertIn('<title>Monitoring of {} at {}</title>'\n .format(self.system, self.my_container.date_time),\n html_rendered)\n\n graph_titles = []\n with open(self.my_container.graphs_definition_file,\n 'r') as graphs_file:\n for line in graphs_file:\n line = line.strip()\n if not len(line) or line[0] == '#':\n continue\n graph_titles.append(line.split(';')[1])\n\n for title in graph_titles:\n title = title.strip()\n self.assertIn('<pre><gtitle>{}</gtitle></pre>'.format(title),\n html_rendered)\n\n def test_non_existing_template(self):\n \"\"\"Test with a non existing template file, should yield nothing\"\"\"\n with self.assertRaises(StopIteration):\n _report = Report(self.my_container, self.system)\n _report.html_template = 'this_file_does_not_exist'\n _report.render()\n\n def test_not_valid_data(self):\n \"\"\"\n Test than when no data in the container nothing should be yielded\n \"\"\"\n with self.assertRaises(StopIteration):\n _report = Report(self.my_container, self.system)\n _report.data = pd.DataFrame()\n _report.render()\n\n def test_no_system_specified(self):\n \"\"\"\n Test than when no system was specified, nothing should be yielded\n \"\"\"\n with self.assertRaises(StopIteration):\n gen_report(self.my_container, '')\n\n def test_rendergraphs(self):\n \"\"\" Test function for render_graphs \"\"\"\n _report = Report(self.my_container, self.system)\n my_graph = next(_report.render_graphs())\n # test that the generated graph is a valid base64 encoded PNG file\n self.assertIsInstance(my_graph, tuple)\n for tuple_element in my_graph:\n self.assertIsInstance(tuple_element, six.string_types)\n my_graph = my_graph[1][len('data:image/png;base64,'):]\n with tempfile.NamedTemporaryFile() as temporary_file:\n temporary_file.write(base64.b64decode(six.b(my_graph)))\n temporary_file.file.close()\n self.assertEqual(imghdr.what(temporary_file.name), 'png')\n\n # Test when the graphs file contains invalid entries\n _report.graphs_definition_file = base.TEST_CSV # bad file here\n self.assertIsNone(next(_report.render_graphs()))\n"
]
| [
[
"pandas.DataFrame"
]
]
|
Robin-WZQ/NER-in-PKU-corpus | [
"4cb595e5031ca58af001cf1e5a1533ed6f53d9fa"
]
| [
"train_val_test.py"
]
| [
"import torch\r\nfrom sklearn.metrics import f1_score, precision_score, recall_score\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\nfrom tensorboardX import SummaryWriter\r\n\r\n\r\ndef train(device,train_iter,optimizor,criterion,n_epoches,batch_size,net,val_iter):\r\n '''\r\n 训练函数\r\n '''\r\n print(\"training on -> {}\".format(device))\r\n writer = SummaryWriter('runs/exp') # 记录训练过程\r\n for epoch in range(n_epoches):\r\n train_l_sum,m = 0.0, 0\r\n f_all,p_all,r_all = 0.0,0.0,0.0\r\n for i,data in enumerate(train_iter): # 按batch迭代\r\n feature,true_labels=data[0],data[1]\r\n feature = feature.to(device) # 将特征转入设备\r\n true_labels = true_labels.to(device) # 将标签转入设备\r\n predict = net(feature) # [batch_size,3]\r\n\r\n Loss = criterion(predict,true_labels.long()) # 交叉熵损失\r\n\r\n optimizor.zero_grad() # 梯度清零\r\n Loss.backward() # 反向传播\r\n optimizor.step() # 梯度更新\r\n\r\n train_l_sum += Loss.item() # 将tensor转化成int类型\r\n\r\n f1,p,r = compute(predict,true_labels) # 计算查全率、查准率、F1值\r\n f_all+=f1\r\n p_all+=p\r\n r_all+=r\r\n\r\n m += 1\r\n l = train_l_sum / m\r\n\r\n if m%2000==0: # 打印相关结果\r\n print('epoch %d [%d/%d], loss %.4f, train recall %.3f, train precision %.3f, train F1 %.3f'% (epoch + 1, m,len(train_iter),l,r_all/m,p_all/m,f_all/m ))\r\n\r\n if epoch % 3 == 0:\r\n f1,p,r = evaluate(device,val_iter,net) # 进行验证集下的验证\r\n writer.add_scalar('F1-score_val/epoch', f1, global_step=epoch, walltime=None)\r\n print(\"------------------------------------------------------------------\")\r\n print(\"validation -> val_recall=%.3f val_precision=%.3f val_F1=%.3f\"% (p,r,f1))\r\n print(\"------------------------------------------------------------------\")\r\n torch.save(net.state_dict(), 'results/'+f'{epoch}_softmax_net.pkl') # 保存模型\r\n \r\n writer.add_scalar('loss/epoch', l, global_step=epoch, walltime=None)\r\n writer.add_scalar('recall/epoch', r_all/m, global_step=epoch, walltime=None)\r\n writer.add_scalar('precision/epoch',p_all/m, global_step=epoch, walltime=None)\r\n writer.add_scalar('F1-score/epoch', f_all/m, global_step=epoch, walltime=None)\r\n\r\ndef evaluate(device,val_iter,net):\r\n '''\r\n 验证函数\r\n '''\r\n net.eval() # 选择调试模型\r\n f_all,p_all,r_all,n = 0.0,0.0,0.0,0\r\n for i,data in enumerate(val_iter): # 按batch迭代\r\n feature,true_labels=data[0],data[1]\r\n feature = feature.to(device) # 将特征转入设备\r\n true_labels = true_labels.to(device) # 将标签转入设备\r\n predict = net(feature) # [batch_size,3]\r\n f1,p,r = compute(predict,true_labels)\r\n f_all+=f1\r\n p_all+=p\r\n r_all+=r\r\n n+=1\r\n\r\n return f_all/n,p_all/n,r_all/n\r\n\r\ndef testall(device,test_iter,net):\r\n '''\r\n 测试函数\r\n '''\r\n net.eval()\r\n f_all,p_all,r_all,n = 0.0,0.0,0.0,0\r\n for i,data in enumerate(test_iter):\r\n feature,true_labels=data[0],data[1]\r\n feature = feature.to(device)\r\n true_labels = true_labels.to(device)\r\n predict = net(feature) # [batch_size,3]\r\n f1,p,r = compute(predict,true_labels)\r\n f_all+=f1\r\n p_all+=p\r\n r_all+=r\r\n n+=1\r\n\r\n print(\"测试结果:\")\r\n print('test recall %.3f, test precision %.3f, test F1 %.3f'% (r_all/n,p_all/n,f_all/n))\r\n\r\ndef compute(tensor1,tensor2):\r\n '''\r\n 计算查准率、查全率与F1值\\n\r\n 方法来自sklearn(三分类下的)\r\n '''\r\n y = tensor1.argmax(dim=1)\r\n y_pred = y.tolist() # 首先转换成列表\r\n y_true = tensor2.tolist() # 首先转换成列表\r\n f1 = f1_score( y_true, y_pred, average='macro' )\r\n p = precision_score(y_true, y_pred, average='macro')\r\n r = recall_score(y_true, y_pred, average='macro')\r\n\r\n return f1,p,r\r\n"
]
| [
[
"sklearn.metrics.precision_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.recall_score"
]
]
|
physimals/vaby_models_cvr | [
"798d347653fa31b1de8072674ddbc2dbafea8ad7"
]
| [
"examples/glm_example.py"
]
| [
"import sys\nimport os\n\nfrom vaby.data import DataModel\nfrom vaby.utils import setup_logging\nfrom vaby_models_cvr import CvrPetCo2Model\n\nimport numpy as np\npco2 = np.loadtxt(\"pco2.txt\")\n\noptions = {\n \"regressors\" : pco2,\n \"tr\" : 0.8,\n \"save_mean\" : True,\n #\"save_free_energy_history\" : True,\n \"save_runtime\" : True,\n \"save_model_fit\" : True,\n \"save_input_data\" : True,\n \"save_log\" : True,\n \"log_stream\" : sys.stdout,\n \"max_iterations\" : 50,\n}\n\nOUTDIR=\"glm_example_out\"\nos.makedirs(OUTDIR, exist_ok=True)\n\nsetup_logging(OUTDIR, **options)\ndata_model = DataModel(\"filtered_func_data.nii.gz\", mask=\"mask.nii.gz\")\nmodel = CvrPetCo2Model(data_model, **options)\ncvr, delay, sig0, modelfit = model.fit_glm(delay_min=-10, delay_max=10, delay_step=2)\n\ndata_model.model_space.save_data(cvr, \"cvr_glm\", OUTDIR)\ndata_model.model_space.save_data(delay, \"delay_glm\", OUTDIR)\ndata_model.model_space.save_data(sig0, \"sig0_glm\", OUTDIR)\ndata_model.model_space.save_data(modelfit, \"modelfit_glm\", OUTDIR)\n"
]
| [
[
"numpy.loadtxt"
]
]
|
clarkandrew/jesse | [
"527952a74bc76f76cf3a2d25755386f8db285885"
]
| [
"jesse/utils.py"
]
| [
"import math\nfrom decimal import Decimal\nfrom typing import Union\n\nimport numpy as np\nimport pandas as pd\n\nimport jesse.helpers as jh\nfrom jesse.enums import timeframes\n\n\ndef anchor_timeframe(timeframe: str) -> str:\n \"\"\"\n Returns the anchor timeframe. Useful for writing\n dynamic strategies using multiple timeframes.\n\n :param timeframe: str\n :return: str\n \"\"\"\n\n dic = {\n timeframes.MINUTE_1: timeframes.MINUTE_5,\n timeframes.MINUTE_3: timeframes.MINUTE_15,\n timeframes.MINUTE_5: timeframes.MINUTE_30,\n timeframes.MINUTE_15: timeframes.HOUR_2,\n timeframes.MINUTE_30: timeframes.HOUR_3,\n timeframes.MINUTE_45: timeframes.HOUR_3,\n timeframes.HOUR_1: timeframes.HOUR_4,\n timeframes.HOUR_2: timeframes.HOUR_6,\n timeframes.HOUR_3: timeframes.DAY_1,\n timeframes.HOUR_4: timeframes.DAY_1,\n timeframes.HOUR_6: timeframes.DAY_1,\n timeframes.HOUR_8: timeframes.DAY_1,\n timeframes.HOUR_12: timeframes.DAY_1,\n timeframes.DAY_1: timeframes.WEEK_1,\n timeframes.DAY_3: timeframes.WEEK_1,\n }\n\n return dic[timeframe]\n\n\ndef crossed(series1: np.ndarray, series2: Union[float, int, np.ndarray], direction: str = None,\n sequential: bool = False) -> bool:\n \"\"\"\n Helper for detection of crosses\n\n :param series1: np.ndarray\n :param series2: float, int, np.array\n :param direction: str - default: None - above or below\n :param sequential: bool - default: False\n\n :return: bool\n \"\"\"\n\n if sequential:\n series1_shifted = jh.np_shift(series1, 1, np.nan)\n\n if type(series2) is np.ndarray:\n series2_shifted = jh.np_shift(series2, 1, np.nan)\n else:\n series2_shifted = series2\n\n if direction is None or direction == \"above\":\n cross_above = np.logical_and(series1 > series2, series1_shifted <= series2_shifted)\n\n if direction is None or direction == \"below\":\n cross_below = np.logical_and(series1 < series2, series1_shifted >= series2_shifted)\n\n if direction is None:\n return np.logical_or(cross_above, cross_below)\n\n else:\n if type(series2) is not np.ndarray:\n series2 = np.array([series2, series2])\n\n if direction is None or direction == \"above\":\n cross_above = series1[-2] <= series2[-2] and series1[-1] > series2[-1]\n if direction is None or direction == \"below\":\n cross_below = series1[-2] >= series2[-2] and series1[-1] < series2[-1]\n\n if direction is None:\n return cross_above or cross_below\n\n if direction == \"above\":\n return cross_above\n else:\n return cross_below\n\n\ndef estimate_risk(entry_price: float, stop_price: float) -> float:\n \"\"\"\n estimates the risk per share\n\n :param entry_price: float\n :param stop_price: float\n :return: float\n \"\"\"\n if math.isnan(entry_price) or math.isnan(stop_price):\n raise TypeError()\n\n return abs(entry_price - stop_price)\n\n\ndef limit_stop_loss(entry_price: float, stop_price: float, trade_type: str, max_allowed_risk_percentage: int) -> float:\n \"\"\"\n Limits the stop-loss price according to the max allowed risk percentage.\n (How many percent you're OK with the price going against your position)\n\n :param entry_price:\n :param stop_price:\n :param trade_type:\n :param max_allowed_risk_percentage:\n :return: float\n \"\"\"\n risk = abs(entry_price - stop_price)\n max_allowed_risk = entry_price * (max_allowed_risk_percentage / 100)\n risk = min(risk, max_allowed_risk)\n return (entry_price - risk) if trade_type == 'long' else (entry_price + risk)\n\n\ndef numpy_candles_to_dataframe(candles: np.ndarray, name_date: str = \"date\", name_open: str = \"open\",\n name_high: str = \"high\",\n name_low: str = \"low\", name_close: str = \"close\",\n name_volume: str = \"volume\") -> pd.DataFrame:\n columns = [name_date, name_open, name_close, name_high, name_low, name_volume]\n df = pd.DataFrame(data=candles, index=pd.to_datetime(candles[:, 0], unit=\"ms\"), columns=columns)\n df[name_date] = pd.to_datetime(df.index, unit=\"ms\")\n return df\n\n\ndef qty_to_size(qty: float, price: float) -> float:\n \"\"\"\n converts quantity to position-size\n example: requesting 2 shares at the price of %50 would return $100\n\n :param qty: float\n :param price: float\n :return: float\n \"\"\"\n if math.isnan(qty) or math.isnan(price):\n raise TypeError()\n\n return qty * price\n\n\ndef risk_to_qty(capital: float, risk_per_capital: float, entry_price: float, stop_loss_price: float, precision: int = 8,\n fee_rate: float = 0) -> float:\n \"\"\"\n a risk management tool to quickly get the qty based on risk percentage\n\n :param capital:\n :param risk_per_capital:\n :param entry_price:\n :param stop_loss_price:\n :param precision:\n :param fee_rate:\n :return: float\n \"\"\"\n risk_per_qty = abs(entry_price - stop_loss_price)\n size = risk_to_size(capital, risk_per_capital, risk_per_qty, entry_price)\n\n if fee_rate != 0:\n size = size * (1 - fee_rate * 3)\n\n return size_to_qty(size, entry_price, precision=precision, fee_rate=fee_rate)\n\n\ndef risk_to_size(capital_size: float, risk_percentage: float, risk_per_qty: float, entry_price: float) -> float:\n \"\"\"\n calculates the size of the position based on the amount of risk percentage you're willing to take\n example: round(risk_to_size(10000, 1, 0.7, 8.6)) == 1229\n\n :param capital_size:\n :param risk_percentage:\n :param risk_per_qty:\n :param entry_price:\n :return: float\n \"\"\"\n if risk_per_qty == 0:\n raise ValueError('risk cannot be zero')\n\n risk_percentage /= 100\n temp_size = ((risk_percentage * capital_size) / risk_per_qty) * entry_price\n return min(temp_size, capital_size)\n\n\ndef size_to_qty(position_size: float, entry_price: float, precision: int = 3, fee_rate: float = 0) -> float:\n \"\"\"\n converts position-size to quantity\n example: requesting $100 at the entry_price of $50 would return 2\n :param position_size: float\n :param entry_price: float\n :param precision: int\n :param fee_rate:\n :return: float\n \"\"\"\n if math.isnan(position_size) or math.isnan(entry_price):\n raise TypeError()\n\n if fee_rate != 0:\n position_size *= 1 - fee_rate * 3\n\n return jh.floor_with_precision(position_size / entry_price, precision)\n\n\ndef subtract_floats(float1: float, float2: float) -> float:\n \"\"\"\n Subtracts two floats without the rounding issue in Python\n\n :param float1: float\n :param float2: float\n\n :return: float\n \"\"\"\n return float(Decimal(str(float1)) - Decimal(str(float2)))\n\n\ndef sum_floats(float1: float, float2: float) -> float:\n \"\"\"\n Sums two floats without the rounding issue in Python\n\n :param float1: float\n :param float2: float\n\n :return: float\n \"\"\"\n return float(Decimal(str(float1)) + Decimal(str(float2)))\n\n\ndef strictly_increasing(series: np.ndarray, lookback: int) -> bool:\n a = series[-lookback:]\n diff = np.diff(a)\n return np.all(diff > 0)\n\n\ndef strictly_decreasing(series: np.ndarray, lookback: int) -> bool:\n a = series[-lookback:]\n diff = np.diff(a)\n return np.all(diff < 0)\n\n\ndef streaks(series: np.ndarray, use_diff=True) -> np.ndarray:\n if use_diff:\n series = np.diff(series)\n pos = np.clip(series, 0, 1).astype(bool).cumsum()\n neg = np.clip(series, -1, 0).astype(bool).cumsum()\n streak = np.where(series >= 0, pos - np.maximum.accumulate(np.where(series <= 0, pos, 0)),\n -neg + np.maximum.accumulate(np.where(series >= 0, neg, 0)))\n\n return np.concatenate(\n (np.full((series.shape[0] - streak.shape[0]), np.nan), streak)\n )\n\n\ndef signal_line(series: np.ndarray, period: int = 10, matype: int = 0) -> np.ndarray:\n from jesse.indicators.ma import ma\n return ma(series, period=period, matype=matype, sequential=True)\n\n\ndef kelly_criterion(win_rate: float, ratio_avg_win_loss: float) -> float:\n return win_rate - ((1 - win_rate) / ratio_avg_win_loss)\n\n\ndef prices_to_returns(price_series: np.ndarray) -> np.ndarray:\n \"\"\"\n converts a series of asset prices to returns.\n \"\"\"\n pct = np.diff(price_series) / price_series[:-1] * 100\n return jh.same_length(price_series, pct)\n\n\ndef z_score(series: np.ndarray) -> np.ndarray:\n \"\"\"\n A Z-score is a numerical measurement that describes a value's relationship to the mean of a group of values. Z-score is measured in terms of standard deviations from the mean\n \"\"\"\n return (series - np.mean(series)) / np.std(series)\n\n\ndef are_cointegrated(price_returns_1: np.ndarray, price_returns_2: np.ndarray, cutoff=0.05) -> bool:\n \"\"\"\n Uses unit-root test on residuals to test for cointegrated relationship\n See Hamilton (1994) 19.2 for more details\n H_0 is that there is no cointegration i.e. that the residuals have are unit root series (non-stationary)\n We must observe significant p-value to convince ourselves that the series are cointegrated\n \"\"\"\n from statsmodels.tsa.stattools import coint\n\n p_value = coint(price_returns_1, price_returns_2)[1]\n return p_value < cutoff\n\n\ndef dd(msg: str) -> None:\n \"\"\"\n The dd function dumps the given variables and ends execution of the script. \n Used for debugging. \n\n :param msg: str\n \"\"\"\n print(msg)\n jh.terminate_app()\n\n\ndef candlestick_chart(candles: np.ndarray):\n \"\"\"\n Displays a candlestick chart from the numpy array\n \"\"\"\n import mplfinance as mpf\n df = numpy_candles_to_dataframe(candles)\n mpf.plot(df, type='candle')\n\n\ndef combinations_without_repeat(a: np.ndarray, n: int = 2) -> np.ndarray:\n \"\"\"\n Creates an array containing all combinations of the passed arrays individual values without repetitions. Useful for the optimization mode.\n \"\"\"\n from itertools import permutations\n if n <= 1:\n raise ValueError(\"n must be >= 2\")\n return np.array(list(permutations(a, n)))\n\n\ndef wavelet_denoising(raw: np.ndarray, wavelet='haar', level: int = 1, mode: str = 'symmetric',\n smoothing_factor: float = 0, threshold_mode: str = 'hard') -> np.ndarray:\n \"\"\"\n deconstructs, thresholds then reconstructs\n higher thresholds = less detailed reconstruction\n\n Only consider haar, db, sym, coif wavelet basis functions, as these are relatively suitable for financial data\n \"\"\"\n import pywt\n # Deconstruct\n coeff = pywt.wavedec(raw, wavelet, mode=mode)\n # Mean absolute deviation of a signal\n max_level = pywt.dwt_max_level(len(raw), wavelet)\n level = min(level, max_level)\n madev = np.mean(np.absolute(coeff[-level] - np.mean(coeff[-level])))\n # The hardcored factor is explained here: https://en.wikipedia.org/wiki/Median_absolute_deviation\n sigma = (1 / 0.67449) * madev * smoothing_factor\n threshold = sigma * np.sqrt(2 * np.log(len(raw)))\n coeff[1:] = (pywt.threshold(i, value=threshold, mode=threshold_mode) for i in coeff[1:])\n signal = pywt.waverec(coeff, wavelet, mode=mode)\n if len(signal) > len(raw):\n signal = np.delete(signal, -1)\n return signal\n"
]
| [
[
"pandas.to_datetime",
"numpy.logical_or",
"numpy.delete",
"numpy.array",
"numpy.full",
"numpy.logical_and",
"numpy.diff",
"numpy.mean",
"numpy.std",
"numpy.where",
"numpy.clip",
"numpy.all"
]
]
|
Teppei-Kanayama/myChainer | [
"6ffbfd8479768ca8b580c98788c5b1ba1fd3aee8"
]
| [
"tests/chainer_tests/functions_tests/math_tests/test_maximum.py"
]
| [
"import unittest\n\nimport chainer\nimport numpy\n\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.testing import condition\nfrom chainer.utils import type_check\n\n\[email protected](*testing.product({\n 'shape': [(3, 2), ()],\n 'dtype': [numpy.float16, numpy.float32, numpy.float64]\n}))\nclass TestMaximum(unittest.TestCase):\n\n def setUp(self):\n shape = self.shape\n self.x1 = numpy.random.uniform(-1, 1, shape).astype(self.dtype)\n self.x2 = numpy.random.uniform(-1, 1, shape).astype(self.dtype)\n # Avoid close values for stability in numerical gradient.\n for i in numpy.ndindex(shape):\n if -0.125 < self.x1[i] - self.x2[i] < 0.125:\n self.x1[i] = -0.5\n self.x2[i] = 0.5\n self.y_expected = numpy.maximum(self.x1, self.x2)\n self.gy = numpy.random.uniform(-1, 1, shape).astype(self.dtype)\n self.check_forward_options = {}\n self.check_backward_options = {'eps': 1e-2}\n if self.dtype == numpy.float16:\n self.check_forward_options = {'atol': 1e-4, 'rtol': 1e-3}\n self.check_backward_options = {\n 'eps': 2 ** -3, 'atol': 1e-2, 'rtol': 1e-1}\n\n def check_forward(self, x1_data, x2_data, y_expected):\n x1 = chainer.Variable(x1_data)\n x2 = chainer.Variable(x2_data)\n y = functions.maximum(x1, x2)\n gradient_check.assert_allclose(\n y_expected, y.data, **self.check_forward_options)\n\n @condition.retry(3)\n def test_forward_cpu(self):\n self.check_forward(self.x1, self.x2, self.y_expected)\n\n @attr.gpu\n @condition.retry(3)\n def test_forward_gpu(self):\n x1 = cuda.to_gpu(self.x1)\n x2 = cuda.to_gpu(self.x2)\n self.check_forward(x1, x2, self.y_expected)\n\n def check_backward(self, x1_data, x2_data, y_grad):\n func = functions.maximum\n x = (x1_data, x2_data)\n gradient_check.check_backward(\n func, x, y_grad, **self.check_backward_options)\n\n @condition.retry(3)\n def test_backward_cpu(self):\n self.check_backward(self.x1, self.x2, self.gy)\n\n @attr.gpu\n @condition.retry(3)\n def test_backward_gpu(self):\n x1 = cuda.to_gpu(self.x1)\n x2 = cuda.to_gpu(self.x2)\n gy = cuda.to_gpu(self.gy)\n self.check_backward(x1, x2, gy)\n\n\[email protected](*testing.product({\n 'dtype1': [numpy.float16, numpy.float32, numpy.float64],\n 'dtype2': [numpy.float16, numpy.float32, numpy.float64]\n}))\nclass TestMaximumInconsistentTypes(unittest.TestCase):\n\n def test_maximum_inconsistent_types(self):\n if self.dtype1 == self.dtype2:\n return\n x1_data = numpy.random.uniform(-1, 1, (3, 2)).astype(self.dtype1)\n x2_data = numpy.random.uniform(-1, 1, (3, 2)).astype(self.dtype2)\n x1 = chainer.Variable(x1_data)\n x2 = chainer.Variable(x2_data)\n with self.assertRaises(type_check.InvalidType):\n functions.maximum(x1, x2)\n\n\[email protected](*testing.product({\n 'dtype': [numpy.float16, numpy.float32, numpy.float64]\n}))\nclass TestMaximumInconsistentShapes(unittest.TestCase):\n\n def test_maximum_inconsistent_shapes(self):\n x1_data = numpy.random.uniform(-1, 1, (3, 2)).astype(self.dtype)\n x2_data = numpy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)\n x1 = chainer.Variable(x1_data)\n x2 = chainer.Variable(x2_data)\n with self.assertRaises(type_check.InvalidType):\n functions.maximum(x1, x2)\n\ntesting.run_module(__name__, __file__)\n"
]
| [
[
"numpy.ndindex",
"numpy.random.uniform",
"numpy.maximum"
]
]
|
franzmueller/wradlib | [
"6680d357dd6b19511f687727020fc37bc47c968d"
]
| [
"wradlib/georef/polar.py"
]
| [
"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# Copyright (c) 2011-2020, wradlib developers.\n# Distributed under the MIT License. See LICENSE.txt for more info.\n\n\"\"\"\nPolar Grid Functions\n^^^^^^^^^^^^^^^^^^^^\n\n.. autosummary::\n :nosignatures:\n :toctree: generated/\n\n {}\n\"\"\"\n__all__ = [\n \"spherical_to_xyz\",\n \"spherical_to_proj\",\n \"spherical_to_polyvert\",\n \"spherical_to_centroids\",\n \"centroid_to_polyvert\",\n \"sweep_centroids\",\n \"maximum_intensity_projection\",\n]\n__doc__ = __doc__.format(\"\\n \".join(__all__))\n\nimport warnings\n\nimport numpy as np\n\nfrom wradlib.georef import misc, projection\n\n\ndef spherical_to_xyz(\n r, phi, theta, sitecoords, re=None, ke=4.0 / 3.0, squeeze=False, strict_dims=False\n):\n \"\"\"Transforms spherical coordinates (r, phi, theta) to cartesian\n coordinates (x, y, z) centered at sitecoords (aeqd).\n\n It takes the shortening of the great circle\n distance with increasing elevation angle as well as the resulting\n increase in height into account.\n\n Parameters\n ----------\n r : :class:`numpy:numpy.ndarray`\n Contains the radial distances in meters.\n phi : :class:`numpy:numpy.ndarray`\n Contains the azimuthal angles in degree.\n theta: :class:`numpy:numpy.ndarray`\n Contains the elevation angles in degree.\n sitecoords : a sequence of three floats\n the lon / lat coordinates of the radar location and its altitude\n a.m.s.l. (in meters)\n if sitecoords is of length two, altitude is assumed to be zero\n re : float\n earth's radius [m]\n ke : float\n adjustment factor to account for the refractivity gradient that\n affects radar beam propagation. In principle this is wavelength-\n dependent. The default of 4/3 is a good approximation for most\n weather radar wavelengths.\n squeeze : bool\n If True, returns squeezed array. Defaults to False.\n strict_dims : bool\n If True, generates output of (theta, phi, r, 3) in any case.\n If False, dimensions with same length are \"merged\".\n\n Returns\n -------\n xyz : :class:`numpy:numpy.ndarray`\n Array of shape (..., 3). Contains cartesian coordinates.\n rad : osr object\n Destination Spatial Reference System (Projection).\n Defaults to wgs84 (epsg 4326).\n \"\"\"\n # if site altitude is present, use it, else assume it to be zero\n try:\n centalt = sitecoords[2]\n except IndexError:\n centalt = 0.0\n\n # if no radius is given, get the approximate radius of the WGS84\n # ellipsoid for the site's latitude\n if re is None:\n re = projection.get_earth_radius(sitecoords[1])\n # Set up aeqd-projection sitecoord-centered, wgs84 datum and ellipsoid\n # use world azimuthal equidistant projection\n projstr = (\n \"+proj=aeqd +lon_0={lon:f} +x_0=0 +y_0=0 +lat_0={lat:f} \"\n + \"+ellps=WGS84 +datum=WGS84 +units=m +no_defs\"\n + \"\"\n ).format(lon=sitecoords[0], lat=sitecoords[1])\n\n else:\n # Set up aeqd-projection sitecoord-centered, assuming spherical earth\n # use Sphere azimuthal equidistant projection\n projstr = (\n \"+proj=aeqd +lon_0={lon:f} +lat_0={lat:f} +a={a:f} \"\n \"+b={b:f} +units=m +no_defs\"\n ).format(lon=sitecoords[0], lat=sitecoords[1], a=re, b=re)\n\n rad = projection.proj4_to_osr(projstr)\n\n r = np.asanyarray(r)\n theta = np.asanyarray(theta)\n phi = np.asanyarray(phi)\n\n if r.ndim:\n r = r.reshape((1,) * (3 - r.ndim) + r.shape)\n\n if phi.ndim:\n phi = phi.reshape((1,) + phi.shape + (1,) * (2 - phi.ndim))\n\n if not theta.ndim:\n theta = np.broadcast_to(theta, phi.shape)\n\n dims = 3\n if not strict_dims:\n if phi.ndim and theta.ndim and (theta.shape[0] == phi.shape[1]):\n dims -= 1\n if r.ndim and theta.ndim and (theta.shape[0] == r.shape[2]):\n dims -= 1\n\n if theta.ndim and phi.ndim:\n theta = theta.reshape(theta.shape + (1,) * (dims - theta.ndim))\n\n z = misc.bin_altitude(r, theta, centalt, re, ke=ke)\n dist = misc.site_distance(r, theta, z, re, ke=ke)\n\n if (not strict_dims) and phi.ndim and r.ndim and (r.shape[2] == phi.shape[1]):\n z = np.squeeze(z)\n dist = np.squeeze(dist)\n phi = np.squeeze(phi)\n\n x = dist * np.cos(np.radians(90 - phi))\n y = dist * np.sin(np.radians(90 - phi))\n\n if z.ndim:\n z = np.broadcast_to(z, x.shape)\n\n xyz = np.stack((x, y, z), axis=-1)\n\n if xyz.ndim == 1:\n xyz.shape = (1,) * 3 + xyz.shape\n elif xyz.ndim == 2:\n xyz.shape = (xyz.shape[0],) + (1,) * 2 + (xyz.shape[1],)\n\n if squeeze:\n xyz = np.squeeze(xyz)\n\n return xyz, rad\n\n\ndef spherical_to_proj(r, phi, theta, sitecoords, proj=None, re=None, ke=4.0 / 3.0):\n \"\"\"Transforms spherical coordinates (r, phi, theta) to projected\n coordinates centered at sitecoords in given projection.\n\n It takes the shortening of the great circle\n distance with increasing elevation angle as well as the resulting\n increase in height into account.\n\n Parameters\n ----------\n r : :class:`numpy:numpy.ndarray`\n Contains the radial distances.\n phi : :class:`numpy:numpy.ndarray`\n Contains the azimuthal angles.\n theta: :class:`numpy:numpy.ndarray`\n Contains the elevation angles.\n sitecoords : a sequence of three floats\n the lon / lat coordinates of the radar location and its altitude\n a.m.s.l. (in meters)\n if sitecoords is of length two, altitude is assumed to be zero\n proj : osr object\n Destination Spatial Reference System (Projection).\n Defaults to wgs84 (epsg 4326).\n re : float\n earth's radius [m]\n ke : float\n adjustment factor to account for the refractivity gradient that\n affects radar beam propagation. In principle this is wavelength-\n dependent. The default of 4/3 is a good approximation for most\n weather radar wavelengths.\n\n Returns\n -------\n coords : :class:`numpy:numpy.ndarray`\n Array of shape (..., 3). Contains projected map coordinates.\n\n Examples\n --------\n\n A few standard directions (North, South, North, East, South, West) with\n different distances (amounting to roughly 1°) from a site\n located at 48°N 9°E\n\n >>> r = np.array([0., 0., 111., 111., 111., 111.,])*1000\n >>> az = np.array([0., 180., 0., 90., 180., 270.,])\n >>> th = np.array([0., 0., 0., 0., 0., 0.5,])\n >>> csite = (9.0, 48.0)\n >>> coords = spherical_to_proj(r, az, th, csite)\n >>> for coord in coords:\n ... print( '{0:7.4f}, {1:7.4f}, {2:7.4f}'.format(*coord))\n ...\n 9.0000, 48.0000, 0.0000\n 9.0000, 48.0000, 0.0000\n 9.0000, 48.9981, 725.7160\n 10.4872, 47.9904, 725.7160\n 9.0000, 47.0017, 725.7160\n 7.5131, 47.9904, 1694.2234\n\n Here, the coordinates of the east and west directions won't come to lie on\n the latitude of the site because the beam doesn't travel along the latitude\n circle but along a great circle.\n\n See :ref:`/notebooks/basics/wradlib_workflow.ipynb#\\\nGeoreferencing-and-Projection`.\n \"\"\"\n if proj is None:\n proj = projection.get_default_projection()\n\n xyz, rad = spherical_to_xyz(r, phi, theta, sitecoords, re=re, ke=ke, squeeze=True)\n\n # reproject aeqd to destination projection\n coords = projection.reproject(xyz, projection_source=rad, projection_target=proj)\n\n return coords\n\n\ndef centroid_to_polyvert(centroid, delta):\n \"\"\"Calculates the 2-D Polygon vertices necessary to form a rectangular\n polygon around the centroid's coordinates.\n\n The vertices order will be clockwise, as this is the convention used\n by ESRI's shapefile format for a polygon.\n\n Parameters\n ----------\n centroid : array_like\n List of 2-D coordinates of the center point of the rectangle.\n delta : scalar or :class:`numpy:numpy.ndarray`\n Symmetric distances of the vertices from the centroid in each\n direction. If ``delta`` is scalar, it is assumed to apply to\n both dimensions.\n\n Returns\n -------\n vertices : :class:`numpy:numpy.ndarray`\n An array with 5 vertices per centroid.\n\n Note\n ----\n The function can currently only deal with 2-D data (If you come up with a\n higher dimensional version of 'clockwise' you're welcome to add it).\n The data is then assumed to be organized within the ``centroid`` array with\n the last dimension being the 2-D coordinates of each point.\n\n Examples\n --------\n\n >>> centroid_to_polyvert([0., 1.], [0.5, 1.5])\n array([[-0.5, -0.5],\n [-0.5, 2.5],\n [ 0.5, 2.5],\n [ 0.5, -0.5],\n [-0.5, -0.5]])\n >>> centroid_to_polyvert(np.arange(4).reshape((2,2)), 0.5)\n array([[[-0.5, 0.5],\n [-0.5, 1.5],\n [ 0.5, 1.5],\n [ 0.5, 0.5],\n [-0.5, 0.5]],\n <BLANKLINE>\n [[ 1.5, 2.5],\n [ 1.5, 3.5],\n [ 2.5, 3.5],\n [ 2.5, 2.5],\n [ 1.5, 2.5]]])\n\n \"\"\"\n cent = np.asanyarray(centroid)\n if cent.shape[-1] != 2:\n raise ValueError(\"Parameter 'centroid' dimensions need \" \"to be (..., 2)\")\n dshape = [1] * cent.ndim\n dshape.insert(-1, 5)\n dshape[-1] = 2\n\n d = np.array(\n [[-1.0, -1.0], [-1.0, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]]\n ).reshape(tuple(dshape))\n\n return np.asanyarray(centroid)[..., None, :] + d * np.asanyarray(delta)\n\n\ndef spherical_to_polyvert(r, phi, theta, sitecoords, proj=None):\n \"\"\"\n Generate 3-D polygon vertices directly from spherical coordinates\n (r, phi, theta).\n\n This is an alternative to :func:`~wradlib.georef.centroid_to_polyvert`\n which does not use centroids, but generates the polygon vertices by simply\n connecting the corners of the radar bins.\n\n Both azimuth and range arrays are assumed to be equidistant and to contain\n only unique values. For further information refer to the documentation of\n :func:`~wradlib.georef.spherical_to_xyz`.\n\n Parameters\n ----------\n r : :class:`numpy:numpy.ndarray`\n Array of ranges [m]; r defines the exterior boundaries of the range\n bins! (not the centroids). Thus, values must be positive!\n phi : :class:`numpy:numpy.ndarray`\n Array of azimuth angles containing values between 0° and 360°.\n The angles are assumed to describe the pointing direction fo the main\n beam lobe!\n The first angle can start at any values, but make sure the array is\n sorted continuously positively clockwise and the angles are\n equidistant. An angle if 0 degree is pointing north.\n theta : float\n Elevation angle of scan\n sitecoords : a sequence of three floats\n the lon/lat/alt coordinates of the radar location\n proj : osr object\n Destination Projection\n\n Returns\n -------\n output : :class:`numpy:numpy.ndarray`\n A 3-d array of polygon vertices with shape(num_vertices,\n num_vertex_nodes, 2). The last dimension carries the xyz-coordinates\n either in `aeqd` or given proj.\n proj : osr object\n only returned if proj is None\n\n Examples\n --------\n >>> import wradlib.georef as georef # noqa\n >>> import numpy as np\n >>> from matplotlib import collections\n >>> import matplotlib.pyplot as pl\n >>> #pl.interactive(True)\n >>> # define the polar coordinates and the site coordinates in lat/lon\n >>> r = np.array([50., 100., 150., 200.]) * 1000\n >>> # _check_polar_coords fails in next line\n >>> # az = np.array([0., 45., 90., 135., 180., 225., 270., 315., 360.])\n >>> az = np.array([0., 45., 90., 135., 180., 225., 270., 315.])\n >>> el = 1.0\n >>> sitecoords = (9.0, 48.0, 0)\n >>> polygons, proj = georef.spherical_to_polyvert(r, az, el, sitecoords)\n >>> # plot the resulting mesh\n >>> fig = pl.figure()\n >>> ax = fig.add_subplot(111)\n >>> #polycoll = mpl.collections.PolyCollection(vertices,closed=True, facecolors=None) # noqa\n >>> polycoll = collections.PolyCollection(polygons[...,:2], closed=True, facecolors='None') # noqa\n >>> ret = ax.add_collection(polycoll, autolim=True)\n >>> pl.autoscale()\n >>> pl.show()\n\n \"\"\"\n # prepare the range and azimuth array so they describe the boundaries of\n # a bin, not the centroid\n r, phi = _check_polar_coords(r, phi)\n r = np.insert(r, 0, r[0] - _get_range_resolution(r))\n phi = phi - 0.5 * _get_azimuth_resolution(phi)\n phi = np.append(phi, phi[0])\n phi = np.where(phi < 0, phi + 360.0, phi)\n\n # generate a grid of polar coordinates of bin corners\n r, phi = np.meshgrid(r, phi)\n\n coords, rad = spherical_to_xyz(\n r, phi, theta, sitecoords, squeeze=True, strict_dims=True\n )\n if proj is not None:\n coords = projection.reproject(\n coords, projection_source=rad, projection_target=proj\n )\n\n llc = coords[:-1, :-1]\n ulc = coords[:-1, 1:]\n urc = coords[1:, 1:]\n lrc = coords[1:, :-1]\n\n vertices = np.stack((llc, ulc, urc, lrc, llc), axis=-2).reshape((-1, 5, 3))\n\n if proj is None:\n return vertices, rad\n else:\n return vertices\n\n\ndef spherical_to_centroids(r, phi, theta, sitecoords, proj=None):\n \"\"\"\n Generate 3-D centroids of the radar bins from the sperical\n coordinates (r, phi, theta).\n\n Both azimuth and range arrays are assumed to be equidistant and to contain\n only unique values. The ranges are assumed to define the exterior\n boundaries of the range bins (thus they must be positive). The angles are\n assumed to describe the pointing direction fo the main beam lobe.\n\n For further information refer to the documentation of\n :meth:`~wradlib.georef.polar2lonlat`.\n\n Parameters\n ----------\n r : :class:`numpy:numpy.ndarray`\n Array of ranges [m]; r defines the exterior boundaries of the range\n bins! (not the centroids). Thus, values must be positive!\n phi : :class:`numpy:numpy.ndarray`\n Array of azimuth angles containing values between 0° and 360°.\n The angles are assumed to describe the pointing direction fo the main\n beam lobe!\n The first angle can start at any values, but make sure the array is\n sorted continuously positively clockwise and the angles are\n equidistant. An angle if 0 degree is pointing north.\n theta : float\n Elevation angle of scan\n sitecoords : a sequence of three floats\n the lon/lat/alt coordinates of the radar location\n proj : osr object\n Destination Projection\n\n Returns\n -------\n output : centroids :class:`numpy:numpy.ndarray`\n A 3-d array of bin centroids with shape(num_rays, num_bins, 3).\n The last dimension carries the xyz-coordinates\n either in `aeqd` or given proj.\n proj : osr object\n only returned if proj is None\n\n Note\n ----\n Azimuth angles of 360 deg are internally converted to 0 deg.\n\n \"\"\"\n # make sure the range and azimuth angles have the right properties\n r, phi = _check_polar_coords(r, phi)\n\n r = r - 0.5 * _get_range_resolution(r)\n\n # generate a polar grid and convert to lat/lon\n r, phi = np.meshgrid(r, phi)\n\n coords, rad = spherical_to_xyz(r, phi, theta, sitecoords, squeeze=True)\n\n if proj is None:\n return coords, rad\n else:\n return projection.reproject(\n coords, projection_source=rad, projection_target=proj\n )\n\n\ndef _check_polar_coords(r, az):\n \"\"\"\n Contains a lot of checks to make sure the polar coordinates are adequate.\n\n Parameters\n ----------\n r : :class:`numpy:numpy.ndarray`\n range gates in any unit\n az : :class:`numpy:numpy.ndarray`\n azimuth angles in degree\n\n \"\"\"\n r = np.array(r, \"f4\")\n az = np.array(az, \"f4\")\n az[az == 360.0] = 0.0\n if 0.0 in r:\n raise ValueError(\n \"Invalid polar coordinates: \"\n \"0 is not a valid range gate specification \"\n \"(the centroid of a range gate must be positive).\"\n )\n if len(np.unique(r)) != len(r):\n raise ValueError(\n \"Invalid polar coordinates: \"\n \"Range gate specification contains duplicate \"\n \"entries.\"\n )\n if len(np.unique(az)) != len(az):\n raise ValueError(\n \"Invalid polar coordinates: \"\n \"Azimuth specification contains duplicate entries.\"\n )\n if not _is_sorted(r):\n raise ValueError(\"Invalid polar coordinates: \" \"Range array must be sorted.\")\n if len(np.unique(r[1:] - r[:-1])) > 1:\n raise ValueError(\n \"Invalid polar coordinates: \" \"Range gates are not equidistant.\"\n )\n if len(np.where(az >= 360.0)[0]) > 0:\n raise ValueError(\n \"Invalid polar coordinates: \"\n \"Azimuth angles must not be greater than \"\n \"or equal to 360 deg.\"\n )\n if not _is_sorted(az):\n # it is ok if the azimuth angle array is not sorted, but it has to be\n # 'continuously clockwise', e.g. it could start at 90° and stop at °89\n az_right = az[np.where(np.logical_and(az <= 360, az >= az[0]))[0]]\n az_left = az[np.where(az < az[0])]\n if (not _is_sorted(az_right)) or (not _is_sorted(az_left)):\n raise ValueError(\n \"Invalid polar coordinates: \" \"Azimuth array is not sorted clockwise.\"\n )\n if len(np.unique(np.sort(az)[1:] - np.sort(az)[:-1])) > 1:\n warnings.warn(\n \"The azimuth angles of the current \" \"dataset are not equidistant.\",\n UserWarning,\n )\n # print('Invalid polar coordinates: Azimuth angles '\n # 'are not equidistant.')\n # exit()\n return r, az\n\n\ndef _is_sorted(x):\n \"\"\"\n Returns True when array x is sorted\n \"\"\"\n return np.all(x == np.sort(x))\n\n\ndef _get_range_resolution(x):\n \"\"\"\n Returns the range resolution based on\n the array x of the range gates' exterior limits\n \"\"\"\n if len(x) <= 1:\n raise ValueError(\n \"The range gate array has to contain at least \"\n \"two values for deriving the resolution.\"\n )\n res = np.unique(x[1:] - x[:-1])\n if len(res) > 1:\n raise ValueError(\"The resolution of the range array is ambiguous.\")\n return res[0]\n\n\ndef _get_azimuth_resolution(x):\n \"\"\"\n Returns the azimuth resolution based on the array x of the beams'\n azimuth angles\n \"\"\"\n res = np.unique(np.sort(x)[1:] - np.sort(x)[:-1])\n if len(res) > 1:\n raise ValueError(\"The resolution of the azimuth angle array \" \"is ambiguous.\")\n return res[0]\n\n\ndef sweep_centroids(nrays, rscale, nbins, elangle):\n \"\"\"Construct sweep centroids native coordinates.\n\n Parameters\n ----------\n nrays : int\n number of rays\n rscale : float\n length [m] of a range bin\n nbins : int\n number of range bins\n elangle : float\n elevation angle [deg]\n\n Returns\n -------\n coordinates : 3d array\n array of shape (nrays,nbins,3) containing native centroid radar\n coordinates (slant range, azimuth, elevation)\n \"\"\"\n ascale = 360.0 / nrays\n azimuths = ascale / 2.0 + np.linspace(0, 360.0, nrays, endpoint=False)\n ranges = np.arange(nbins) * rscale + rscale / 2.0\n coordinates = np.empty((nrays, nbins, 3), dtype=float)\n coordinates[:, :, 0] = np.tile(ranges, (nrays, 1))\n coordinates[:, :, 1] = np.transpose(np.tile(azimuths, (nbins, 1)))\n coordinates[:, :, 2] = elangle\n return coordinates\n\n\ndef maximum_intensity_projection(\n data, r=None, az=None, angle=None, elev=None, autoext=True\n):\n \"\"\"Computes the maximum intensity projection along an arbitrary cut \\\n through the ppi from polar data.\n\n Parameters\n ----------\n data : :class:`numpy:numpy.ndarray`\n Array containing polar data (azimuth, range)\n r : :class:`numpy:numpy.ndarray`\n Array containing range data\n az : array\n Array containing azimuth data\n angle : float\n angle of slice, Defaults to 0. Should be between 0 and 180.\n 0. means horizontal slice, 90. means vertical slice\n elev : float\n elevation angle of scan, Defaults to 0.\n autoext : True | False\n This routine uses numpy.digitize to bin the data.\n As this function needs bounds, we create one set of coordinates more\n than would usually be provided by `r` and `az`.\n\n Returns\n -------\n xs : :class:`numpy:numpy.ndarray`\n meshgrid x array\n ys : :class:`numpy:numpy.ndarray`\n meshgrid y array\n mip : :class:`numpy:numpy.ndarray`\n Array containing the maximum intensity projection (range, range*2)\n \"\"\"\n # this may seem odd at first, but d1 and d2 are also used in several\n # plotting functions and thus it may be easier to compare the functions\n d1 = r\n d2 = az\n\n # providing 'reasonable defaults', based on the data's shape\n if d1 is None:\n d1 = np.arange(data.shape[1], dtype=np.float)\n if d2 is None:\n d2 = np.arange(data.shape[0], dtype=np.float)\n\n if angle is None:\n angle = 0.0\n\n if elev is None:\n elev = 0.0\n\n if autoext:\n # the ranges need to go 'one bin further', assuming some regularity\n # we extend by the distance between the preceding bins.\n x = np.append(d1, d1[-1] + (d1[-1] - d1[-2]))\n # the angular dimension is supposed to be cyclic, so we just add the\n # first element\n y = np.append(d2, d2[0])\n else:\n # no autoext basically is only useful, if the user supplied the correct\n # dimensions himself.\n x = d1\n y = d2\n\n # roll data array to specified azimuth, assuming equidistant azimuth angles\n ind = (d2 >= angle).nonzero()[0][0]\n data = np.roll(data, ind, axis=0)\n\n # build cartesian range array, add delta to last element to compensate for\n # open bound (np.digitize)\n dc = np.linspace(-np.max(d1), np.max(d1) + 0.0001, num=d1.shape[0] * 2 + 1)\n\n # get height values from polar data and build cartesian height array\n # add delta to last element to compensate for open bound (np.digitize)\n hp = np.zeros((y.shape[0], x.shape[0]))\n hc = misc.bin_altitude(x, elev, 0, re=6370040.0)\n hp[:] = hc\n hc[-1] += 0.0001\n\n # create meshgrid for polar data\n xx, yy = np.meshgrid(x, y)\n\n # create meshgrid for cartesian slices\n xs, ys = np.meshgrid(dc, hc)\n # xs, ys = np.meshgrid(dc,x)\n\n # convert polar coordinates to cartesian\n xxx = xx * np.cos(np.radians(90.0 - yy))\n # yyy = xx * np.sin(np.radians(90.-yy))\n\n # digitize coordinates according to cartesian range array\n range_dig1 = np.digitize(xxx.ravel(), dc)\n range_dig1.shape = xxx.shape\n\n # digitize heights according polar height array\n height_dig1 = np.digitize(hp.ravel(), hc)\n # reshape accordingly\n height_dig1.shape = hp.shape\n\n # what am I doing here?!\n range_dig1 = range_dig1[0:-1, 0:-1]\n height_dig1 = height_dig1[0:-1, 0:-1]\n\n # create height and range masks\n height_mask = [(height_dig1 == i).ravel().nonzero()[0] for i in range(1, len(hc))]\n range_mask = [(range_dig1 == i).ravel().nonzero()[0] for i in range(1, len(dc))]\n\n # create mip output array, set outval to inf\n mip = np.zeros((d1.shape[0], 2 * d1.shape[0]))\n mip[:] = np.inf\n\n # fill mip array,\n # in some cases there are no values found in the specified range and height\n # then we fill in nans and interpolate afterwards\n for i in range(0, len(range_mask)):\n mask1 = range_mask[i]\n found = False\n for j in range(0, len(height_mask)):\n mask2 = np.intersect1d(mask1, height_mask[j])\n # this is to catch the ValueError from the max() routine when\n # calculating on empty array\n try:\n mip[j, i] = data.ravel()[mask2].max()\n if not found:\n found = True\n except ValueError:\n if found:\n mip[j, i] = np.nan\n\n # interpolate nans inside image, do not touch outvals\n good = ~np.isnan(mip)\n xp = good.ravel().nonzero()[0]\n fp = mip[~np.isnan(mip)]\n x = np.isnan(mip).ravel().nonzero()[0]\n mip[np.isnan(mip)] = np.interp(x, xp, fp)\n\n # reset outval to nan\n mip[mip == np.inf] = np.nan\n\n return xs, ys, mip\n"
]
| [
[
"numpy.tile",
"numpy.where",
"numpy.radians",
"numpy.sort",
"numpy.broadcast_to",
"numpy.max",
"numpy.empty",
"numpy.interp",
"numpy.logical_and",
"numpy.arange",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.roll",
"numpy.stack",
"numpy.intersect1d",
"numpy.squeeze",
"numpy.isnan",
"numpy.linspace",
"numpy.meshgrid",
"numpy.asanyarray",
"numpy.unique"
]
]
|
JanWeldert/freeDOM | [
"242fc7e76943bb47f2d7cca3f56f77606f260e40"
]
| [
"freedom/reco/postfit.py"
]
| [
"\"\"\"\nProvides \"postfit\" functions. Postfits analyze the minimizer samples\nto provide alternative parameter estimates and uncertainty estimates\n\"\"\"\n\n__author__ = \"Aaron Fienberg\"\n\nimport numpy as np\nfrom numpy.polynomial import polynomial as poly, Polynomial\nfrom scipy.spatial import ConvexHull\nfrom scipy.spatial.qhull import QhullError\nfrom freedom.utils.i3frame_dataloader import DEFAULT_LABELS\n\nDELTA_LLH_CUT = 15\nDEFAULT_LOC_SPACING = (-1.5, 1.5, 10)\nDEFAULT_START_STEP = 0.05\nPAR_NAMES = DEFAULT_LABELS\n\n\ndef calc_stats(all_pts, par_names, do_angles=True):\n \"\"\"Calculate likelihood-weighted mean and variance\n\n Given llh samples from an optimizer, this function calculates the likelihood-weighted\n mean and variance for each parameter\n\n Parameters\n ----------\n all_pts : np.ndarray\n the optimizer samples; the negative llh values should be in the final column\n par_names : list\n the parameter names\n do_angles : bool, default True\n whether to calculate stats for the azimuth, zenith parameters\n\n Returns\n -------\n tuple\n ([means], [variances])\n \"\"\"\n llhs = all_pts[:, -1]\n w = np.exp(llhs.min() - llhs)\n\n means = np.zeros(len(par_names))\n variances = np.zeros(len(par_names))\n for i, name in enumerate(par_names):\n if \"zenith\" not in name and \"azimuth\" not in name:\n mean = np.average(all_pts[:, i], weights=w)\n means[i] = mean\n variances[i] = np.average((all_pts[:, i] - mean) ** 2, weights=w)\n\n try:\n zen_ind = par_names.index(\"zenith\")\n az_ind = par_names.index(\"azimuth\")\n except ValueError:\n do_angles = False\n\n if do_angles:\n zen = all_pts[:, zen_ind]\n az = all_pts[:, az_ind]\n\n p_x = np.average(np.sin(zen) * np.cos(az), weights=w)\n p_y = np.average(np.sin(zen) * np.sin(az), weights=w)\n p_z = np.average(np.cos(zen), weights=w)\n\n r = np.sqrt(p_x ** 2 + p_y ** 2 + p_z ** 2)\n\n if r != 0:\n means[zen_ind] = np.arccos(p_z / r)\n means[az_ind] = np.arctan2(p_y, p_x) % (2 * np.pi)\n\n variances[zen_ind] = np.average(\n (all_pts[:, zen_ind] - means[zen_ind]) ** 2, weights=w\n )\n\n # adjust azimuth samples prior to calculating azimuth variance\n az_pts = adjust_angle_samples(all_pts[:, az_ind], means[az_ind])\n variances[az_ind] = np.average((az_pts - means[az_ind]) ** 2, weights=w)\n\n return means, variances\n\n\ndef fit_envelope(\n par, llhs, mean, std, start_step=DEFAULT_START_STEP, loc_spacing=DEFAULT_LOC_SPACING\n):\n \"\"\"Estimate 1d parabolic llh envelopes for a single parameter\n\n Parameters\n ----------\n par : np.ndarray\n the parameter values\n llhs : np.ndarray\n the llh values\n mean : float\n estimate of the parameter best fit value\n std : float\n estimate of the parameter uncertainty\n\n Returns\n -------\n tuple\n ([parabola coeffs], [fit x pts], [fit y pts])\n \"\"\"\n min_llh = llhs.min()\n\n locs = np.linspace(*loc_spacing)\n xs = []\n ys = []\n for loc in locs:\n bin_cent = mean + std * loc\n\n step = start_step\n while True:\n pt_q = (par > bin_cent - step * std) & (par < bin_cent + step * std)\n if np.any(pt_q):\n break\n else:\n step = step * 2\n\n loc_llhs = llhs[pt_q]\n loc_pars = par[pt_q]\n\n min_ind = np.argmin(loc_llhs)\n xs.append(loc_pars[min_ind])\n ys.append(loc_llhs[min_ind] - min_llh)\n\n return poly.polyfit(xs, ys, 2), xs, ys\n\n\ndef hull_area(par, llhs, above_min=1):\n \"\"\"Estimate projected area of llh minimum for single parameter\n\n Parameters\n ----------\n par : np.ndarray\n the parameter values\n llhs : np.ndarray\n the llh values\n\n Returns\n -------\n float\n \"\"\"\n min_llh = llhs.min()\n try:\n Hull = ConvexHull(np.stack([par, llhs]).T[llhs < min_llh+above_min])\n return Hull.volume\n except QhullError:\n return np.inf\n\n\ndef furthest_point(par, llhs, above_min=2):\n \"\"\"Estimate uncertainty based on simplex point furthest away from min\n\n Parameters\n ----------\n par : np.ndarray\n the parameter values\n llhs : np.ndarray\n the llh values\n\n Returns\n -------\n float\n \"\"\"\n min_llh = llhs.min()\n min_par = par[np.argmin(llhs)]\n \n return np.max(np.abs(min_par - par[llhs<min_llh+above_min]))\n\n\ndef env_residual_rms(env, xs, ys):\n \"\"\"Calculate the RMS of the envelope fit residuals\n\n Parameters\n ----------\n env : np.ndarray\n envelope parameters (polynomial coefficients)\n xs : list\n x values for the envelope fit\n ys : list\n y values for the envelope fit\n\n Returns\n -------\n float\n \"\"\"\n xs = np.asarray(xs)\n ys = np.asarray(ys)\n\n resids = Polynomial(env)(xs) - ys\n\n return np.std(resids)\n\n\ndef calc_parabola_opt(quad_coeffs):\n \"\"\"x value of the parabola optimum\n\n Parameters\n ----------\n quad_coeffs : np.ndarray\n the parabola coefficients; p0 + p1*x + p2*x^2 -> [p0, p1, p2]\n\n Returns\n -------\n float\n \"\"\"\n if quad_coeffs[2] != 0:\n return -quad_coeffs[1] / (2 * quad_coeffs[2])\n else:\n return np.nan\n\n\ndef adjust_angle_samples(par_samps, center, angle_max=2 * np.pi):\n \"\"\"Adjust angle (usually azimuth) samples\n\n Adjusts angle values by +/- angle_max (typically 2pi) to minimize their distance\n from the \"center\" point. This improves uncertainty estimations for angular parameters\n when the best fit point is close to the edge of the allowed range.\n\n Parameters\n ----------\n par_samps : np.ndarray\n the parameter samples\n center : float\n the point from which to minimize the distance of the par_samps\n angle_max : float, default 2*pi\n\n Returns\n -------\n np.ndarray\n a new array of the adjusted parameter samples\n \"\"\"\n half_range = angle_max / 2\n high_diff_q = par_samps - center > half_range\n low_diff_q = center - par_samps > half_range\n\n par_samps = np.copy(par_samps)\n par_samps[high_diff_q] = par_samps[high_diff_q] - angle_max\n par_samps[low_diff_q] = par_samps[low_diff_q] + angle_max\n\n return par_samps\n\n\ndef postfit(all_pts, par_names=PAR_NAMES, llh_cut=DELTA_LLH_CUT):\n \"\"\"postfit routine for event reconstruction\n\n The postfit includes uncertainty estimation and alternative parameter estimators\n\n Parameters\n ----------\n all_pts : np.ndarray\n the optimizer samples; the negative llh values should be in the last column\n par_names : list, optional\n parameter names, defaults to\n [\"x\", \"y\", \"z\", \"time\", \"azimuth\", \"zenith\", \"cascade energy\", \"track energy\"]\n \"azimuth\" and \"zenith\" parameters receive special treatment\n llh_cut : float, default 15\n postfit routines only consider samples within llh_cut llh of the best sample\n\n Returns\n -------\n dict\n \"\"\"\n all_pts = np.asarray(all_pts)\n all_llhs = all_pts[:, -1]\n cut_pts = all_pts[all_llhs < all_llhs.min() + llh_cut]\n cut_llhs = cut_pts[:, -1]\n\n means, variances = calc_stats(cut_pts, par_names)\n stds = np.sqrt(variances)\n\n par_samps = [p for p in cut_pts[:, :-1].T]\n env_rets, hull_areas, furthest_points = [], [], []\n for par, mean, std, name in zip(par_samps, means, stds, par_names):\n # adjust azimuth samples before attempting to fit the envelope\n if name == \"azimuth\":\n par = adjust_angle_samples(par, mean)\n\n env_rets.append(fit_envelope(par, cut_llhs, mean, std))\n hull_areas.append(hull_area(par, cut_llhs))\n furthest_points.append(furthest_point(par, cut_llhs))\n\n resid_rms = [env_residual_rms(env, xs, ys) for env, xs, ys in env_rets]\n\n envs, env_xs, env_ys = list(zip(*env_rets))\n\n env_mins = [calc_parabola_opt(env) for env in envs]\n try:\n az_ind = par_names.index(\"azimuth\")\n env_mins[az_ind] = env_mins[az_ind] % (2 * np.pi)\n except ValueError:\n pass\n\n return dict(\n means=means,\n stds=stds,\n envs=envs,\n env_mins=env_mins,\n env_resid_rms=resid_rms,\n hull_areas=hull_areas,\n furthest_points=furthest_points,\n # env_xs=env_xs,\n # env_ys=env_ys,\n )\n"
]
| [
[
"numpy.sin",
"numpy.arccos",
"numpy.asarray",
"numpy.argmin",
"numpy.polynomial.polynomial.polyfit",
"numpy.copy",
"numpy.std",
"numpy.any",
"numpy.stack",
"numpy.polynomial.Polynomial",
"numpy.arctan2",
"numpy.sqrt",
"numpy.abs",
"numpy.average",
"numpy.cos",
"numpy.linspace"
]
]
|
Michaeldbydbcl/deepxde | [
"e55bcbbf9d95964cfc766885da382d9821f169c9"
]
| [
"examples/mf_L2H_Ex2/GP_mf_L2H_Ex2.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport GPy\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport emukit.multi_fidelity\nimport emukit.test_functions\nfrom emukit.model_wrappers.gpy_model_wrappers import GPyMultiOutputWrapper\nfrom emukit.multi_fidelity.convert_lists_to_array import convert_x_list_to_array\nfrom emukit.multi_fidelity.convert_lists_to_array import convert_xy_lists_to_arrays\nfrom emukit.multi_fidelity.models import GPyLinearMultiFidelityModel\n\n#--------------------------------------------------------------------------------\n# Import necessary functions from \"Code\" folder to process the data\nimport sys\nimport math\n\nsys.path.append('../')\nimport Code as Code\n\n# Import data process function from Code folder, Data_Process.py\nfrom Code.Data_Process import Get_Data\nfrom Code.Data_Process import Write_Data\n\n# Import the L2 error function from Code folder, Error_Func.\nfrom Code.Error_Func import L2_RE\n#--------------------------------------------------------------------------------\n\nclass LinearMFGP(object):\n def __init__(self, noise=None, n_optimization_restarts=10):\n self.noise = noise\n self.n_optimization_restarts = n_optimization_restarts\n self.model = None\n\n def train(self, x_l, y_l, x_h, y_h):\n # Construct a linear multi-fidelity model\n X_train, Y_train = convert_xy_lists_to_arrays([x_l, x_h], [y_l, y_h])\n kernels = [GPy.kern.RBF(x_l.shape[1]), GPy.kern.RBF(x_h.shape[1])]\n kernel = emukit.multi_fidelity.kernels.LinearMultiFidelityKernel(kernels)\n gpy_model = GPyLinearMultiFidelityModel(\n X_train, Y_train, kernel, n_fidelities=2\n )\n if self.noise is not None:\n gpy_model.mixed_noise.Gaussian_noise.fix(self.noise)\n gpy_model.mixed_noise.Gaussian_noise_1.fix(self.noise)\n\n # Wrap the model using the given 'GPyMultiOutputWrapper'\n self.model = GPyMultiOutputWrapper(\n gpy_model, 2, n_optimization_restarts=self.n_optimization_restarts\n )\n # Fit the model\n self.model.optimize()\n\n def predict(self, x):\n # Convert x_plot to its ndarray representation\n X = convert_x_list_to_array([x, x])\n X_l = X[: len(x)]\n X_h = X[len(x) :]\n\n # Compute mean predictions and associated variance\n lf_mean, lf_var = self.model.predict(X_l)\n lf_std = np.sqrt(lf_var)\n hf_mean, hf_var = self.model.predict(X_h)\n hf_std = np.sqrt(hf_var)\n return lf_mean, lf_std, hf_mean, hf_std\n\n\ndef main():\n\n##### From previous example of Gaussian process\n # high_fidelity = emukit.test_functions.forrester.forrester\n # low_fidelity = emukit.test_functions.forrester.forrester_low\n # x_plot = np.linspace(0, 1, 200)[:, None]\n # y_plot_l = low_fidelity(x_plot)\n # y_plot_h = high_fidelity(x_plot) \n # x_plot_l = Get_Data(\"dataset\\mf_lo_one_train.dat\", 0, 1)\n # y_plot_l = Get_Data(\"dataset\\mf_lo_one_train.dat\", 1, 2)\n x_plot_l = Get_Data(\"dataset\\mf_lo_two_train.dat\", 0, 1)\n y_plot_l = Get_Data(\"dataset\\mf_lo_two_train.dat\", 1, 2)\n \n x_plot_h = Get_Data(\"dataset\\mf_hi_train.dat\", 0, 1)\n y_plot_h = Get_Data(\"dataset\\mf_hi_train.dat\", 1, 2)\n\n # x_train_h = np.atleast_2d(np.random.permutation(x_train_l)[:8])\n # y_train_l = low_fidelity(x_train_l)\n # y_train_h = high_fidelity(x_train_h)\n x_train_l = Get_Data(\"dataset\\mf_lo_one_train.dat\", 0, 1)\n y_train_l = Get_Data(\"dataset\\mf_lo_one_train.dat\", 1, 2)\n x_train_h = Get_Data(\"dataset\\mf_hi_train.dat\", 0, 1)\n y_train_h = Get_Data(\"dataset\\mf_hi_train.dat\", 1, 2)\n\n model = LinearMFGP(noise=0, n_optimization_restarts=10)\n model.train(x_train_l, y_train_l, x_train_h, y_train_h)\n lf_mean, lf_std, hf_mean, hf_std = model.predict(x_plot_l)\n lf_mean_cal, lf_std_cal, hf_mean_cal, hf_std_cal = model.predict(x_plot_h)\n\n#---------------------------------------------------------------------\n##### Print out the predicted values and the ture values\n\n print(\"The predicted low values are: \", lf_mean_cal)\n print(\"The true low values are: \", y_train_l)\n print(\"#-------------------------------------------------------\")\n print(\"The predicted high values are: \", hf_mean_cal)\n print(\"The true high values are: \", y_train_h)\n print(\"#-------------------------------------------------------\")\n\n print(\"L2 relative error for high train is: \", L2_RE(hf_mean, y_train_h))\n print(\"L2 relative error for low train is: \", L2_RE(lf_mean, y_train_l))\n\n#---------------------------------------------------------------------\n\n plt.figure(figsize=(12, 8))\n plt.plot(x_plot_l, y_plot_l, \"b\")\n plt.plot(x_plot_h, y_plot_h, \"r\")\n plt.scatter(x_train_l, y_train_l, color=\"b\", s=40)\n plt.scatter(x_train_h, y_train_h, color=\"r\", s=40)\n plt.ylabel(\"f (x)\")\n plt.xlabel(\"x\")\n plt.legend([\"Low fidelity\", \"High fidelity\"])\n plt.title(\"High and low fidelity Forrester functions\")\n\n ## Plot the posterior mean and variance\n plt.figure(figsize=(12, 8))\n plt.fill_between(\n x_plot_l.flatten(),\n (lf_mean - 1.96 * lf_std).flatten(),\n (lf_mean + 1.96 * lf_std).flatten(),\n facecolor=\"g\",\n alpha=0.3,\n )\n plt.fill_between(\n x_plot_l.flatten(),\n (hf_mean - 1.96 * hf_std).flatten(),\n (hf_mean + 1.96 * hf_std).flatten(),\n facecolor=\"y\",\n alpha=0.3,\n )\n\n plt.plot(x_plot_l, y_plot_l, \"b\")\n plt.plot(x_plot_h, y_plot_h, \"r\")\n plt.plot(x_plot_l, lf_mean, \"--\", color=\"g\")\n plt.plot(x_plot_l, hf_mean, \"--\", color=\"y\")\n plt.scatter(x_train_l, y_train_l, color=\"b\", s=40)\n plt.scatter(x_train_h, y_train_h, color=\"r\", s=40)\n plt.ylabel(\"f (x)\")\n plt.xlabel(\"x\")\n plt.legend(\n [\n \"Low Fidelity\",\n \"High Fidelity\",\n \"Predicted Low Fidelity\",\n \"Predicted High Fidelity\",\n ]\n )\n plt.title(\n \"Linear multi-fidelity model fit to low and high fidelity function\"\n )\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()"
]
| [
[
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.sqrt",
"matplotlib.pyplot.scatter"
]
]
|
syakhmi/cs236-proj | [
"086bcec467a2461122c6b1cc8026cca41c2b439c"
]
| [
"models/embedders.py"
]
| [
"from transformers import *\n\nfrom utils.pixelcnnpp_utils import *\nimport pdb\nfrom torch.nn.utils import weight_norm as wn\nfrom tqdm import tqdm\nfrom torch.nn.utils.rnn import pad_sequence\n\n\ndef bert_encoder():\n return BERTEncoder()\n\n\ndef class_embedding(n_classes, embedding_dim):\n return nn.Embedding(n_classes, embedding_dim)\n\n\ndef unconditional(n_classes, embedding_dim):\n return nn.Embedding(n_classes, embedding_dim)\n\n\nclass Embedder(nn.Module):\n def __init__(self, embed_size):\n super(Embedder, self).__init__()\n self.embed_size = embed_size\n\n def forward(self, class_labels, captions):\n raise NotImplementedError\n\n\nclass BERTEncoder(Embedder):\n '''\n pretrained model used to embed text to a 768 dimensional vector\n '''\n\n def __init__(self):\n super(BERTEncoder, self).__init__(embed_size=768)\n self.pretrained_weights = 'bert-base-uncased'\n self.tokenizer = BertTokenizer.from_pretrained(self.pretrained_weights)\n self.model = BertModel.from_pretrained(self.pretrained_weights)\n self.max_len = 50\n\n def tokenize(self, text_batch):\n text_token_ids = [\n torch.tensor(self.tokenizer.encode(string_, add_special_tokens=False, max_length=self.max_len)) for\n string_ in text_batch]\n padded_input = pad_sequence(text_token_ids, batch_first=True, padding_value=0)\n return padded_input\n\n def forward(self, class_labels, captions):\n '''\n :param class_labels : torch.LongTensor, class ids\n :param list captions: list of strings, sentences to embed\n :return: torch.tensor embeddings: embeddings of shape (batch_size,embed_size=768)\n '''\n\n padded_input = self.tokenize(captions)\n device = list(self.parameters())[0].device\n padded_input = padded_input.to(device)\n # takes the mean of the last hidden states computed by the pre-trained BERT encoder and return it\n return self.model(padded_input)[0].mean(dim=1)\n\n\nclass OneHotClassEmbedding(Embedder):\n\n def __init__(self, num_classes):\n super(OneHotClassEmbedding, self).__init__(embed_size=num_classes)\n self.num_classes = num_classes\n self.weights = nn.Parameter(torch.eye(self.num_classes))\n\n def forward(self, class_labels, captions):\n '''\n :param class_ids : torch.LongTensor, class ids\n :param list text_batch: list of strings, sentences to embed\n :return: torch.tensor embeddings: embeddings of shape (batch_size,embed_size=768)\n '''\n return self.weights[class_labels]\n\n\nclass UnconditionalClassEmbedding(Embedder):\n def __init__(self):\n super(UnconditionalClassEmbedding, self).__init__(embed_size=1)\n\n def forward(self, class_labels, captions):\n '''\n :param class_ids : torch.LongTensor, class ids\n :param list text_batch: list of strings, sentences to embed\n :return: torch.tensor embeddings: embeddings of shape (batch_size,embed_size=768)\n '''\n zero = torch.zeros(class_labels.size(0), 1).to(class_labels.device)\n return zero\n"
]
| [
[
"torch.nn.utils.rnn.pad_sequence"
]
]
|
rishi1111/vaex | [
"b3516201d04e9277b8918dadab9df33a7c83c01a"
]
| [
"tests/ml/lightgbm_test.py"
]
| [
"import sys\nimport pytest\npytest.importorskip(\"lightgbm\")\n\nimport numpy as np\nimport lightgbm as lgb\nimport vaex.ml.lightgbm\nimport vaex.ml.datasets\nfrom vaex.utils import _ensure_strings_from_expressions\n\n\n# the parameters of the model\nparams = {\n 'learning_rate': 0.1, # learning rate\n 'max_depth': 1, # max depth of the tree\n 'colsample_bytree': 0.8, # subsample ratio of columns when constructing each tree\n 'subsample': 0.8, # subsample ratio of the training instance\n 'reg_lambda': 1, # L2 regularisation\n 'reg_alpha': 0, # L1 regularisation\n 'min_child_weight': 1, # minimum sum of instance weight (hessian) needed in a child\n 'objective': 'softmax', # learning task objective\n 'num_class': 3, # number of target classes (if classification)\n 'random_state': 42, # fixes the seed, for reproducibility\n 'n_jobs': -1} # cpu cores used\n\nparams_reg = {\n 'learning_rate': 0.1, # learning rate\n 'max_depth': 3, # max depth of the tree\n 'colsample_bytree': 0.8, # subsample ratio of columns when con$\n 'subsample': 0.8, # subsample ratio of the training ins$\n 'reg_lambda': 1, # L2 regularisation\n 'reg_alpha': 0, # L1 regularisation\n 'min_child_weight': 1, # minimum sum of instance weight (hes$\n 'objective': 'regression', # learning task objective\n 'random_state': 42, # fixes the seed, for reproducibility\n 'n_jobs': -1} # cpu cores used\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_light_gbm_virtual_columns():\n ds = vaex.ml.datasets.load_iris()\n ds['x'] = ds.sepal_length * 1\n ds['y'] = ds.sepal_width * 1\n ds['w'] = ds.petal_length * 1\n ds['z'] = ds.petal_width * 1\n ds_train, ds_test = ds.ml.train_test_split(test_size=0.2, verbose=False)\n features = ['x', 'y', 'z', 'w']\n booster = vaex.ml.lightgbm.LightGBMModel(num_boost_round=10,\n params=params,\n features=features,\n target='class_')\n booster.fit(ds_train, copy=False)\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_lightgbm():\n ds = vaex.ml.datasets.load_iris()\n ds_train, ds_test = ds.ml.train_test_split(test_size=0.2, verbose=False)\n features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\n features = _ensure_strings_from_expressions(features)\n booster = vaex.ml.lightgbm.LightGBMModel(num_boost_round=10, params=params, features=features, target='class_')\n\n booster.fit(ds_train, copy=True) # for coverage\n class_predict_train = booster.predict(ds_train, copy=True) # for coverage\n class_predict_test = booster.predict(ds_test)\n assert np.all(ds_test.col.class_.values == np.argmax(class_predict_test, axis=1))\n\n ds_train = booster.transform(ds_train) # this will add the lightgbm_prediction column\n state = ds_train.state_get()\n ds_test.state_set(state)\n assert np.all(ds_test.col.class_.values == np.argmax(ds_test.lightgbm_prediction.values, axis=1))\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_lightgbm_serialize(tmpdir):\n ds = vaex.ml.datasets.load_iris()\n features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']\n target = 'class_'\n\n gbm = ds.ml.lightgbm_model(target=target, features=features, num_boost_round=100, params=params, transform=False)\n pl = vaex.ml.Pipeline([gbm])\n pl.save(str(tmpdir.join('test.json')))\n pl.load(str(tmpdir.join('test.json')))\n\n gbm = ds.ml.lightgbm_model(target=target, features=features, num_boost_round=100, params=params, transform=False)\n gbm.state_set(gbm.state_get())\n pl = vaex.ml.Pipeline([gbm])\n pl.save(str(tmpdir.join('test.json')))\n pl.load(str(tmpdir.join('test.json')))\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_lightgbm_numerical_validation():\n ds = vaex.ml.datasets.load_iris()\n features = ['sepal_width', 'petal_length', 'sepal_length', 'petal_width']\n\n # Vanilla lightgbm\n X = np.array(ds[features])\n dtrain = lgb.Dataset(X, label=ds.class_.values)\n lgb_bst = lgb.train(params, dtrain, 3)\n lgb_pred = lgb_bst.predict(X)\n\n # Vaex.ml.lightgbm\n booster = ds.ml.lightgbm_model(target=ds.class_, num_boost_round=3, features=features, params=params, copy=False, transform=False)\n vaex_pred = booster.predict(ds)\n\n # Comparing the the predictions of lightgbm vs vaex.ml\n np.testing.assert_equal(vaex_pred, lgb_pred, verbose=True, err_msg='The predictions of vaex.ml do not match those of lightgbm')\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_lightgbm_validation_set():\n # read data\n ds = vaex.example()\n # Train and test split\n train, test = ds.ml.train_test_split(verbose=False)\n # Define the training featuress\n features = ['vx', 'vy', 'vz', 'Lz', 'L']\n # history of the booster (evaluations of the train and validation sets)\n history = {}\n # instantiate the booster model\n booster = vaex.ml.lightgbm.LightGBMModel(features=features, target='E', num_boost_round=10, params=params_reg)\n # fit the booster - including saving the history of the validation sets\n with pytest.warns(UserWarning):\n booster.fit(train, valid_sets=[train, test], valid_names=['train', 'test'],\n early_stopping_rounds=2, evals_result=history, copy=False)\n assert booster.booster.best_iteration == 10\n assert len(history['train']['l2']) == 10\n assert len(history['test']['l2']) == 10\n booster.fit(train, valid_sets=[train, test], valid_names=['train', 'test'],\n early_stopping_rounds=2, evals_result=history, copy=True)\n assert booster.booster.best_iteration == 10\n assert len(history['train']['l2']) == 10\n assert len(history['test']['l2']) == 10\n\n\[email protected](sys.version_info < (3, 6), reason=\"requires python3.6 or higher\")\ndef test_lightgbm_pipeline():\n # read data\n ds = vaex.example()\n # train test splot\n train, test = ds.ml.train_test_split(verbose=False)\n # add virtual columns\n train['r'] = np.sqrt(train.x**2 + train.y**2 + train.z**2)\n # Do a pca\n features = ['vx', 'vy', 'vz', 'Lz', 'L']\n pca = train.ml.pca(n_components=3, features=features, transform=False)\n train = pca.transform(train)\n # Do state transfer\n st = train.ml.state_transfer()\n # now the lightgbm model thingy\n features = ['r', 'PCA_0', 'PCA_1', 'PCA_2']\n # The booster model from vaex.ml\n booster = train.ml.lightgbm_model(target='E', num_boost_round=10, features=features, params=params_reg, transform=False)\n # Create a pipeline\n pp = vaex.ml.Pipeline([st, booster])\n # Use the pipeline\n pred = pp.predict(test) # This works\n trans = pp.transform(test) # This will crash (softly)\n # trans.evaluate('lightgbm_prediction') # This is where the problem happens\n np.testing.assert_equal(pred, trans.evaluate('lightgbm_prediction'),\n verbose=True, err_msg='The predictions from the fit and transform method do not match')\n"
]
| [
[
"numpy.array",
"numpy.argmax",
"numpy.sqrt",
"numpy.testing.assert_equal"
]
]
|
naver-ai/cgl_fairness | [
"00d3bec233c9b3e0f88496118abaed8321ca3159"
]
| [
"trainer/trainer_factory.py"
]
| [
"\"\"\"\ncgl_fairness\nCopyright (c) 2022-present NAVER Corp.\nMIT license\n\"\"\"\nimport torch\nimport numpy as np\nimport os\nimport torch.nn as nn\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau, MultiStepLR, CosineAnnealingLR\nfrom sklearn.metrics import confusion_matrix\nfrom utils import make_log_name\n\n\nclass TrainerFactory:\n def __init__(self):\n pass\n\n @staticmethod\n def get_trainer(method, **kwargs):\n if method == 'scratch':\n import trainer.vanilla_train as trainer\n elif method == 'mfd':\n import trainer.mfd as trainer\n elif method == 'fairhsic':\n import trainer.fairhsic as trainer\n elif method == 'adv':\n import trainer.adv_debiasing as trainer\n elif method == 'reweighting':\n import trainer.reweighting as trainer\n elif method == 'groupdro':\n import trainer.groupdro as trainer\n elif method == 'groupdro_ori':\n import trainer.groupdro as trainer\n else:\n raise Exception('Not allowed method')\n return trainer.Trainer(**kwargs)\n\n\nclass GenericTrainer:\n '''\n Base class for trainer; to implement a new training routine, inherit from this.\n '''\n def __init__(self, model, args, optimizer, teacher=None):\n self.get_inter = args.get_inter\n\n self.record = args.record\n self.cuda = args.cuda\n self.device = args.device\n self.t_device = args.t_device\n self.term = args.term\n self.lr = args.lr\n self.epochs = args.epochs\n self.method = args.method\n self.model_name =args.model\n self.model = model\n self.teacher = teacher\n self.optimizer = optimizer\n self.optim_type = args.optimizer\n self.log_dir = args.log_dir\n self.criterion=torch.nn.CrossEntropyLoss()\n self.scheduler = None\n\n self.log_name = make_log_name(args)\n self.log_dir = os.path.join(args.log_dir, args.date, args.dataset, args.method)\n self.save_dir = os.path.join(args.save_dir, args.date, args.dataset, args.method)\n\n if self.optim_type == 'Adam' and self.optimizer is not None:\n self.scheduler = ReduceLROnPlateau(self.optimizer)\n elif self.optim_type == 'AdamP' and self.optimizer is not None:\n if self.epochs < 100:\n t_max = self.epochs\n elif self.epochs == 200:\n t_max = 66\n self.scheduler = CosineAnnealingLR(self.optimizer, t_max)\n else:\n self.scheduler = MultiStepLR(self.optimizer, [60, 120, 180], gamma=0.1)\n #self.scheduler = MultiStepLR(self.optimizer, [30, 60, 90], gamma=0.1)\n\n\n def evaluate(self, model, loader, criterion, device=None):\n model.eval()\n num_groups = loader.dataset.num_groups\n num_classes = loader.dataset.num_classes\n device = self.device if device is None else device\n\n eval_acc = 0\n eval_loss = 0\n eval_eopp_list = torch.zeros(num_groups, num_classes).cuda(device)\n eval_data_count = torch.zeros(num_groups, num_classes).cuda(device)\n\n if 'Custom' in type(loader).__name__:\n loader = loader.generate()\n with torch.no_grad():\n for j, eval_data in enumerate(loader):\n if j == 100:\n break\n # Get the inputs\n inputs, _, groups, classes, _ = eval_data\n #\n labels = classes\n if self.cuda:\n inputs = inputs.cuda(device)\n labels = labels.cuda(device)\n groups = groups.cuda(device)\n\n outputs = model(inputs)\n\n loss = criterion(outputs, labels)\n eval_loss += loss.item() * len(labels)\n preds = torch.argmax(outputs, 1)\n acc = (preds == labels).float().squeeze()\n eval_acc += acc.sum()\n\n for g in range(num_groups):\n for l in range(num_classes):\n eval_eopp_list[g, l] += acc[(groups == g) * (labels == l)].sum()\n eval_data_count[g, l] += torch.sum((groups == g) * (labels == l))\n\n eval_loss = eval_loss / eval_data_count.sum()\n eval_acc = eval_acc / eval_data_count.sum()\n eval_eopp_list = eval_eopp_list / eval_data_count\n eval_max_eopp = torch.max(eval_eopp_list, dim=0)[0] - torch.min(eval_eopp_list, dim=0)[0]\n eval_avg_eopp = torch.mean(eval_max_eopp).item()\n eval_max_eopp = torch.max(eval_max_eopp).item()\n model.train()\n return eval_loss, eval_acc, eval_max_eopp, eval_avg_eopp, eval_eopp_list\n\n def save_model(self, save_dir, log_name=\"\", model=None):\n model_to_save = self.model if model is None else model\n model_savepath = os.path.join(save_dir, log_name + '.pt')\n torch.save(model_to_save.state_dict(), model_savepath)\n\n print('Model saved to %s' % model_savepath)\n\n def compute_confusion_matix(self, dataset='test', num_classes=2,\n dataloader=None, log_dir=\"\", log_name=\"\"):\n from scipy.io import savemat\n from collections import defaultdict\n self.model.eval()\n confu_mat = defaultdict(lambda: np.zeros((num_classes, num_classes)))\n print('# of {} data : {}'.format(dataset, len(dataloader.dataset)))\n\n predict_mat = {}\n output_set = torch.tensor([])\n group_set = torch.tensor([], dtype=torch.long)\n target_set = torch.tensor([], dtype=torch.long)\n intermediate_feature_set = torch.tensor([])\n\n with torch.no_grad():\n for i, data in enumerate(dataloader):\n # Get the inputs\n inputs, _, groups, targets, _ = data\n labels = targets\n groups = groups.long()\n\n if self.cuda:\n inputs = inputs.cuda(self.device)\n labels = labels.cuda(self.device)\n\n # forward\n\n outputs = self.model(inputs)\n if self.get_inter:\n intermediate_feature = self.model.forward(inputs, get_inter=True)[-2]\n\n group_set = torch.cat((group_set, groups))\n target_set = torch.cat((target_set, targets))\n output_set = torch.cat((output_set, outputs.cpu()))\n if self.get_inter:\n intermediate_feature_set = torch.cat((intermediate_feature_set, intermediate_feature.cpu()))\n\n pred = torch.argmax(outputs, 1)\n group_element = list(torch.unique(groups).numpy())\n for i in group_element:\n mask = groups == i\n if len(labels[mask]) != 0:\n confu_mat[str(i)] += confusion_matrix(\n labels[mask].cpu().numpy(), pred[mask].cpu().numpy(),\n labels=[i for i in range(num_classes)])\n\n predict_mat['group_set'] = group_set.numpy()\n predict_mat['target_set'] = target_set.numpy()\n predict_mat['output_set'] = output_set.numpy()\n if self.get_inter:\n predict_mat['intermediate_feature_set'] = intermediate_feature_set.numpy()\n\n savepath = os.path.join(log_dir, log_name + '_{}_confu'.format(dataset))\n print('savepath', savepath)\n savemat(savepath, confu_mat, appendmat=True)\n\n savepath_pred = os.path.join(log_dir, log_name + '_{}_pred'.format(dataset))\n savemat(savepath_pred, predict_mat, appendmat=True)\n\n print('Computed confusion matrix for {} dataset successfully!'.format(dataset))\n return confu_mat\n"
]
| [
[
"torch.zeros",
"torch.cat",
"torch.argmax",
"torch.min",
"numpy.zeros",
"torch.max",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.unique",
"torch.no_grad",
"scipy.io.savemat",
"torch.optim.lr_scheduler.MultiStepLR",
"torch.tensor",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.mean",
"torch.nn.CrossEntropyLoss",
"torch.sum"
]
]
|
Palour/cnn_mnist | [
"e546176c0cf6c574c3624926192a8932a8a2a390"
]
| [
"cnn_conv2d_3_mnist.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 23 15:10:07 2019\n\n@author: zixks\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# \nx = tf.placeholder(tf.float32, [None, 784])\ny = tf.placeholder(tf.float32, [None, 10])\n\n\ndef wb_variable(shape):\n initial = tf.truncated_normal(shape, stddev = 0.1)\n return tf.Variable(initial)\n\n\ndef conv2d_kernel(shape=[3, 3, 1, 1]):\n kernel = tf.truncated_normal(shape=shape, dtype=tf.float32, stddev=0.1)\n return tf.Variable(kernel)\n\n\ndef input_layer(x, name='input_layer'):\n with tf.name_scope(name):\n img = tf.reshape(x, [-1, 28, 28, 1])\n return img\n\n\ndef max_pool_2x2(x, name):\n with tf.name_scope(name):\n return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],\n strides = [1, 2, 2, 1], padding = 'SAME')\n\n\ndef conv2d_layer(x, kernel, bias, name, activation=None, strides=(1, 1, 1, 1), \n padding='SAME'):\n \n if name.strip() == '':\n raise Exception('name can not be null')\n \n if kernel is None or x is None:\n raise Exception('x and kernel can not be null')\n \n with tf.name_scope(name):\n conv2dout = tf.nn.conv2d(input=x, filter=kernel, strides=strides, \n padding=padding)\n layer = conv2dout + bias\n \n if activation is not None:\n return tf.nn.relu(layer)\n else:\n return layer\n\nif __name__ == '__main__':\n x = tf.placeholder(tf.float32, [None, 784])\n y = tf.placeholder(tf.float32, [None, 10])\n in_layer = input_layer(x, 'input_layer')\n \n #########################################################################\n conv_1_1 = conv2d_layer(x=in_layer, kernel=wb_variable([3, 3, 1, 32]), \n bias=wb_variable([32]), activation=tf.nn.relu, \n name='conv_1_1')\n conv_1_2 = conv2d_layer(x=conv_1_1, kernel=wb_variable([3, 3, 32, 32]),\n bias=wb_variable([32]), activation=tf.nn.relu,\n name='conv_1_2')\n pool_1 = max_pool_2x2(x=conv_1_2, name='pool_2')\n \n # 14\n #########################################################################\n conv_2_1 = conv2d_layer(x=pool_1, kernel=wb_variable([3, 3, 32, 64]), \n bias=wb_variable([64]), activation=tf.nn.relu, \n name='conv_2_1')\n conv_2_2 = conv2d_layer(x=conv_2_1, kernel=wb_variable([3, 3, 64, 64]), \n bias=wb_variable([64]), activation=tf.nn.relu, \n name='conv_2_2')\n pool_2 = max_pool_2x2(x=conv_2_2, name='pool_2')\n \n # 7\n #########################################################################\n conv_3_1 = conv2d_layer(x=pool_2, kernel=wb_variable([3, 3, 64, 128]), \n bias=wb_variable([128]), activation=tf.nn.relu, \n name='conv_3_1')\n conv_3_2 = conv2d_layer(x=conv_3_1, kernel=wb_variable([3, 3, 128, 128]), \n bias=wb_variable([128]), activation=tf.nn.relu, \n name='conv_3_2')\n \n \n \n with tf.name_scope('FULL_CONNECT_1'):\n w6 = wb_variable([128 * 7 * 7, 1024])\n b6 = wb_variable([1024])\n f_6_in = tf.reshape(conv_3_2, shape=[-1, 128 * 7 * 7])\n f_6_out = tf.nn.relu(tf.matmul(f_6_in, w6 ))\n \n\n with tf.name_scope('DROPOUT_1'):\n keep_prob = tf.placeholder(\"float\")\n dropout_1 = tf.nn.dropout(f_6_out, keep_prob=keep_prob)\n \n \n with tf.name_scope('SOFTMAX_1'):\n W_fc2 = wb_variable([1024, 10])\n b_fc2 = wb_variable([10])\n y_conv = tf.nn.softmax(tf.matmul(dropout_1, W_fc2) + b_fc2)\n \n \n loss = -tf.reduce_sum(y * tf.log(y_conv)) #计算交叉熵\n \n train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)\n correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction,\"float\"))\n \n \n with tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n tf.summary.FileWriter(\"logs/\", sess.graph)\n for i in range(100000):\n batch = mnist.train.next_batch(50)\n sess.run(train_step, feed_dict={x: batch[0], y: batch[1], \n keep_prob:0.5})\n \n if i % 100 == 0:\n lt = loss.eval(session=sess, feed_dict = {x:batch[0], y:batch[1], keep_prob:1.0})\n ld = loss.eval(session=sess, feed_dict = {x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})\n train_accuracy = accuracy.eval(session = sess,\n feed_dict = {x:batch[0], y:batch[1], keep_prob:1.0})\n test = accuracy.eval(session = sess,\n feed_dict = {x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})\n print(\"epoch {}, train accuracy {}%, dev accuracy {}%, train loss {}%, dev loss {}%\".format(\n mnist.train.epochs_completed, round(train_accuracy * 100, 2), round(test * 100, 2), round(lt * 100, 2), round(ld * 100, 2)))\n"
]
| [
[
"tensorflow.train.AdamOptimizer",
"tensorflow.nn.conv2d",
"tensorflow.nn.relu",
"tensorflow.initialize_all_variables",
"tensorflow.argmax",
"tensorflow.Session",
"tensorflow.Variable",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.reshape",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.log",
"tensorflow.placeholder",
"tensorflow.name_scope",
"tensorflow.summary.FileWriter",
"tensorflow.nn.max_pool",
"tensorflow.nn.dropout",
"tensorflow.cast"
]
]
|
lnls-fac/apsuite | [
"f96b0c6ce2314d6cd6e0b2d14d33e4b5a588e9a1"
]
| [
"apsuite/commisslib/meas_touschek_lifetime.py"
]
| [
"\"\"\".\"\"\"\nimport time as _time\nfrom functools import partial as _partial\nfrom threading import Event as _Event\n\nimport numpy as _np\nimport numpy.polynomial.polynomial as _np_pfit\nimport matplotlib.pyplot as _mplt\nimport matplotlib.gridspec as _mgs\nimport scipy.optimize as _scy_opt\nimport scipy.integrate as _scy_int\n\nfrom siriuspy.devices import BPM, CurrInfoSI, EGun, RFCav, Tune, Trigger, \\\n Event, EVG\nfrom siriuspy.search import BPMSearch\nfrom siriuspy.epics import PV\n\nfrom ..utils import ThreadedMeasBaseClass as _BaseClass, \\\n ParamsBaseClass as _ParamsBaseClass\n\n\nclass MeasTouschekParams(_ParamsBaseClass):\n \"\"\".\"\"\"\n\n DEFAULT_BPMNAME = 'SI-01M2:DI-BPM'\n\n def __init__(self):\n \"\"\".\"\"\"\n _ParamsBaseClass().__init__()\n self.total_duration = 0 # [s] 0 means infinity\n self.save_partial = True\n self.bpm_name = self.DEFAULT_BPMNAME\n self.bpm_attenuation = 14 # [dB]\n self.acquisition_timeout = 1 # [s]\n self.acquisition_period = 4 # [s]\n self.mask_beg_bunch_a = 180\n self.mask_end_bunch_a = 0\n self.mask_beg_bunch_b = 0\n self.mask_end_bunch_b = 240\n self.bucket_bunch_a = 1\n self.bucket_bunch_b = 550\n self.acq_nrsamples_pre = 10000\n self.acq_nrsamples_post = 10000\n self.filename = ''\n\n def __str__(self):\n \"\"\".\"\"\"\n dtmp = '{0:20s} = {1:9d}\\n'.format\n ftmp = '{0:20s} = {1:9.4f} {2:s}\\n'.format\n stmp = '{0:20s} = {1:}\\n'.format\n\n stg = ''\n stg += ftmp(\n 'total_duration', self.total_duration, '[s] (0) means forever')\n stg += f'save_partial = {str(bool(self.save_partial)):s}'\n stg += stmp('bpm_name', self.bpm_name)\n stg += ftmp('bpm_attenuation', self.bpm_attenuation, '[dB]')\n stg += ftmp('acquisition_timeout', self.acquisition_timeout, '[s]')\n stg += ftmp('acquisition_period', self.acquisition_period, '[s]')\n stg += dtmp('mask_beg_bunch_a', self.mask_beg_bunch_a)\n stg += dtmp('mask_end_bunch_a', self.mask_end_bunch_a)\n stg += dtmp('mask_beg_bunch_b', self.mask_beg_bunch_b)\n stg += dtmp('mask_end_bunch_b', self.mask_end_bunch_b)\n stg += dtmp('bucket_bunch_a', self.bucket_bunch_a)\n stg += dtmp('bucket_bunch_b', self.bucket_bunch_b)\n stg += dtmp('acq_nrsamples_pre', self.acq_nrsamples_pre)\n stg += dtmp('acq_nrsamples_post', self.acq_nrsamples_post)\n stg += stmp('filename', self.filename)\n return stg\n\n\nclass MeasTouschekLifetime(_BaseClass):\n \"\"\".\"\"\"\n\n AVG_PRESSURE_PV = 'Calc:VA-CCG-SI-Avg:Pressure-Mon'\n RFFEAttMB = 0 # [dB] Multibunch Attenuation\n RFFEAttSB = 30 # [dB] Singlebunch Attenuation\n FILTER_OUTLIER = 0.2 # Relative error data/fitting\n\n # calibration curves measured during machine shift in 2021/09/21:\n EXCCURVE_SUMA = [-1.836e-3, 1.9795e-4]\n EXCCURVE_SUMB = [-2.086e-3, 1.9875e-4]\n OFFSET_DCCT = 8.4e-3 # [mA]\n\n def __init__(self, isonline=True):\n \"\"\".\"\"\"\n _BaseClass.__init__(\n self, params=MeasTouschekParams(), target=self._do_measure,\n isonline=isonline)\n\n self._recursion = 0\n self._updated_evt = _Event()\n\n if isonline:\n self._bpms = dict()\n bpmnames = BPMSearch.get_names({'sec': 'SI', 'dev': 'BPM'})\n bpm = BPM(bpmnames[0])\n self._bpms[bpmnames[0]] = bpm\n propties = bpm.auto_monitor_status()\n for name in bpmnames[1:]:\n bpm = BPM(name)\n for ppt in propties:\n bpm.set_auto_monitor(ppt, False)\n self._bpms[name] = bpm\n\n self.devices.update(self._bpms)\n self.devices['trigger'] = Trigger('SI-Fam:TI-BPM')\n self.devices['event'] = Event('Study')\n self.devices['evg'] = EVG()\n self.devices['currinfo'] = CurrInfoSI()\n self.devices['egun'] = EGun()\n self.devices['rfcav'] = RFCav(RFCav.DEVICES.SI)\n self.devices['tune'] = Tune(Tune.DEVICES.SI)\n self.pvs['avg_pressure'] = PV(MeasTouschekLifetime.AVG_PRESSURE_PV)\n\n def set_bpms_attenuation(self, value_att=RFFEAttSB):\n \"\"\".\"\"\"\n if not self.isonline:\n raise ConnectionError('Cannot do that in offline mode.')\n\n for bpm in self._bpms.values():\n bpm.rffe_att = value_att\n _time.sleep(1.0)\n\n mstr = ''\n for name, bpm in self._bpms.items():\n if bpm.rffe_att != value_att:\n mstr += (\n f'\\n{name:<20s}: ' +\n f'rb {bpm.rffe_att:.0f} != sp {value_att:.0f}')\n if not mstr:\n print('RFFE attenuation set confirmed in all BPMs.')\n else:\n print(\n 'RFFE attenuation set confirmed in all BPMs, except:' + mstr)\n\n def cmd_switch_to_single_bunch(self):\n \"\"\".\"\"\"\n return self.devices['egun'].cmd_switch_to_single_bunch()\n\n def cmd_switch_to_multi_bunch(self):\n \"\"\".\"\"\"\n return self.devices['egun'].cmd_switch_to_multi_bunch()\n\n def process_data(\n self, proc_type='fit_model', nr_bunches=1, nr_intervals=1,\n window=1000, include_bunlen=False, outlier_std=6,\n outlier_max_recursion=3):\n \"\"\".\"\"\"\n if 'analysis' in self.data:\n self.analysis = self.data.pop('analysis')\n if 'measure' in self.data:\n self.data = self.data.pop('measure')\n\n # Pre-processing of data:\n self._handle_data_lens()\n self._remove_nans()\n self._calc_current_per_bunch(nr_bunches=nr_bunches)\n self._remove_outliers(\n num_std=outlier_std, max_recursion=outlier_max_recursion)\n\n if proc_type.lower().startswith('fit_model'):\n self._process_model_totalrate(nr_intervals=nr_intervals)\n else:\n self._process_diffbunches(window, include_bunlen)\n\n @classmethod\n def totalrate_model(cls, curr, *coeff):\n \"\"\".\"\"\"\n total = cls.gasrate_model(curr, *coeff[:-2])\n total += cls.touschekrate_model(curr, *coeff[-2:])\n return total\n\n @classmethod\n def gasrate_model(cls, curr, *gases):\n \"\"\".\"\"\"\n nr_gas = len(gases)\n totsiz = curr.size//2\n quo = totsiz // nr_gas\n rest = totsiz % nr_gas\n lst = []\n for i, gas in enumerate(gases):\n siz = quo + (i < rest)\n lst.extend([gas, ]*siz)\n return _np.r_[lst, lst]\n\n @classmethod\n def touschekrate_model(cls, curr, *coeff):\n \"\"\".\"\"\"\n tous = coeff[-2]\n blen = coeff[-1]\n return tous*curr/(1 + blen*curr)\n\n @classmethod\n def curr_model(cls, curr, *coeff, tim=None):\n \"\"\".\"\"\"\n size = curr.size // 2\n curra = curr[:size]\n currb = curr[size:]\n\n drate_mod = -cls.totalrate_model(curr, *coeff)\n dratea_mod = drate_mod[:size]\n drateb_mod = drate_mod[size:]\n\n curra_mod = _scy_int.cumtrapz(dratea_mod * curra, x=tim, initial=0.0)\n currb_mod = _scy_int.cumtrapz(drateb_mod * currb, x=tim, initial=0.0)\n curra_mod += curra.mean() - curra_mod.mean()\n currb_mod += currb.mean() - currb_mod.mean()\n return _np.r_[curra_mod, currb_mod]\n\n def plot_touschek_lifetime(\n self, fname=None, title=None, fitting=False, rate=True):\n \"\"\".\"\"\"\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n tsck_a, tsck_b = anly['touschek_a'], anly['touschek_b']\n window = anly.get('window', 1)\n\n fig = _mplt.figure(figsize=(8, 6))\n gs = _mgs.GridSpec(1, 1)\n ax1 = _mplt.subplot(gs[0, 0])\n pwr = -1 if rate else 1\n ax1.plot(curr_a, tsck_a**pwr, '.', color='C0', label='Bunch A')\n ax1.plot(curr_b, tsck_b**pwr, '.', color='C1', label='Bunch B')\n\n if fitting:\n currs = _np.r_[curr_a, curr_b]\n tscks = _np.r_[tsck_a, tsck_b]\n poly = _np_pfit.polyfit(currs, 1/tscks, deg=1)\n currs_fit = _np.linspace(currs.min(), currs.max(), 2*currs.size)\n rate_fit = _np_pfit.polyval(currs_fit, poly)\n tsck_fit = 1/rate_fit\n label = r\"Fitting, $\\tau \\times I_b$={:.4f} C\".format(3.6*poly[1])\n ax1.plot(\n currs_fit, tsck_fit**pwr, '--', color='k', lw=3, label=label)\n\n ax1.set_xlabel('current single bunch [mA]')\n ylabel = 'rate [1/h]' if rate else 'lifetime [h]'\n ax1.set_ylabel('Touschek ' + ylabel)\n window_time = anly['tim_a'][window]/60\n stg0 = f'Fitting with window = {window:d} '\n stg0 += f'points ({window_time:.1f} min)'\n stg = title or stg0\n ax1.set_title(stg)\n ax1.legend()\n ax1.grid(ls='--', alpha=0.5)\n _mplt.tight_layout(True)\n if fname:\n fig.savefig(fname, dpi=300, format='png')\n return fig, ax1\n\n def plot_gas_lifetime(self, fname=None, title=None, rate=True):\n \"\"\".\"\"\"\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n gaslt = anly['gas_lifetime']\n window = anly.get('window', 1)\n\n total_curr = curr_a + curr_b\n\n fig = _mplt.figure(figsize=(8, 6))\n gs = _mgs.GridSpec(1, 1)\n ax1 = _mplt.subplot(gs[0, 0])\n\n pwr = -1 if rate else 1\n ax1.plot(total_curr, gaslt**pwr, '.', color='C0')\n ax1.set_xlabel('Total current [mA]')\n\n ylabel = 'rate [1/h]' if rate else 'lifetime [h]'\n ax1.set_ylabel('Gas ' + ylabel)\n\n window_time = anly['tim_a'][window]/60\n stg0 = f'Fitting with window = {window:d} '\n stg0 += f'points ({window_time:.1f} min)'\n stg = title or stg0\n ax1.set_title(stg)\n\n ax1.grid(ls='--', alpha=0.5)\n _mplt.tight_layout(True)\n if fname:\n fig.savefig(fname, dpi=300, format='png')\n return fig, ax1\n\n def plot_total_lifetime(\n self, fname=None, title=None, fitting=False,\n rate=True, errors=True):\n \"\"\".\"\"\"\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n total_a, total_b = anly['total_lifetime_a'], anly['total_lifetime_b']\n err_a, err_b = anly['fiterror_a'], anly['fiterror_b']\n window = anly.get('window', 1)\n\n fig = _mplt.figure(figsize=(8, 6))\n gs = _mgs.GridSpec(1, 1)\n ax1 = _mplt.subplot(gs[0, 0])\n pwr = -1 if rate else 1\n\n if errors:\n errbar_a = err_a/total_a**2 if rate else err_a\n ax1.errorbar(\n curr_a, total_a**pwr, yerr=errbar_a,\n marker='.', ls='', color='C0',\n label=f'Bunch A - Max. Error: {_np.max(errbar_a):.2e}')\n errbar_b = err_b/total_b**2 if rate else err_b\n ax1.errorbar(\n curr_b, total_b**pwr, yerr=errbar_b,\n marker='.', ls='', color='C1',\n label=f'Bunch B - Max. Error: {_np.max(errbar_b):.2e}')\n else:\n ax1.plot(curr_a, total_a**pwr, '-', color='C0', label='Bunch A')\n ax1.plot(curr_b, total_b**pwr, '-', color='C1', label='Bunch B')\n\n if fitting:\n currs = _np.hstack((curr_a, curr_b))\n totls = _np.hstack((total_a, total_b))\n poly = _np_pfit.polyfit(currs, 1/totls, deg=1)\n currs_fit = _np.linspace(currs.min(), currs.max(), 2*currs.size)\n rate_fit = _np_pfit.polyval(currs_fit, poly)\n totls = 1/rate_fit\n label = 'Fitting'\n ax1.plot(\n currs_fit, totls**pwr, ls='--', color='k', lw=3, label=label)\n\n ax1.set_xlabel('current single bunch [mA]')\n ylabel = 'rate [1/h]' if rate else 'lifetime [h]'\n ax1.set_ylabel('Total ' + ylabel)\n window_time = anly['tim_a'][window]/60\n stg0 = f'Fitting with window = {window:d} '\n stg0 += f'points ({window_time:.1f} min)'\n stg = title or stg0\n ax1.set_title(stg)\n ax1.legend()\n ax1.grid(ls='--', alpha=0.5)\n _mplt.tight_layout(True)\n if fname:\n fig.savefig(fname, dpi=300, format='png')\n return fig, ax1\n\n def plot_fitting_error(self, fname=None, title=None):\n \"\"\".\"\"\"\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n fiterror_a, fiterror_b = anly['fiterror_a'], anly['fiterror_b']\n window = anly.get('window', 1)\n\n fig = _mplt.figure(figsize=(8, 6))\n gs = _mgs.GridSpec(1, 1)\n ax1 = _mplt.subplot(gs[0, 0])\n ax1.plot(curr_a, fiterror_a, '.', color='C0', label='Bunch A')\n ax1.plot(curr_b, fiterror_b, '.', color='C1', label='Bunch B')\n\n ax1.set_xlabel('current single bunch [mA]')\n ax1.set_ylabel('Fitting Error')\n window_time = anly['tim_a'][window]/60\n stg0 = f'Fitting with window = {window:d} '\n stg0 += f'points ({window_time:.1f} min)'\n stg = title or stg0\n ax1.set_title(stg)\n ax1.legend()\n ax1.grid(ls='--', alpha=0.5)\n _mplt.tight_layout(True)\n if fname:\n fig.savefig(fname, dpi=300, format='png')\n return fig, ax1\n\n def plot_current_decay(self, fname=None, title=None):\n \"\"\".\"\"\"\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n dt_a = anly['tim_a']/3600\n dt_b = anly['tim_b']/3600\n\n fig = _mplt.figure(figsize=(8, 6))\n gs = _mgs.GridSpec(1, 1)\n ax1 = _mplt.subplot(gs[0, 0])\n ax1.plot(dt_a, curr_a, '.', color='C0', label='Bunch A')\n ax1.plot(dt_b, curr_b, '.', color='C1', label='Bunch B')\n ax1.set_xlabel('time [h]')\n ax1.set_ylabel('bunch current [mA]')\n ax1.set_title(title)\n ax1.legend()\n ax1.grid(ls='--', alpha=0.5)\n _mplt.tight_layout(True)\n if fname:\n fig.savefig(fname, dpi=300, format='png')\n return fig, ax1\n\n def _handle_data_lens(self):\n meas = self.data\n len_min = min(len(meas['sum_a']), len(meas['sum_b']))\n\n sum_a = _np.array(meas['sum_a'])[:len_min]\n sum_b = _np.array(meas['sum_b'])[:len_min]\n tim_a = _np.array(meas['tim_a'])[:len_min]\n tim_b = _np.array(meas['tim_b'])[:len_min]\n currt = _np.array(meas['current'])[:len_min]\n\n anly = dict()\n anly['sum_a'], anly['sum_b'] = sum_a, sum_b\n anly['tim_a'], anly['tim_b'] = tim_a - tim_a[0], tim_b - tim_b[0]\n anly['current'] = currt\n self.analysis = anly\n\n def _remove_nans(self):\n anly = self.analysis\n sum_a, sum_b = anly['sum_a'], anly['sum_b']\n tim_a, tim_b = anly['tim_a'], anly['tim_b']\n currt = anly['current']\n\n nanidx = _np.isnan(sum_a).ravel()\n nanidx |= _np.isnan(sum_b).ravel()\n sum_a, sum_b = sum_a[~nanidx], sum_b[~nanidx]\n tim_a, tim_b = tim_a[~nanidx], tim_b[~nanidx]\n currt = currt[~nanidx]\n\n anly = dict()\n anly['sum_a'], anly['sum_b'] = sum_a, sum_b\n anly['tim_a'], anly['tim_b'] = tim_a, tim_b\n anly['current'] = currt\n self.analysis = anly\n\n def _calc_current_per_bunch(self, nr_bunches=1):\n \"\"\".\"\"\"\n anly = self.analysis\n anly['current'] -= self.OFFSET_DCCT\n anly['current_a'] = _np_pfit.polyval(\n anly['sum_a']/nr_bunches, self.EXCCURVE_SUMA)\n anly['current_b'] = _np_pfit.polyval(\n anly['sum_b']/nr_bunches, self.EXCCURVE_SUMB)\n\n def _remove_outliers(self, num_std=6, max_recursion=3):\n anly = self.analysis\n\n dt_a = anly['tim_a']/3600\n dt_b = anly['tim_b']/3600\n curr_a = anly['current_a']\n curr_b = anly['current_b']\n\n loga = _np.log(curr_a)\n logb = _np.log(curr_b)\n pol_a = _np_pfit.polyfit(dt_a, loga, deg=1)\n pol_b = _np_pfit.polyfit(dt_b, logb, deg=1)\n fit_a = _np.exp(_np_pfit.polyval(dt_a, pol_a))\n fit_b = _np.exp(_np_pfit.polyval(dt_b, pol_b))\n\n diff_a = _np.abs(curr_a - fit_a)\n diff_b = _np.abs(curr_b - fit_b)\n\n out = num_std\n idx_keep = (diff_a < out*diff_a.std()) & (diff_b < out*diff_b.std())\n\n for key in anly.keys():\n anly[key] = anly[key][idx_keep]\n\n print('Filtering outliers: recursion = {0:d}, num = {1:d}'.format(\n self._recursion, curr_a.size - _np.sum(idx_keep)))\n if _np.sum(idx_keep) < curr_a.size and self._recursion < max_recursion:\n self._recursion += 1\n self._remove_outliers(num_std, max_recursion=max_recursion)\n else:\n self._recursion = 0\n\n def _process_model_totalrate(self, nr_intervals=5):\n anly = self.analysis\n curra = anly['current_a']\n currb = anly['current_b']\n tim = anly['tim_a']\n size = curra.size\n currt = _np.r_[curra, currb]\n\n # First do one round without bounds to use LM algorithm and find the\n # true miminum:\n coeff0 = [1/40/3600, ] * nr_intervals + [1/10/3600, 0.2]\n coeff, pconv = _scy_opt.curve_fit(\n _partial(self.curr_model, tim=tim), currt, currt, p0=coeff0)\n\n # Then fix the negative arguments to make the final round with bounds:\n coeff = _np.array(coeff)\n idcs = coeff < 0\n if idcs.any():\n coeff[idcs] = 0\n lower = [0, ] * (nr_intervals + 2)\n upper = [_np.inf, ] * (nr_intervals + 2)\n coeff, pconv = _scy_opt.curve_fit(\n _partial(self.curr_model, tim=tim), currt, currt, p0=coeff,\n bounds=(lower, upper))\n errs = _np.sqrt(_np.diag(pconv))\n\n tousrate = self.touschekrate_model(currt, *coeff[-2:])\n gasrate = self.gasrate_model(currt, *coeff[:-2])\n gasrate *= 3600\n tousrate *= 3600\n totrate = tousrate + gasrate\n\n currt_fit = self.curr_model(currt, *coeff, tim=tim)\n\n anly['coeffs'] = coeff\n anly['coeffs_pconv'] = pconv\n anly['current_a_fit'] = currt_fit[:size]\n anly['current_b_fit'] = currt_fit[size:]\n anly['total_lifetime_a'] = 1 / totrate[:size]\n anly['total_lifetime_b'] = 1 / totrate[size:]\n fiterr = _np.sqrt(_np.sum(errs*errs/_np.array(coeff)))\n anly['fiterror_a'] = 1/totrate[:size] * fiterr\n anly['fiterror_b'] = 1/totrate[size:] * fiterr\n\n # Calc Touschek and Gas Lifetime\n anly['touschek_a'] = 1/tousrate[:size]\n anly['touschek_b'] = 1/tousrate[size:]\n anly['gas_lifetime_a'] = 1/gasrate[:size]\n anly['gas_lifetime_b'] = 1/gasrate[size:]\n anly['gas_lifetime'] = 1/gasrate[:size]\n\n def _process_diffbunches(self, window, include_bunlen=False):\n anly = self.analysis\n\n tim_a, tim_b = anly['tim_a'], anly['tim_b']\n curr_a, curr_b = anly['current_a'], anly['current_b']\n currt = anly['current']\n\n # Fit total lifetime\n window = (int(window) // 2)*2 + 1\n ltime_a, fiterr_a = self._fit_lifetime(tim_a, curr_a, window=window)\n ltime_b, fiterr_b = self._fit_lifetime(tim_b, curr_b, window=window)\n anly['window'] = window\n anly['total_lifetime_a'] = ltime_a\n anly['total_lifetime_b'] = ltime_b\n anly['fiterror_a'] = fiterr_a\n anly['fiterror_b'] = fiterr_b\n\n # Resize all vectors to match lifetime size\n leng = window // 2\n slc = slice(leng+1, -leng)\n # slc = slice(0, -window)\n curr_a = curr_a[slc]\n curr_b = curr_b[slc]\n tim_a = tim_a[slc]\n tim_b = tim_b[slc]\n currt = currt[slc]\n anly['current_a'] = curr_a\n anly['current_b'] = curr_b\n anly['tim_a'] = tim_a - tim_a[0]\n anly['tim_b'] = tim_b - tim_a[0]\n anly['current'] = currt\n\n # Calc Touschek Lifetime from Total Lifetime of both bunches\n if include_bunlen:\n self._calc_touschek_lifetime()\n tsck_a = anly['touschek_a']\n tsck_b = anly['touschek_b']\n else:\n num = 1 - curr_b/curr_a\n den = 1/ltime_a - 1/ltime_b\n tsck_a = num/den\n tsck_b = tsck_a * curr_a / curr_b\n anly['touschek_a'] = tsck_a\n anly['touschek_b'] = tsck_b\n\n # Recover Gas Lifetime\n gas_rate_a = 1/ltime_a - 1/tsck_a\n gas_rate_b = 1/ltime_b - 1/tsck_b\n anly['gas_lifetime_a'] = 1/gas_rate_a\n anly['gas_lifetime_b'] = 1/gas_rate_b\n anly['gas_lifetime'] = 2/(gas_rate_a + gas_rate_b)\n\n def _calc_touschek_lifetime(self):\n \"\"\".\"\"\"\n def model(curr, tous, blen):\n curr_a, curr_b = curr\n alpha_a = tous*curr_a/(1+blen*curr_a)\n alpha_b = tous*curr_b/(1+blen*curr_b)\n return alpha_a - alpha_b\n\n anly = self.analysis\n curr_a, curr_b = anly['current_a'], anly['current_b']\n ltime_a, ltime_b = anly['total_lifetime_a'], anly['total_lifetime_b']\n curr_a = curr_a[:ltime_a.size]\n curr_b = curr_b[:ltime_b.size]\n\n p0_ = (1, 1)\n alpha_total = 1/ltime_a - 1/ltime_b\n coeffs, pconv = _scy_opt.curve_fit(\n model, (curr_a, curr_b), alpha_total, p0=p0_)\n tous, blen = coeffs\n\n alpha_a = tous*curr_a/(1+blen*curr_a)\n alpha_b = tous*curr_b/(1+blen*curr_b)\n anly['touschek_a'] = 1/alpha_a\n anly['touschek_b'] = 1/alpha_b\n anly['alpha_total'] = alpha_total\n anly['tous_coeffs'] = coeffs\n anly['tous_coeffs_pconv'] = pconv\n\n def _do_measure(self):\n meas = dict(\n sum_a=[], sum_b=[], nan_a=[], nan_b=[], tim_a=[], tim_b=[],\n current=[], rf_voltage=[], avg_pressure=[], tunex=[], tuney=[])\n parms = self.params\n\n curr = self.devices['currinfo']\n rfcav = self.devices['rfcav']\n tune = self.devices['tune']\n press = self.pvs['avg_pressure']\n bpm = self.devices[parms.bpm_name]\n\n excx0 = tune.enablex\n excy0 = tune.enabley\n\n pvsum = bpm.pv_object('GEN_SUMArrayData')\n pvsum.auto_monitor = True\n pvsum.add_callback(self._pv_updated)\n\n self.devices['trigger'].source = 'Study'\n self.devices['event'].mode = 'Continuous'\n self.devices['evg'].cmd_update_events()\n\n bpm.cmd_acq_abort()\n bpm.acq_nrsamples_pre = parms.acq_nrsamples_pre\n bpm.acq_nrsamples_post = parms.acq_nrsamples_post\n bpm.acq_repeat = 'normal'\n bpm.acq_trigger = 'external'\n bpm.rffe_att = parms.bpm_attenuation\n bpm.tbt_mask_enbl = 1\n\n maxidx = parms.total_duration / parms.acquisition_period\n maxidx = float('inf') if maxidx < 1 else maxidx\n idx = 0\n\n while idx < maxidx and not self._stopevt.is_set():\n # Get data for bunch with higher current\n bpm.tbt_mask_beg = parms.mask_beg_bunch_a\n bpm.tbt_mask_end = parms.mask_end_bunch_a\n self._updated_evt.clear()\n bpm.cmd_acq_start()\n bpm.wait_acq_finish(timeout=parms.acquisition_timeout)\n self._updated_evt.wait(timeout=parms.acquisition_timeout)\n suma = bpm.mt_possum\n meas['sum_a'].append(_np.nanmean(suma))\n meas['nan_a'].append(_np.sum(_np.isnan(suma)))\n meas['tim_a'].append(_time.time())\n\n # Get data for bunch with lower current\n bpm.tbt_mask_beg = parms.mask_beg_bunch_b\n bpm.tbt_mask_end = parms.mask_end_bunch_b\n self._updated_evt.clear()\n bpm.cmd_acq_start()\n bpm.wait_acq_finish(timeout=parms.acquisition_timeout)\n self._updated_evt.wait(timeout=parms.acquisition_timeout)\n sumb = bpm.mt_possum\n meas['sum_b'].append(_np.nanmean(sumb))\n meas['nan_b'].append(_np.sum(_np.isnan(sumb)))\n meas['tim_b'].append(_time.time())\n\n # Get other relevant parameters\n meas['current'].append(curr.current)\n meas['tunex'] = tune.tunex\n meas['tuney'] = tune.tuney\n meas['rf_voltage'].append(rfcav.dev_cavmon.gap_voltage)\n meas['avg_pressure'].append(press.value)\n\n if not idx % 100 and parms.save_partial:\n # Only get the tune at every 100 iterations not to disturb the\n # beam too much with the tune shaker\n tunex, tuney = self._get_tunes()\n meas['tunex'].append(tunex)\n meas['tuney'].append(tuney)\n\n self.data = meas\n self.save_data(fname=parms.filename, overwrite=True)\n print(f'{idx:04d}: data saved to file.')\n idx += 1\n _time.sleep(parms.acquisition_period)\n\n tune.enablex = int(excx0)\n tune.enabley = int(excy0)\n self.devices['trigger'].source = 'DigSI'\n self.devices['event'].mode = 'External'\n self.devices['evg'].cmd_update_events()\n pvsum.clear_callbacks()\n pvsum.auto_monitor = False\n\n self.data = meas\n self.save_data(fname=parms.filename, overwrite=True)\n print(f'{idx:04d}: data saved to file.')\n print('Done!')\n\n def _pv_updated(self, *args, **kwargs):\n _ = args, kwargs\n self._updated_evt.set()\n\n def _get_tunes(self):\n tune = self.devices['tune']\n tune.enablex = 1\n tune.enabley = 1\n _time.sleep(1)\n tunex = tune.tunex\n tuney = tune.tuney\n tune.enablex = 0\n tune.enabley = 0\n return tunex, tuney\n\n @staticmethod\n def _linear_fun(tim, *coeff):\n amp, tau = coeff\n return amp*(1 - tim/tau)\n\n @staticmethod\n def _fit_lifetime(dtime, current, window):\n \"\"\".\"\"\"\n lifetimes, fiterrors = [], []\n for idx in range(len(dtime)-window):\n beg = idx\n end = idx + window\n dtm = _np.array(dtime[beg:end]) - dtime[beg]\n dtm /= 3600\n dcurr = current[beg:end]/current[beg]\n coeff, pconv = _scy_opt.curve_fit(\n MeasTouschekLifetime._linear_fun, dtm, dcurr, p0=(1, 1))\n errs = _np.sqrt(_np.diag(pconv))\n lifetimes.append(coeff[-1])\n fiterrors.append(errs[-1])\n return _np.array(lifetimes), _np.array(fiterrors)\n"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.isnan",
"scipy.optimize.curve_fit",
"numpy.log",
"numpy.polynomial.polynomial.polyval",
"numpy.polynomial.polynomial.polyfit",
"numpy.sum",
"scipy.integrate.cumtrapz",
"matplotlib.pyplot.figure",
"numpy.nanmean",
"matplotlib.pyplot.tight_layout",
"numpy.abs",
"numpy.hstack",
"numpy.diag",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.subplot"
]
]
|
rahil1304/News-Companion | [
"0aaa453674c89ff07298f11f1b390a640672281d"
]
| [
"News-companion/Un-Fake(Web)/News/NewsCompanion/views.py"
]
| [
"from django.shortcuts import render\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\n# Create your views here.\r\nfrom newspaper import Article\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimport re\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization, LSTM, Embedding, Reshape,Bidirectional\r\nfrom keras.models import load_model, model_from_json\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nimport tensorflow as tf\r\nimport os\r\nimport urllib\r\n\r\nfrom urllib.request import urlretrieve\r\n\r\nfrom os import mkdir, makedirs, remove, listdir\r\n\r\nfrom collections import Counter\r\nfrom keras.engine.topology import Layer\r\nimport keras.backend as K\r\nfrom keras import initializers\r\nfrom keras.models import model_from_yaml\r\nimport pickle\r\nfrom keras.backend import clear_session\r\n\r\nfrom pyimagesearch.transform import four_point_transform\r\nfrom skimage.filters import threshold_local\r\nimport numpy as np\r\n#import argparse\r\nimport cv2\r\nimport imutils\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport sys\r\nimport scipy\r\n\r\n\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.allow_growth = True\r\nsession = tf.Session(config=config)\r\n\r\n\r\nclass Embedding2(Layer):\r\n\r\n def __init__(self, input_dim, output_dim, fixed_weights, embeddings_initializer='uniform', \r\n input_length=None, **kwargs):\r\n kwargs['dtype'] = 'int32'\r\n if 'input_shape' not in kwargs:\r\n if input_length:\r\n kwargs['input_shape'] = (input_length,)\r\n else:\r\n kwargs['input_shape'] = (None,)\r\n super(Embedding2, self).__init__(**kwargs)\r\n \r\n self.input_dim = input_dim\r\n self.output_dim = output_dim\r\n self.embeddings_initializer = embeddings_initializer\r\n self.fixed_weights = fixed_weights\r\n self.num_trainable = input_dim - len(fixed_weights)\r\n self.input_length = input_length\r\n \r\n w_mean = fixed_weights.mean(axis=0)\r\n w_std = fixed_weights.std(axis=0)\r\n self.variable_weights = w_mean + w_std*np.random.randn(self.num_trainable, output_dim)\r\n\r\n def build(self, input_shape, name='embeddings'): \r\n fixed_weight = K.variable(self.fixed_weights, name=name+'_fixed')\r\n variable_weight = K.variable(self.variable_weights, name=name+'_var')\r\n \r\n self._trainable_weights.append(variable_weight)\r\n self._non_trainable_weights.append(fixed_weight)\r\n \r\n self.embeddings = K.concatenate([fixed_weight, variable_weight], axis=0)\r\n \r\n self.built = True\r\n\r\n def call(self, inputs):\r\n if K.dtype(inputs) != 'int32':\r\n inputs = K.cast(inputs, 'int32')\r\n out = K.gather(self.embeddings, inputs)\r\n return out\r\n\r\n def compute_output_shape(self, input_shape):\r\n if not self.input_length:\r\n input_length = input_shape[1]\r\n else:\r\n input_length = self.input_length\r\n return (input_shape[0], input_length, self.output_dim)\r\n \r\nwith open('objs.pkl','rb') as f: # Python 3: open(..., 'rb')\r\n fixed_weights2,word2num_length,X_test,y_test,word2num= pickle.load(f)\r\n \r\nnew_model = Sequential()\r\nnew_model.add(Embedding2(word2num_length, 50,\r\n fixed_weights= fixed_weights2)) # , batch_size=batch_size\r\nnew_model.add(Bidirectional(LSTM(64)))\r\nnew_model.add(Dense(1, activation='sigmoid'))\r\n\r\n# rmsprop = keras.optimizers.RMSprop(lr=1e-4)\r\n\r\nnew_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\nnew_model.load_weights('model.h5')\r\nnew_model._make_predict_function()\r\nscore = new_model.evaluate(X_test,y_test)\r\nprint(\"%s: %.2f%%\" % (new_model.metrics_names[1], score[1]*100))\r\n\r\n\r\n\r\ndef home(request):\r\n if request.method == 'POST':\r\n if request.POST.get('link') != '':\r\n text=request.POST.get('link')\r\n # text = text.encode('utf-8')\r\n print(str(text))\r\n sentence = str(text).lower()\r\n sentence_num = [word2num[w] if w in word2num else word2num['<Other>'] for w in sentence.split()]\r\n sentence_num = [word2num['<PAD>']]*(0) + sentence_num\r\n sentence_num = np.array(sentence_num)\r\n reliability = (new_model.predict(sentence_num[None,:])).flatten()[0] * 100\r\n reliability = int(reliability)\r\n if(reliability <15):\r\n rel = \"Not Reliable :(\"\r\n elif(reliability > 15 and reliability < 60):\r\n rel = \"Reliable :)\"\r\n elif(reliability > 60):\r\n rel = \" Very Reliable\"\r\n print(rel)\r\n\r\n\r\n result=rel\r\n return render(request,'result.html', {'result': result})\r\n else:\r\n file = request.POST.get('file')\r\n print(file[-3:])\r\n if(file[-3:] == 'jpg', 'png','JPG' or file[-4:] == 'jpeg'):\r\n image = cv2.imread(file)\r\n ratio = image.shape[0] / 500.0\r\n orig = image.copy()\r\n image = imutils.resize(image, height = 500)\r\n\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n gray = cv2.GaussianBlur(gray, (5, 5), 0)\r\n edged = cv2.Canny(gray, 75, 200)\r\n screenCnt=0\r\n\r\n cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\r\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\r\n cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]\r\n\r\n\r\n for c in cnts:\r\n \r\n peri = cv2.arcLength(c, True)\r\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\r\n\r\n if len(approx) == 4:\r\n screenCnt = approx\r\n break\r\n else:\r\n break\r\n \r\n\r\n if(len(approx)==4):\r\n ctr = np.array(screenCnt).reshape((-1,1,2)).astype(np.int32)\r\n cv2.drawContours(image, [ctr], -1, (0, 255, 0), 2)\r\n warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)\r\n warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\r\n T = threshold_local(warped, 11, offset = 10, method = \"gaussian\")\r\n warped = (warped > T).astype(\"uint8\") * 255\r\n cv2.imshow(\"Original\", imutils.resize(orig, height = 650))\r\n cv2.imshow(\"Scanned\", imutils.resize(warped, height = 650))\r\n text = pytesseract.image_to_string(orig, lang='eng')\r\n\r\n cv2.waitKey(0)\r\n\r\n else:\r\n\r\n text = pytesseract.image_to_string(orig, lang='eng')\r\n # cv2.imshow(\"Original\", imutils.resize(orig, height = 650))\r\n\r\n # cv2.waitKey(0)\r\n \r\n text = text.replace(\"\\r\",\"\")\r\n text = text.replace(\"\\n\",\"\")\r\n # j=1\r\n # text2=\"\"\r\n # for character in text:\r\n # if(character=='\\n'):\r\n # j+=1\r\n # if(j>3 and j<8):\r\n # if(character != '\\n' ):\r\n # text2 = text2 + character\r\n # print(text2)\r\n # text = text.encode('utf-8')\r\n \r\n sentence = str(text[0:300]).lower()\r\n # print(\"Image result\" + sentence)\r\n sentence_num = [word2num[w] if w in word2num else word2num['<Other>'] for w in sentence.split()]\r\n sentence_num = [word2num['<PAD>']]*(0) + sentence_num\r\n sentence_num = np.array(sentence_num)\r\n reliability = (new_model.predict(sentence_num[None,:])).flatten()[0] * 100\r\n reliability = int(reliability)\r\n if(reliability <15):\r\n rel = \"Not Reliable :(\"\r\n elif(reliability > 15 and reliability < 60):\r\n rel = \"Reliable :)\"\r\n elif(reliability > 60):\r\n rel = \" Very Reliable\"\r\n print(rel)\r\n\r\n\r\n result=rel\r\n return render(request,'result.html', {'result': result}) \r\n else:\r\n with open(file, 'r') as f:\r\n text = f.read()\r\n result=''\r\n return render(request,result, {'result': result})\r\n return render(request, 'home.html')\r\n\r\n\r\ndef result(request, result):\r\n return render(request, 'result.html', {'result': result})\r\n\r\ndef pie(request):\r\n return render(request, 'pie.html')\r\n pass\r\n\r\ndef about(request):\r\n return render(request, 'about.html')\r\n pass\r\n"
]
| [
[
"tensorflow.ConfigProto",
"numpy.array",
"tensorflow.Session",
"numpy.random.randn"
]
]
|
FRidh/auraliser | [
"f20f037ca131299d1a584ea640bb39d83b5ceb26"
]
| [
"bin/read_from_wav.py"
]
| [
"\"\"\"\nExample that shows how to unapply the Doppler shift to an existing wav file.\n\"\"\"\n\n\nimport sys\nsys.path.append('..')\n\n\nimport numpy as np\n\n#from auraliser import Signal\n\nfrom auraliser.signal import Signal\nfrom auraliser.model import Model, Source, Receiver\n\nimport matplotlib as mpl\nmpl.rc('figure', figsize=(12,10))\n\n\n\ndef main():\n \n filename = '../data/recording.wav'\n \n signal = Signal.from_wav(filename)\n signal.plot_spectrogram('../data/spec.png')\n \n \"\"\"Let's create a model. We ultimately need position vectors for the source and receiver.\"\"\"\n model = Model()\n fs = signal.sample_frequency\n \n duration = fs * len(signal)\n \n velocity = 65.0 # Velocity of the source in m/s. Guess\n \n distance_per_sample = velocity / fs # Velocity vector expressed in meters per sample\n \n \n xyz_strip = np.array([1600.0, 0.0, -10.0]) # Touchdown coordinate\n xyz_receiver = np.array([0.0, 0.0, 0.0]) # Receiver\n \n xyz_passage = np.array([0.0, 0.0, 65.0]) # Height of source at passage\n \n distance = xyz_strip - xyz_passage # Distance between passage and touchdown \n orientation = distance / np.linalg.norm(distance) # This results in the bearing of the aircraft.\n \n print( np.degrees(np.arctan(orientation[2]/orientation[0])))\n \n assert(orientation[2] < 0.0) # The aircraft should decrease in altitude...\n \n dxds = distance_per_sample * orientation # Let's create a velocity vector instead!!\n \n t_passage = 23.8 # Time after start of recording that the aircraft passes the receiver location\n \n source = np.outer( dxds, np.arange(0, len(signal))) # Position of source, not yet given the right offset.\n \n s_passage = t_passage * fs\n \n source = source.transpose()\n \n source = source - source[s_passage,:] + xyz_passage.transpose()\n \n #print ( ( - xyz_receiver ).transpose() )\n \n #source = Source(\n \n \n model.geometry.source.position.x = source[:,0]\n model.geometry.source.position.y = source[:,1]\n model.geometry.source.position.z = source[:,2]\n \n receiver = np.ones((len(signal), 3)) * xyz_receiver\n model.geometry.receiver.position.x = receiver[:,0]\n model.geometry.receiver.position.y = receiver[:,1]\n model.geometry.receiver.position.z = receiver[:,2]\n \n #print model.geometry.source.position.as_array()[-1,:]\n \n ###model.geometry.plot_position('../data/position.png')\n ###model.geometry.plot_distance('../data/distance.png', signal=signal)\n ###model.plot_velocity('../data/velocity.png', signal=signal)\n ###model.plot_delay('../data/delay.png', signal=signal)\n ###model.plot_time_compression('../data/time_compression.png')\n \n assert source[-1,2] > xyz_strip[2] # That we have no crash...\n \n signal.plot_spectrogram('../data/original.png')\n \n l = len(signal)\n \n signal = model.unapply_atmospheric_absorption(signal, taps=200, n_d=50)[0:l]\n signal = model.unapply_spherical_spreading(signal)\n signal = model.unapply_doppler(signal)\n \n signal.plot_spectrogram('../data/after_absorption.png')\n \n \n \n \n signal.to_wav('../data/after_absorption.wav')\n \n ###model.unapply_spherical_spreading(signal)\n ####signal.to_wav('../data/after_spreading.wav')\n \n \n ###model.unapply_doppler(signal)\n ###signal.to_wav('../data/after_doppler_and_spreading.wav')\n ###signal.plot_spectrogram('../data/after_doppler_and_spreading.png')\n \n \n #signal.plot_scaleogram('../data/scaleogram.png')\n \n \nif __name__ == \"__main__\":\n main()"
]
| [
[
"numpy.array",
"numpy.linalg.norm",
"numpy.arctan",
"matplotlib.rc"
]
]
|
petermao/iri2016 | [
"065355a78b8950efab3c9bdd688f2c07de2086e6"
]
| [
"src/iri2016/plots.py"
]
| [
"import xarray\nfrom matplotlib.pyplot import figure\n\n\ndef timeprofile(iono: xarray.Dataset):\n\n fig = figure(figsize=(16, 12))\n axs = fig.subplots(3, 1, sharex=True).ravel()\n\n fig.suptitle(\n f\"{str(iono.time[0].values)[:-13]} to \"\n f\"{str(iono.time[-1].values)[:-13]}\\n\"\n f\"Glat, Glon: {iono.glat.item()}, {iono.glon.item()}\"\n )\n\n ax = axs[0]\n ax.plot(iono.time, iono[\"NmF2\"], label=\"N$_m$F$_2$\")\n ax.plot(iono.time, iono[\"NmF1\"], label=\"N$_m$F$_1$\")\n ax.plot(iono.time, iono[\"NmE\"], label=\"N$_m$E\")\n ax.set_title(\"Maximum number densities vs. ionospheric layer\")\n ax.set_ylabel(\"(m$^{-3}$)\")\n ax.set_yscale(\"log\")\n ax.legend(loc=\"best\")\n ax = axs[1]\n ax.plot(iono.time, iono[\"hmF2\"], label=\"h$_m$F$_2$\")\n ax.plot(iono.time, iono[\"hmF1\"], label=\"h$_m$F$_1$\")\n ax.plot(iono.time, iono[\"hmE\"], label=\"h$_m$E\")\n ax.set_title(\"Height of maximum density vs. ionospheric layer\")\n ax.set_ylabel(\"(km)\")\n ax.set_ylim((90, None))\n ax.legend(loc=\"best\")\n ax = axs[2]\n ax.plot(iono.time, iono[\"foF2\"], label=\"foF2\")\n ax.set_title(\"F2 layer plasma frequency\")\n ax.set_ylabel(\"(MHz)\")\n\n for a in axs.ravel():\n a.grid(True)\n\n # %%\n fig = figure(figsize=(16, 12))\n axs = fig.subplots(1, 1, sharex=True)\n\n fig.suptitle(\n f\"{str(iono.time[0].values)[:-13]} to \"\n f\"{str(iono.time[-1].values)[:-13]}\\n\"\n f\"Glat, Glon: {iono.glat.item()}, {iono.glon.item()}\"\n )\n # %% Tec(time)\n ax = axs\n ax.plot(iono.time, iono[\"TEC\"], label=\"TEC\")\n ax.set_ylabel(\"(m$^{-2}$)\")\n ax.set_title(\"Total Electron Content (TEC)\")\n # ax.set_yscale('log')\n ax.legend(loc=\"best\")\n ax.grid(True)\n # %% ion_drift(time)\n # ax = axs[1]\n # ax.plot(iono.time, iono[\"EqVertIonDrift\"], label=r\"V$_y$\")\n # ax.set_xlabel(\"time (UTC)\")\n # ax.set_ylabel(\"(m/s)\")\n # ax.legend(loc=\"best\")\n\n # for a in axs.ravel():\n # a.grid(True)\n\n # %% Ne(time)\n fg = figure()\n ax = fg.gca()\n hi = ax.pcolormesh(iono.time, iono.alt_km, iono[\"ne\"].values.T)\n fg.colorbar(hi, ax=ax).set_label(\"[m$^{-3}$]\")\n ax.set_ylabel(\"altitude [km]\")\n ax.set_title(\"$N_e$ vs. altitude and time\")\n\n\ndef altprofile(iono: xarray.Dataset):\n fig = figure(figsize=(16, 6))\n axs = fig.subplots(1, 2)\n\n fig.suptitle(f\"{str(iono.time[0].values)[:-13]}\\n\" f\"Glat, Glon: {iono.glat.item()}, {iono.glon.item()}\")\n\n pn = axs[0]\n pn.plot(iono[\"ne\"], iono.alt_km, label=\"N$_e$\")\n # pn.set_title(iri2016Obj.title1)\n pn.set_xlabel(\"Density (m$^{-3}$)\")\n pn.set_ylabel(\"Altitude (km)\")\n pn.set_xscale(\"log\")\n pn.legend(loc=\"best\")\n pn.grid(True)\n\n pn = axs[1]\n pn.plot(iono[\"Ti\"], iono.alt_km, label=\"T$_i$\")\n pn.plot(iono[\"Te\"], iono.alt_km, label=\"T$_e$\")\n # pn.set_title(iri2016Obj.title2)\n pn.set_xlabel(\"Temperature (K)\")\n pn.set_ylabel(\"Altitude (km)\")\n pn.legend(loc=\"best\")\n pn.grid(True)\n\n\ndef latprofile(iono: xarray.Dataset):\n\n fig = figure(figsize=(8, 12))\n axs = fig.subplots(2, 1, sharex=True)\n\n ax = axs[0]\n\n ax.plot(iono[\"glat\"], iono[\"NmF2\"], label=\"N$_m$F$_2$\")\n ax.plot(iono[\"glat\"], iono[\"NmF1\"], label=\"N$_m$F$_1$\")\n ax.plot(iono[\"glat\"], iono[\"NmE\"], label=\"N$_m$E\")\n ax.set_title(str(iono.time[0].values)[:-13] + f' latitude {iono[\"glat\"][[0, -1]].values}')\n # ax.set_xlim(iono.lat[[0, -1]])\n ax.set_xlabel(r\"Geog. Lat. ($^\\circ$)\")\n ax.set_ylabel(\"(m$^{-3}$)\")\n ax.set_yscale(\"log\")\n\n ax = axs[1]\n ax.plot(iono[\"glat\"], iono[\"hmF2\"], label=\"h$_m$F$_2$\")\n ax.plot(iono[\"glat\"], iono[\"hmF1\"], label=\"h$_m$F$_1$\")\n ax.plot(iono[\"glat\"], iono[\"hmE\"], label=\"h$_m$E\")\n ax.set_xlim(iono[\"glat\"][[0, -1]])\n ax.set_title(str(iono.time[0].values)[:-13] + f' latitude {iono[\"glat\"][[0, -1]].values}')\n ax.set_xlabel(r\"Geog. Lat. ($^\\circ$)\")\n ax.set_ylabel(\"(km)\")\n\n for a in axs:\n a.legend(loc=\"best\")\n a.grid(True)\n"
]
| [
[
"matplotlib.pyplot.figure"
]
]
|
xiaohu2015/tflearn | [
"30ed136f9ac3c48fa41a693fd27c6112bbc6e489"
]
| [
"tflearn/variables.py"
]
| [
"# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\nimport tensorflow as tf\nimport tflearn\n\n\[email protected]_arg_scope\ndef variable(name, shape=None, dtype=tf.float32, initializer=None,\n regularizer=None, trainable=True, collections=None, device='',\n restore=True):\n \"\"\" variable.\n\n Instantiate a new variable.\n\n Arguments:\n name: `str`. A name for this variable.\n shape: list of `int`. The variable shape (optional).\n dtype: `type`. The variable data type.\n initializer: `str` or `Tensor`. The variable initialization. (See\n tflearn.initializations for references).\n regularizer: `str` or `Tensor`. The variable regularizer. (See\n tflearn.losses for references).\n trainable: `bool`. If True, this variable weights will be trained.\n collections: `str`. A collection to add the new variable to (optional).\n device: `str`. Device ID to store the variable. Default: '/cpu:0'.\n restore: `bool`. Restore or not this variable when loading a\n pre-trained model (Only compatible with tflearn pre-built\n training functions).\n\n Returns:\n A Variable.\n\n \"\"\"\n\n if isinstance(initializer, str):\n initializer = tflearn.initializations.get(initializer)()\n # Remove shape param if initializer is a Tensor\n if not callable(initializer) and isinstance(initializer, tf.Tensor):\n shape = None\n\n if isinstance(regularizer, str):\n regularizer = tflearn.losses.get(regularizer)\n\n with tf.device(device):\n\n try:\n var = tf.get_variable(name, shape=shape, dtype=dtype,\n initializer=initializer,\n regularizer=regularizer,\n trainable=trainable,\n collections=collections)\n # Fix for old TF versions\n except Exception as e:\n var = tf.get_variable(name, shape=shape, dtype=dtype,\n initializer=initializer,\n trainable=trainable,\n collections=collections)\n if regularizer is not None:\n tflearn.add_weights_regularizer(var, regularizer)\n\n if not restore:\n tf.add_to_collection(tf.GraphKeys.EXCL_RESTORE_VARS, var)\n\n return var\n\n\ndef get_all_variables():\n \"\"\" get_all_variables.\n\n Get all Graph variables.\n\n Returns:\n A list of Variables.\n\n \"\"\"\n return tf.get_collection(tf.GraphKeys.VARIABLES)\n\n\ndef get_all_trainable_variable():\n \"\"\" get_all_variables.\n\n Get all Graph trainable variables.\n\n Returns:\n A list of Variables.\n\n \"\"\"\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n\n\ndef get_layer_variables_by_name(name):\n \"\"\" get_layer_variables_by_name.\n\n Retrieve a layer's variables, given its name.\n\n Arguments:\n name: `str`. The layer name.\n\n Returns:\n A list of Variables.\n\n \"\"\"\n return tf.get_collection(tf.GraphKeys.LAYER_VARIABLES + '/' + name)\n\n# Shortcut\nget_layer_variables = get_layer_variables_by_name\n\n\ndef get_value(var, session=None):\n \"\"\" get_value.\n\n Get a variable's value. If no session provided, use default one.\n\n Arguments:\n var: `Variable`. The variable to get value from.\n session: `Session`. The session to run the op. Default: the default\n session.\n\n Returns:\n The variable's value.\n\n \"\"\"\n if not session:\n session = tf.get_default_session()\n return var.eval(session)\n\n\ndef set_value(var, value, session=None):\n \"\"\" set_value.\n\n Set a variable's value. If no session provided, use default one.\n\n Arguments:\n var: `Variable`. The variable to assign a value.\n value: The value to assign. Must be compatible with variable dtype.\n session: `Session`. The session to perform the assignation.\n Default: the default session.\n\n \"\"\"\n op = tf.assign(var, value=value)\n if not session:\n session = tf.get_default_session()\n return op.eval(session=session)\n\n\ndef get_inputs_placeholder_by_name(name):\n vars = tf.get_collection(tf.GraphKeys.INPUTS)\n tflearn_name = name + '/X:0'\n if len(vars) == 0:\n raise Exception(\"The collection `tf.GraphKeys.INPUTS` is empty! \"\n \"Cannot retrieve placeholder. In case placeholder was \"\n \"defined outside TFLearn `input_data` layer, please \"\n \"add it to that collection.\")\n for e in vars:\n if e.name == tflearn_name:\n return e\n # Search again, in case defined outside TFLearn wrappers.\n for e in vars:\n if e.name == name:\n return e\n\n return None\n\n\ndef get_targets_placeholder_by_name(name):\n vars = tf.get_collection(tf.GraphKeys.TARGETS)\n tflearn_name = name + '/Y:0'\n if len(vars) == 0:\n raise Exception(\"The collection `tf.GraphKeys.INPUTS` is empty! \"\n \"Cannot retrieve placeholder. In case placeholder was \"\n \"defined outside TFLearn `input_data` layer, please \"\n \"add it to that collection.\")\n for e in vars:\n if e.name == tflearn_name:\n return e\n # Search again, in case defined outside TFLearn wrappers.\n for e in vars:\n if e.name == name:\n return e\n\n return None\n"
]
| [
[
"tensorflow.get_default_session",
"tensorflow.assign",
"tensorflow.get_variable",
"tensorflow.device",
"tensorflow.add_to_collection",
"tensorflow.get_collection"
]
]
|
shankarganesh1234/MLProjects | [
"7a9273f0f0d43994dfdee6dc44214f0dd2d92352"
]
| [
"Bitcoin/BitcoinPrices.py"
]
| [
"import numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\nimport matplotlib.pyplot as plt\n\npath = \"/Users/shankarganesh/files/bitcoin/bitcoin_dataset.csv\"\n\ndata = pd.read_csv(path, parse_dates=[\"Date\"], index_col=\"Date\")\ndata[\"btc_trade_volume\"].fillna(method=\"ffill\", inplace=True)\ndata.sort_index(inplace=True)\n\nx_cols = [col for col in data.columns if col not in ['Date', 'btc_market_price'] if data[col].dtype == 'float64']\n\nlabels = []\nvalues = []\nfor col in x_cols:\n labels.append(col)\n values.append(np.corrcoef(data[col].values, data.btc_market_price.values)[0, 1])\ncorr_df = pd.DataFrame({'col_labels': labels, 'corr_values': values})\ncorr_df = corr_df.sort_values(by='corr_values')\n\nind = np.arange(len(labels))\nwidth = 0.9\nfig, ax = plt.subplots(figsize=(12, 40))\nrects = ax.barh(ind, np.array(corr_df.corr_values.values), color='y')\nax.set_yticks(ind)\nax.set_yticklabels(corr_df.col_labels.values, rotation='horizontal')\nax.set_xlabel(\"Correlation coefficient\")\nax.set_title(\"Correlation coefficient of the variables\")\n# autolabel(rects)\n\ntop_features = corr_df.tail(10)[\"col_labels\"]\n\nt = np.append(top_features, \"btc_market_price\")\n\n# top_features\n\nfeature_data = data[t].copy()\n\nfeature_data[\"lagprice1\"] = feature_data[\"btc_market_price\"].shift(1)\nfeature_data[\"lagprice\"] = feature_data[\"btc_market_price\"].shift(-1)\n\n# del feature_data[\"btc_market_price\"]\n\nfeature_data.dropna(axis=0, how='any', inplace=True)\n\nfeature_data.tail(5)\n\n\n# In[8]:\n\n\ndef evaluate(model, test_features, test_labels):\n predictions = model.predict(test_features)\n errors = abs(predictions - test_labels)\n mape = 100 * np.mean(errors / test_labels)\n accuracy = 100 - mape\n print('Model Performance')\n print('Average Error: {:0.4f} .'.format(np.mean(errors)))\n print('Accuracy = {:0.2f}%.'.format(accuracy))\n print(mean_absolute_error(test_labels, predictions))\n return accuracy\n\n\ntrain = feature_data.head(2300)\ntest = feature_data.tail(718)\n\n# train, test = train_test_split(data,test_size=0.25)\n\ny_train = train.iloc[:, -1]\nx_train = train.iloc[:, :-1]\n\n# x_train.head(5)\n\ny_test = test.iloc[:, -1]\nx_test = test.iloc[:, :-1]\n\nregressor = linear_model.LinearRegression()\n\nregressor.fit(x_train, y_train)\n\nprint\nevaluate(regressor, x_test, y_test)\n\ny_train_pred = regressor.predict(x_train)\ny_pred = regressor.predict(x_test)\nprint\nr2_score(y_test, y_pred)\n\nprint\n\"MSE Test\", mean_squared_error(y_test, y_pred)\nprint\n\"MSE Train\", mean_squared_error(y_train, y_train_pred)\n\n# data.info()\nplt.plot(x_test.index, y_test, '.',\n x_test.index, y_pred, '-')\n\nplt.show()\n"
]
| [
[
"numpy.array",
"sklearn.metrics.mean_squared_error",
"sklearn.linear_model.LinearRegression",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.corrcoef",
"matplotlib.pyplot.subplots",
"numpy.mean",
"sklearn.metrics.mean_absolute_error",
"numpy.append",
"sklearn.metrics.r2_score",
"matplotlib.pyplot.show",
"pandas.read_csv"
]
]
|
iN1k1/deep-pyramidal-representations-peron-re-identification | [
"18eacd3b7bde2c4767ba290b655cb0f5c72ed8fe"
]
| [
"src/datamanager/datasetreid.py"
]
| [
"from .dataset import Dataset\nfrom . import utils as datautils\nfrom ..utils import misc\nimport math\nimport os\nimport numpy as np\nimport copy\nfrom operator import itemgetter\n\n\nclass DatasetReID(Dataset):\n def __init__(self, name, root_folder, load=True, im_size=None, in_memory=False, keep_aspect_ratio=True):\n super(DatasetReID, self).__init__(name, root_folder, im_size=im_size)\n self.cams = []\n self.frames = []\n self.indexes = []\n self.probe = []\n self.gallery = []\n loaded_from_file = False\n if load:\n loaded_from_file = self.load(path=self.data_path, in_memory=in_memory, keep_aspect_ratio=keep_aspect_ratio)\n if len(self.images) == 0:\n raise (RuntimeError(\"Found 0 images in : \" + root_folder))\n\n # If data has not been loaded from file, we can save it!\n if not loaded_from_file:\n self.save(self.data_path)\n\n def load(self, path=None, in_memory=False, keep_aspect_ratio=True):\n loaded_from_file = False\n if path is None:\n path = self.data_path\n if os.path.exists(path):\n data = misc.load(path)\n self.images, self.targets, self.cams, self.frames, self.indexes, \\\n self.classes, self.class_to_idx, self.probe, self.gallery = data['images'], data['targets'], data['cams'], data['frames'], data['indexes'], \\\n data['classes'], data['class_to_idx'], data['probe'], data['gallery']\n\n loaded_from_file = True\n else:\n self.images, self.targets, self.cams, self.frames, self.indexes = datautils.load_reid_dataset(self.root, in_memory, self.im_size, keep_aspect_ratio)\n\n # Make contiguous IDs\n self.targets, self.classes, self.class_to_idx = datautils.make_contiguous_targets(self.targets)\n\n self.compute_idx_to_class()\n self.length = len(self.images)\n return loaded_from_file\n\n def save(self, path=None):\n if path is None:\n path = self.data_path\n misc.save(path, images=self.images, targets=self.targets, cams=self.cams, frames=self.frames, indexes=self.indexes,\n classes=self.classes, class_to_idx=self.class_to_idx, probe=self.probe, gallery=self.gallery)\n\n def get_indexes_from_cam(self, cam, N=None):\n indexes = [idx for idx in range(0, self.length) if self.cams[idx] == cam]\n targets = itemgetter(*indexes)(self.targets)\n cams = itemgetter(*indexes)(self.cams)\n if N is not None:\n indexes, targets, cams = self.get_max_N_per_class(N, indexes=indexes, targets=targets, cams=cams)\n return indexes, targets, cams\n\n def get_item_from_global_index(self, idx, N=None):\n indexes = [self.indexes.index(ii) for ii in idx]\n targets = itemgetter(*indexes)(self.targets)\n cams = itemgetter(*indexes)(self.cams)\n if N is not None:\n indexes, targets, cams = self.get_max_N_per_class(N, indexes=indexes, targets=targets, cams=cams)\n return indexes, targets, cams\n\n def get_indexes_from_ID(self, ID):\n return [idx for idx in range(0, self.length) if self.targets[idx] == ID]\n\n def get_indexes_from_id_cam(self, target, cam):\n indexes = [idx for idx in range(0, self.length) if self.cams[idx] == cam and self.targets[idx] == target]\n if len(indexes) == 0:\n return indexes, None, None\n targets = itemgetter(*indexes)(self.targets)\n cams = itemgetter(*indexes)(self.cams)\n return indexes, targets, cams\n\n def get_item_from_index(self, index):\n return self.images[index], self.targets[index], self.cams[index], self.indexes[index]\n\n def get_items_from_indexes(self, indexes):\n images = itemgetter(*indexes)(self.images)\n targets = itemgetter(*indexes)(self.targets)\n cams = itemgetter(*indexes)(self.cams)\n indexes = itemgetter(*indexes)(self.indexes)\n return images, targets, indexes, cams\n\n def get_index(self, target, cam, frame=None):\n index = [idx for idx in range(0, self.length) if self.cams[idx] == cam and self.targets[idx] == target and self.frames[idx] == frame][0]\n return self.get_item_from_index(index), index\n\n def get_max_N_per_class(self, N, indexes=None, targets=None, cams=None):\n\n # Get targets from dset and indexes from its length\n if targets is None:\n targets = self.targets\n if indexes is None:\n indexes = range(0, self.length)\n if cams is None:\n cams = self.cams\n\n # Extract indexes and corresponding classes\n np_targets = np.array(targets)\n unique_targets = np.unique(np_targets)\n valid_idx = []\n for t in unique_targets:\n pos = np.where(np_targets == t)[0]\n if len(pos) > N:\n pos = np.random.choice(pos, N, replace=False)\n valid_idx.extend(pos.tolist())\n return itemgetter(*valid_idx)(indexes), itemgetter(*valid_idx)(targets), itemgetter(*valid_idx)(cams)\n\n def split(self, ratios, save_load=True, **kwargs):\n\n dset_train = DatasetReID(self.name + '_train_' + str(ratios[0]), self.root, False, self.im_size, not isinstance(self.images[0], str))\n dset_test = DatasetReID(self.name + '_test_' + str(ratios[1]), self.root, False, self.im_size, not isinstance(self.images[0], str))\n\n # Try to load from data file\n if save_load and os.path.exists(dset_train.data_path) and os.path.exists(dset_test.data_path):\n dset_train.load()\n dset_test.load()\n else:\n probe_idx = []\n probe_idx_multi = []\n\n # Dataset is already partitioned..\n if os.path.exists(os.path.join(self.root, 'train')):\n n_train = len(os.listdir(os.path.join(self.root, 'train')))\n tridx = list(range(0, n_train))\n teidx = list(range(n_train, self.length))\n\n # Do we have query images already specifid?\n n_query = len(os.listdir(os.path.join(self.root, 'query')))\n n_query_m = 0\n if os.path.exists(os.path.join(self.root, 'query_multi')):\n n_query_m = len(os.listdir(os.path.join(self.root, 'query_multi')))\n\n probe_idx = list(range(self.length - (n_query+n_query_m), self.length-n_query_m))\n probe_idx_multi = list(range(self.length - n_query_m, self.length))\n else:\n unique_targets = list(set(self.targets))\n if ratios[0] <= 1 and ratios[1] <= 1:\n t = math.floor( len(unique_targets)*ratios[0] )\n ratios = (t, len(unique_targets)-t)\n perm = np.random.permutation(unique_targets)\n tridx = list(np.sort([ii for ii in range(0,self.length) if self.targets[ii] in perm[:ratios[0]] ]).tolist())\n teidx = list(np.sort([ii for ii in range(0,self.length) if self.targets[ii] in perm[ratios[0]:ratios[0]+ratios[1]] ]).tolist())\n\n dset_train = self.extract_subset(tridx, dset=dset_train)\n dset_test = self.extract_subset(teidx, dset=dset_test)\n\n if 'make_each_split_contiguous' in kwargs and kwargs['make_each_split_contiguous']:\n dset_train.targets, dset_train.classes, dset_train.class_to_idx = datautils.make_contiguous_targets(dset_train.targets)\n dset_test.targets, dset_test.classes, dset_test.class_to_idx = datautils.make_contiguous_targets(dset_test.targets)\n\n # Are the prpbe (query) images already specified?\n if probe_idx != []:\n\n # Update probe and gallery according to the tridx/teidx split..\n dset_test.probe = [dset_test.indexes.index(ii) for ii in probe_idx]\n gallery_idx = list(set(dset_test.indexes) - set(probe_idx))\n dset_test.gallery = [dset_test.indexes.index(ii) for ii in gallery_idx]\n\n if probe_idx_multi != []:\n probe_multi = [dset_test.indexes.index(ii) for ii in probe_idx_multi]\n probe_idx_multi_all = copy.deepcopy(probe_idx)\n probe_idx_multi_all.extend(probe_idx_multi)\n gallery_idx = list(set(dset_test.indexes) - set(probe_idx_multi_all))\n dset_test.probe = [dset_test.probe, probe_multi]\n dset_test.gallery = [dset_test.indexes.index(ii) for ii in gallery_idx]\n\n # Save\n if save_load:\n dset_train.save()\n dset_test.save()\n\n return dset_train, dset_test\n\n def extract_subset(self, idx, dset=None):\n\n # Create clone\n if dset is None:\n dset = DatasetReID(self.name, self.root, im_size=self.im_size)\n\n dset.class_to_idx = copy.copy(self.class_to_idx)\n dset.idx_to_class = copy.copy(self.idx_to_class)\n dset.compute_idx_to_class()\n\n # Get only selected samples\n if len(idx) > 0:\n dset.images = itemgetter(*idx)(self.images)\n dset.targets = itemgetter(*idx)(self.targets)\n dset.cams = itemgetter(*idx)(self.cams)\n dset.indexes = itemgetter(*idx)(self.indexes)\n if isinstance(dset.targets, int):\n dset.targets = [dset.targets]\n dset.images = [dset.images]\n dset.cams = [dset.cams]\n dset.indexes = [dset.indexes]\n dset.classes = np.sort(np.unique(dset.targets))\n dset.length = len(dset.targets)\n\n return dset\n\n def get_paired_dataset(self, campair, targets_to_pos_neg=False, N=999999, only_positives=False):\n dset_pair = DatasetReID(self.name + '_paired', self.root, False, self.im_size, not isinstance(self.images[0], str))\n dset_pair.images, dset_pair.targets, dset_pair.cams, dset_pair.indexes = datautils.compute_pairs_cams(self.images, self.targets,\n self.cams,range(0,len(self)), campair, N)\n # From target pairs (id1, id2) to +1/-1\n if targets_to_pos_neg:\n dset_pair.targets = (np.array(dset_pair.targets)[:,0] == np.array(dset_pair.targets)[:,1]).tolist()\n\n # Remove negative pairs\n if only_positives:\n pos_idx = []\n if targets_to_pos_neg:\n pos_idx = [ii for ii, idx in enumerate(dset_pair.targets) if idx == True]\n else:\n pos_idx = [ii for ii, idx in enumerate(dset_pair.targets) if idx[0] == idx[1]]\n\n # Keep only positives!\n dset_pair.images = itemgetter(*pos_idx)(dset_pair.images)\n dset_pair.targets = itemgetter(*pos_idx)(dset_pair.targets)\n dset_pair.cams = itemgetter(*pos_idx)(dset_pair.cams)\n\n # Remap indexes..\n dset_pair.indexes = itemgetter(*pos_idx)(dset_pair.indexes)\n\n\n\n # Length of the dataset\n dset_pair.length = len(dset_pair.images)\n\n return dset_pair\n"
]
| [
[
"numpy.array",
"numpy.random.choice",
"numpy.random.permutation",
"numpy.where",
"numpy.unique"
]
]
|
andreazanetti/Paddle | [
"bc379ca3d5895eadbc1748bc5b71606011563ee1"
]
| [
"python/paddle/fluid/contrib/mixed_precision/bf16/amp_utils.py"
]
| [
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nfrom .... import core\nfrom .... import framework\nfrom .... import global_scope\nfrom ....log_helper import get_logger\nfrom ....wrapped_decorator import signature_safe_contextmanager\nfrom .amp_lists import AutoMixedPrecisionListsBF16\nfrom ..fp16_utils import find_true_prev_op, find_true_post_op, _rename_arg, \\\n find_op_index, _rename_op_input\n\nimport collections\nimport struct\nimport logging\nimport numpy as np\n\n__all__ = [\n \"bf16_guard\", \"rewrite_program_bf16\", \"cast_model_to_bf16\",\n \"cast_parameters_to_bf16\", \"convert_float_to_uint16\"\n]\n\n_logger = get_logger(\n __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s')\n\n_valid_types = [\n core.VarDesc.VarType.LOD_TENSOR, core.VarDesc.VarType.SELECTED_ROWS,\n core.VarDesc.VarType.LOD_TENSOR_ARRAY\n]\n\n_bf16_guard_pattern = \"__use_bf16__\"\n\n\ndef convert_float_to_uint16(in_list):\n in_list = np.asarray(in_list)\n out = np.vectorize(\n lambda x: struct.unpack('<I', struct.pack('<f', x))[0] >> 16,\n otypes=[np.uint16])(in_list.flat)\n return np.reshape(out, in_list.shape)\n\n\ndef _dtype_to_str(dtype):\n \"\"\"\n Convert specific variable type to its corresponding string.\n\n Args:\n dtype (VarType): Variable type.\n \"\"\"\n if dtype == core.VarDesc.VarType.BF16:\n return 'bf16'\n else:\n return 'fp32'\n\n\ndef _insert_cast_op(block, op, idx, src_dtype, dest_dtype):\n \"\"\"\n Insert cast op and rename args of input and output.\n\n Args:\n block (Program): The block in which the operator is.\n op (Operator): The operator to insert cast op.\n idx (int): The index of current operator.\n src_dtype (VarType): The input variable dtype of cast op.\n dest_dtype (VarType): The output variable dtype of cast op.\n\n Returns:\n num_cast_op (int): The number of cast ops that have been inserted.\n \"\"\"\n num_cast_ops = 0\n\n for in_name in op.input_names:\n if src_dtype == core.VarDesc.VarType.FP32 and op.type in [\n 'batch_norm', 'fused_bn_add_activation', 'layer_norm'\n ]:\n if in_name not in {'X', 'Z'}:\n continue\n for in_var_name in op.input(in_name):\n in_var = block.var(in_var_name)\n if in_var.type not in _valid_types or in_var.dtype == dest_dtype:\n continue\n if in_var.dtype == src_dtype:\n cast_name = in_var.name + '.cast_' + _dtype_to_str(dest_dtype)\n out_var = block.vars.get(cast_name)\n if out_var is None or out_var.dtype != dest_dtype:\n out_var = block.create_var(\n name=cast_name,\n dtype=dest_dtype,\n persistable=False,\n stop_gradient=in_var.stop_gradient)\n\n block._insert_op(\n idx,\n type=\"cast\",\n inputs={\"X\": in_var},\n outputs={\"Out\": out_var},\n attrs={\n \"in_dtype\": in_var.dtype,\n \"out_dtype\": out_var.dtype\n })\n num_cast_ops += 1\n _rename_arg(op, in_var.name, out_var.name)\n else:\n if op.has_attr('in_dtype'):\n op._set_attr('in_dtype', dest_dtype)\n if src_dtype == core.VarDesc.VarType.FP32 and dest_dtype == core.VarDesc.VarType.BF16:\n for out_name in op.output_names:\n if op.type in [\n 'batch_norm', 'fused_bn_add_activation', 'layer_norm'\n ] and out_name != 'Y':\n continue\n for out_var_name in op.output(out_name):\n out_var = block.var(out_var_name)\n if out_var.type not in _valid_types:\n continue\n if out_var.dtype == core.VarDesc.VarType.FP32:\n out_var.desc.set_dtype(core.VarDesc.VarType.BF16)\n if op.has_attr('out_dtype'):\n op._set_attr('out_dtype', core.VarDesc.VarType.BF16)\n return num_cast_ops\n\n\ndef _insert_cast_post_op(block, op, idx, src_dtype, dest_dtype, target_name,\n op_var_rename_map):\n num_cast_ops = 0\n target_var = block.var(target_name)\n if target_var.type not in _valid_types or target_var.dtype == dest_dtype:\n return num_cast_ops\n\n assert target_var.dtype == src_dtype, \\\n \"The real dtype({}) is not equal to the src dtype({})\".format(_dtype_to_str(target_var.dtype), _dtype_to_str(src_dtype))\n\n cast_name = target_var.name + '.cast_' + _dtype_to_str(dest_dtype)\n cast_var = block.vars.get(cast_name)\n if cast_var is None or cast_var.dtype != dest_dtype:\n cast_var = block.create_var(\n name=cast_name,\n dtype=dest_dtype,\n persistable=False,\n stop_gradient=target_var.stop_gradient)\n block._insert_op(\n idx,\n type=\"cast\",\n inputs={\"X\": target_var},\n outputs={\"Out\": cast_var},\n attrs={\"in_dtype\": target_var.dtype,\n \"out_dtype\": cast_var.dtype})\n num_cast_ops += 1\n op_var_rename_map[block.idx][target_var.name] = cast_var.name\n\n return num_cast_ops\n\n\ndef _is_in_fp32_varnames(op, amp_lists):\n if not amp_lists.fp32_varnames:\n return False\n\n for in_name in op.input_arg_names:\n if in_name in amp_lists.fp32_varnames:\n return True\n\n for out_name in op.output_arg_names:\n if out_name in amp_lists.fp32_varnames:\n return True\n\n return False\n\n\ndef _need_keep_fp32(op, unsupported_op_list, use_bf16_guard):\n if op.type in unsupported_op_list:\n # the highest priority condition: If ops don't have bf16 computing kernels,\n # they must be executed in fp32 calculation pattern.\n return True\n\n # process ops about learning rate\n in_out_arg_names = []\n in_out_arg_names.extend(list(op.input_arg_names))\n in_out_arg_names.extend(list(op.output_arg_names))\n for name in in_out_arg_names:\n if \"learning_rate\" in name:\n return True\n\n if use_bf16_guard:\n if op.has_attr(\"op_namescope\") and \\\n (_bf16_guard_pattern in op.attr(\"op_namescope\")):\n # op in bf16 guard\n return False\n else:\n # op not in bf16 guard\n return True\n else:\n return False\n\n\n@signature_safe_contextmanager\ndef bf16_guard():\n \"\"\"\n As for the pure bf16 training, if users set `use_bf16_guard` to True,\n only those ops created in the context manager `bf16_guard` will be\n transformed as float16 type.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle\n import paddle.nn.functional as F\n paddle.enable_static()\n data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32')\n conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3)\n\n with paddle.static.amp.bf16_guard():\n bn = paddle.static.nn.batch_norm(input=conv2d, act=\"relu\")\n pool = F.max_pool2d(bn, kernel_size=2, stride=2)\n hidden = paddle.static.nn.fc(pool, size=10)\n loss = paddle.mean(hidden)\n \"\"\"\n with framework.name_scope(prefix=_bf16_guard_pattern):\n yield\n\n\ndef cast_model_to_bf16(program, amp_lists=None, use_bf16_guard=True):\n \"\"\"\n Traverse all ops in the whole model and set their inputs and outputs\n to the bf16 data type. This function will do some special processing for\n the batch normalization, which will keep the batchnorm's computations in FP32.\n Args:\n program (Program): The used program.\n amp_lists (AutoMixedPrecisionListsBF16): An AutoMixedPrecisionListsBF16 object.\n use_bf16_guard(bool): Determine whether to use `bf16_guard` when\n constructing the program. Default True.\n \"\"\"\n\n if amp_lists is None:\n amp_lists = AutoMixedPrecisionListsBF16()\n global_block = program.global_block()\n keep_fp32_ops = set()\n to_bf16_var_names = set()\n to_bf16_pre_cast_ops = set()\n origin_ops = []\n for block in program.blocks:\n origin_ops.extend(block.ops)\n\n for block in program.blocks:\n ops = block.ops\n for op in ops:\n if op.type == 'create_py_reader' or op.type == 'read':\n continue\n if _need_keep_fp32(op, amp_lists.unsupported_list, use_bf16_guard):\n keep_fp32_ops.add(op)\n continue # processed below\n for in_name in op.input_names:\n if op.type in {\n 'batch_norm', 'fused_bn_add_activation', 'layer_norm'\n } and in_name not in {'X', 'Z'}:\n continue\n for in_var_name in op.input(in_name):\n in_var = None\n try:\n in_var = block.var(in_var_name)\n except ValueError as e:\n _logger.debug(\n \"-- {}, try to get it in the global block --\".\n format(e))\n in_var = global_block.var(in_var_name)\n if in_var is not None:\n _logger.debug(\n \"-- var {} is got in the global block --\".\n format(in_var_name))\n\n if in_var is None or in_var.type not in _valid_types:\n continue\n\n if in_var.dtype == core.VarDesc.VarType.FP32:\n in_var.desc.set_dtype(core.VarDesc.VarType.BF16)\n to_bf16_var_names.add(in_var_name)\n\n _logger.debug(\n \"-- op type: {}, in var name: {}, in var dtype: {} --\".\n format(op.type, in_var_name, in_var.dtype))\n\n for out_name in op.output_names:\n if op.type in {\n 'batch_norm', 'fused_bn_add_activation', 'layer_norm'\n } and out_name != 'Y':\n continue\n for out_var_name in op.output(out_name):\n out_var = None\n try:\n out_var = block.var(out_var_name)\n except ValueError as e:\n _logger.debug(\n \"-- {}, try to get it in the global block --\".\n format(e))\n out_var = global_block.var(out_var_name)\n if out_var is not None:\n _logger.debug(\n \"-- var {} is got in the global block --\".\n format(out_var_name))\n\n if out_var is None or out_var.type not in _valid_types:\n continue\n\n if out_var.dtype == core.VarDesc.VarType.FP32:\n out_var.desc.set_dtype(core.VarDesc.VarType.BF16)\n\n _logger.debug(\n \"-- op type: {}, out var name: {}, out var dtype: {} --\".\n format(op.type, out_var_name, out_var.dtype))\n for attr_name in ['in_dtype', 'out_dtype', 'dtype']:\n if op.has_attr(attr_name) and op.attr(\n attr_name) == core.VarDesc.VarType.FP32:\n op._set_attr(attr_name, core.VarDesc.VarType.BF16)\n if op.has_attr('use_mkldnn'):\n op._set_attr('use_mkldnn', True)\n if op.has_attr('mkldnn_data_type'):\n op._set_attr('mkldnn_data_type', 'bfloat16')\n\n # process ops in keep_fp32_ops\n op_var_rename_map = [\n collections.OrderedDict() for _ in range(len(program.blocks))\n ]\n for block in program.blocks:\n ops = block.ops\n idx = 0\n while idx < len(ops):\n op = ops[idx]\n num_cast_ops = 0\n if op not in keep_fp32_ops:\n if op in to_bf16_pre_cast_ops:\n in_var_cast_num = _insert_cast_op(block, op, idx,\n core.VarDesc.VarType.FP32,\n core.VarDesc.VarType.BF16)\n num_cast_ops += in_var_cast_num\n else:\n pre_cast_num = _insert_cast_op(block, op, idx,\n core.VarDesc.VarType.BF16,\n core.VarDesc.VarType.FP32)\n num_cast_ops += pre_cast_num\n for out_var_name in op.output_arg_names:\n out_var = block.vars.get(out_var_name)\n if out_var is None or out_var.type not in _valid_types:\n continue\n if out_var.dtype == core.VarDesc.VarType.BF16:\n out_var.desc.set_dtype(core.VarDesc.VarType.FP32)\n post_ops = find_true_post_op(ops, op, out_var_name)\n for post_op in post_ops:\n if post_op in keep_fp32_ops:\n continue\n post_cast_num = _insert_cast_post_op(\n block, op, idx + pre_cast_num + 1,\n core.VarDesc.VarType.FP32,\n core.VarDesc.VarType.BF16, out_var_name,\n op_var_rename_map)\n num_cast_ops += post_cast_num\n idx += num_cast_ops + 1\n\n _rename_op_input(program, op_var_rename_map, origin_ops, keep_fp32_ops)\n return to_bf16_var_names\n\n\ndef cast_parameters_to_bf16(place, program, scope=None, to_bf16_var_names=None):\n \"\"\"\n Traverse all parameters in the whole model and set them to the BF16 data type.\n Whereas, this function will keep parameters of batchnorms in FP32.\n Args:\n place(fluid.CPUPlace|fluid.CUDAPlace): `place` is used to restore the BF16 weight tensors.\n program (Program): The used program.\n scope(fluid.Scope, optional): `scope` is used to get the FP32 weight tensor values.\n Default is None.\n to_bf16_var_names(set|list, optional): The data types of vars in `to_bf16_var_names`\n will be set to BF16. Usually, it is the returned\n value of `cast_model_to_bf16` API.\n \"\"\"\n all_parameters = []\n for block in program.blocks:\n all_parameters.extend(block.all_parameters())\n\n bf16_var_names = to_bf16_var_names if to_bf16_var_names else set()\n var_scope = scope if scope else global_scope()\n for param in all_parameters:\n if param.name in bf16_var_names:\n _logger.debug(\"---- cast {} to bf16 dtype ----\".format(param.name))\n param_t = var_scope.find_var(param.name).get_tensor()\n data = np.array(param_t)\n param_t.set(convert_float_to_uint16(data), place)\n\n\ndef rewrite_program_bf16(main_prog, amp_lists=None):\n \"\"\"\n Traverse all ops in current block and insert cast op according to\n which set current op belongs to.\n\n 1. When an op belongs to the fp32 list, add it to fp32 set\n 2. When an op belongs to the bf16 list, add it to bf16 set\n 3. When an op belongs to the gray list. If one\n of its inputs is the output of fp32 set op or fp32 list op,\n add it to fp32 set. If all of its previous ops are not fp32\n op and one of its inputs is the output of bf16 set op or\n bf16 list op, add it to bf16 set.\n 4. When an op isn't in the lists, add it to fp32 op set.\n 5. Add necessary cast ops to make sure that fp32 set op will be\n computed in fp32 mode, while bf16 set op will be computed in\n bf16 mode.\n\n Args:\n main_prog (Program): The main program for training.\n \"\"\"\n if amp_lists is None:\n amp_lists = AutoMixedPrecisionListsBF16()\n block = main_prog.global_block()\n ops = block.ops\n bf16_op_set = set()\n fp32_op_set = set()\n for op in ops:\n\n # NOTE(zhiqiu): 'create_py_reader' and 'read' is used in non-iterable DataLoder,\n # we don't need to handle reader op and the input of 'create_py_reader' is not\n # in block, which may result in errors.\n # See GeneratorLoader._init_non_iterable() for details.\n if op.type == 'create_py_reader' or op.type == 'read':\n continue\n\n if amp_lists.fp32_varnames is not None and _is_in_fp32_varnames(\n op, amp_lists):\n fp32_op_set.add(op)\n continue\n\n if op.type in amp_lists.fp32_list:\n fp32_op_set.add(op)\n elif op.type in amp_lists.bf16_list:\n bf16_op_set.add(op)\n elif op.type in amp_lists.gray_list:\n is_fp32_op = False\n is_bf16_op = False\n for in_name in op.input_names:\n # if this op has inputs\n if in_name:\n for in_var_name in op.input(in_name):\n in_var = block.var(in_var_name)\n # this in_var isn't the output of other op\n if in_var.op is None:\n continue\n elif in_var.op is op:\n prev_op = find_true_prev_op(ops, op, in_var_name)\n if prev_op is None:\n continue\n else:\n prev_op = in_var.op\n # if it's one of inputs\n if prev_op in fp32_op_set or \\\n prev_op.type in amp_lists.fp32_list:\n is_fp32_op = True\n elif prev_op in bf16_op_set or \\\n prev_op.type in amp_lists.bf16_list:\n is_bf16_op = True\n if is_fp32_op:\n fp32_op_set.add(op)\n elif is_bf16_op:\n bf16_op_set.add(op)\n else:\n pass\n else:\n # For numerical safe, we apply fp32 computation on ops that\n # are not determined which list they should stay.\n fp32_op_set.add(op)\n\n idx = 0\n while idx < len(ops):\n op = ops[idx]\n num_cast_ops = 0\n if op in fp32_op_set:\n num_cast_ops = _insert_cast_op(block, op, idx,\n core.VarDesc.VarType.BF16,\n core.VarDesc.VarType.FP32)\n elif op in bf16_op_set:\n if op.has_attr('use_mkldnn'):\n op._set_attr('use_mkldnn', True)\n op._set_attr('mkldnn_data_type', 'bfloat16')\n elif op.has_attr('dtype') and op.attr(\n 'dtype') == core.VarDesc.VarType.FP32:\n op._set_attr('dtype', core.VarDesc.VarType.BF16)\n\n num_cast_ops = _insert_cast_op(block, op, idx,\n core.VarDesc.VarType.FP32,\n core.VarDesc.VarType.BF16)\n else:\n pass\n\n idx += num_cast_ops + 1\n"
]
| [
[
"numpy.reshape",
"numpy.array",
"numpy.asarray"
]
]
|
Riser6/yolox | [
"2cd60d94528ef9195dc68cd3204d63c3f61d990a",
"2cd60d94528ef9195dc68cd3204d63c3f61d990a"
]
| [
"yolox/exp/yolox_base.py",
"exps/custom/yolox_m_coat_voc.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.\n\nimport os\nimport random\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\n\nfrom .base_exp import BaseExp\n\n\nclass Exp(BaseExp):\n def __init__(self):\n super().__init__()\n\n # ---------------- model config ---------------- #\n self.num_classes = 80\n self.depth = 1.00\n self.width = 1.00\n self.act = 'silu'\n\n # ---------------- dataloader config ---------------- #\n # set worker to 4 for shorter dataloader init time\n self.data_num_workers = 4\n self.input_size = (640, 640) # (height, width)\n # Actual multiscale ranges: [640-5*32, 640+5*32].\n # To disable multiscale training, set the\n # self.multiscale_range to 0.\n self.multiscale_range = 5\n # You can uncomment this line to specify a multiscale range\n # self.random_size = (14, 26)\n self.data_dir = None\n self.train_ann = \"instances_train2017.json\"\n self.val_ann = \"instances_val2017.json\"\n\n # --------------- transform config ----------------- #\n self.mosaic_prob = 1.0\n self.mixup_prob = 1.0\n self.hsv_prob = 1.0\n self.flip_prob = 0.5\n self.degrees = 10.0\n self.translate = 0.1\n self.mosaic_scale = (0.1, 2)\n self.mixup_scale = (0.5, 1.5)\n self.shear = 2.0\n self.enable_mixup = True\n\n # -------------- training config --------------------- #\n self.warmup_epochs = 5\n self.max_epoch = 300\n self.warmup_lr = 0\n self.basic_lr_per_img = 0.01 / 64.0\n self.scheduler = \"yoloxwarmcos\"\n self.no_aug_epochs = 15\n self.min_lr_ratio = 0.05\n self.ema = True\n\n self.weight_decay = 5e-4\n self.momentum = 0.9\n self.print_interval = 10\n self.eval_interval = 1\n self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n\n # ----------------- testing config ------------------ #\n self.test_size = (640, 640)\n self.test_conf = 0.01\n self.nmsthre = 0.65\n\n def get_model(self):\n from yolox.models import YOLOX, YOLOPAFPN, YOLOXHead\n\n def init_yolo(M):\n for m in M.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eps = 1e-3\n m.momentum = 0.03\n\n if getattr(self, \"model\", None) is None:\n in_channels = [256, 512, 1024]\n backbone = YOLOPAFPN(self.depth, self.width, in_channels=in_channels, act=self.act)\n head = YOLOXHead(self.num_classes, self.width, in_channels=in_channels, act=self.act)\n self.model = YOLOX(backbone, head)\n\n self.model.apply(init_yolo)\n self.model.head.initialize_biases(1e-2)\n return self.model\n\n def get_data_loader(\n self, batch_size, is_distributed, no_aug=False, cache_img=False\n ):\n from yolox.data import (\n COCODataset,\n TrainTransform,\n YoloBatchSampler,\n DataLoader,\n InfiniteSampler,\n MosaicDetection,\n worker_init_reset_seed,\n )\n from yolox.utils import (\n wait_for_the_master,\n get_local_rank,\n )\n\n local_rank = get_local_rank()\n\n with wait_for_the_master(local_rank):\n dataset = COCODataset(\n data_dir=self.data_dir,\n json_file=self.train_ann,\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=50,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n cache=cache_img,\n )\n\n dataset = MosaicDetection(\n dataset,\n mosaic=not no_aug,\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=120,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n degrees=self.degrees,\n translate=self.translate,\n mosaic_scale=self.mosaic_scale,\n mixup_scale=self.mixup_scale,\n shear=self.shear,\n enable_mixup=self.enable_mixup,\n mosaic_prob=self.mosaic_prob,\n mixup_prob=self.mixup_prob,\n )\n\n self.dataset = dataset\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n\n sampler = InfiniteSampler(len(self.dataset), seed=self.seed if self.seed else 0)\n\n batch_sampler = YoloBatchSampler(\n sampler=sampler,\n batch_size=batch_size,\n drop_last=False,\n mosaic=not no_aug,\n )\n\n dataloader_kwargs = {\"num_workers\": self.data_num_workers, \"pin_memory\": True}\n dataloader_kwargs[\"batch_sampler\"] = batch_sampler\n\n # Make sure each process has different random seed, especially for 'fork' method.\n # Check https://github.com/pytorch/pytorch/issues/63311 for more details.\n dataloader_kwargs[\"worker_init_fn\"] = worker_init_reset_seed\n\n train_loader = DataLoader(self.dataset, **dataloader_kwargs)\n\n return train_loader\n\n def random_resize(self, data_loader, epoch, rank, is_distributed):\n tensor = torch.LongTensor(2).cuda()\n\n if rank == 0:\n size_factor = self.input_size[1] * 1.0 / self.input_size[0]\n if not hasattr(self, 'random_size'):\n min_size = int(self.input_size[0] / 32) - self.multiscale_range\n max_size = int(self.input_size[0] / 32) + self.multiscale_range\n self.random_size = (min_size, max_size)\n size = random.randint(*self.random_size)\n size = (int(32 * size), 32 * int(size * size_factor))\n tensor[0] = size[0]\n tensor[1] = size[1]\n\n if is_distributed:\n dist.barrier()\n dist.broadcast(tensor, 0)\n\n input_size = (tensor[0].item(), tensor[1].item())\n return input_size\n\n def preprocess(self, inputs, targets, tsize):\n scale_y = tsize[0] / self.input_size[0]\n scale_x = tsize[1] / self.input_size[1]\n if scale_x != 1 or scale_y != 1:\n inputs = nn.functional.interpolate(\n inputs, size=tsize, mode=\"bilinear\", align_corners=False\n )\n targets[..., 1::2] = targets[..., 1::2] * scale_x\n targets[..., 2::2] = targets[..., 2::2] * scale_y\n return inputs, targets\n\n def get_optimizer(self, batch_size):\n if \"optimizer\" not in self.__dict__:\n if self.warmup_epochs > 0:\n lr = self.warmup_lr\n else:\n lr = self.basic_lr_per_img * batch_size\n\n pg0, pg1, pg2 = [], [], [] # optimizer parameter groups\n\n for k, v in self.model.named_modules():\n if hasattr(v, \"bias\") and isinstance(v.bias, nn.Parameter):\n pg2.append(v.bias) # biases\n if isinstance(v, nn.BatchNorm2d) or \"bn\" in k:\n pg0.append(v.weight) # no decay\n elif hasattr(v, \"weight\") and isinstance(v.weight, nn.Parameter):\n pg1.append(v.weight) # apply decay\n\n optimizer = torch.optim.SGD(\n pg0, lr=lr, momentum=self.momentum, nesterov=True\n )\n optimizer.add_param_group(\n {\"params\": pg1, \"weight_decay\": self.weight_decay}\n ) # add pg1 with weight_decay\n optimizer.add_param_group({\"params\": pg2})\n self.optimizer = optimizer\n\n return self.optimizer\n\n def get_lr_scheduler(self, lr, iters_per_epoch):\n from yolox.utils import LRScheduler\n\n scheduler = LRScheduler(\n self.scheduler,\n lr,\n iters_per_epoch,\n self.max_epoch,\n warmup_epochs=self.warmup_epochs,\n warmup_lr_start=self.warmup_lr,\n no_aug_epochs=self.no_aug_epochs,\n min_lr_ratio=self.min_lr_ratio,\n )\n return scheduler\n\n def get_eval_loader(self, batch_size, is_distributed, testdev=False, legacy=False):\n from yolox.data import COCODataset, ValTransform\n\n valdataset = COCODataset(\n data_dir=self.data_dir,\n json_file=self.val_ann if not testdev else \"image_info_test-dev2017.json\",\n name=\"val2017\" if not testdev else \"test2017\",\n img_size=self.test_size,\n preproc=ValTransform(legacy=legacy),\n )\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n sampler = torch.utils.data.distributed.DistributedSampler(\n valdataset, shuffle=False\n )\n else:\n sampler = torch.utils.data.SequentialSampler(valdataset)\n\n dataloader_kwargs = {\n \"num_workers\": self.data_num_workers,\n \"pin_memory\": True,\n \"sampler\": sampler,\n }\n dataloader_kwargs[\"batch_size\"] = batch_size\n val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)\n\n return val_loader\n\n def get_evaluator(self, batch_size, is_distributed, testdev=False, legacy=False):\n from yolox.evaluators import COCOEvaluator\n\n val_loader = self.get_eval_loader(batch_size, is_distributed, testdev, legacy)\n evaluator = COCOEvaluator(\n dataloader=val_loader,\n img_size=self.test_size,\n confthre=self.test_conf,\n nmsthre=self.nmsthre,\n num_classes=self.num_classes,\n testdev=testdev,\n )\n return evaluator\n\n def eval(self, model, evaluator, is_distributed, half=False):\n return evaluator.evaluate(model, is_distributed, half)\n",
"import os\n\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\n\nfrom yolox.data import get_yolox_datadir\nfrom yolox.exp import Exp as MyExp\n\nfrom timm.optim import create_optimizer_v2\n\n\nclass Exp(MyExp):\n def __init__(self):\n super(Exp, self).__init__()\n self.num_classes = 20\n self.depth = 0.67\n self.width = 0.75\n\n self.warmup_epochs = 5\n self.max_epoch = 300\n self.warmup_lr = 0\n self.basic_lr_per_img = 0.02 / 64.0\n self.scheduler = \"yoloxwarmcos\"\n self.no_aug_epochs = 15\n self.min_lr_ratio = 0.05\n self.ema = True\n self.weight_decay = 0.05\n self.momentum = 0.9\n\n self.exp_name = os.path.split(os.path.realpath(__file__))[1].split(\".\")[0]\n\n def get_model(self, sublinear=False):\n from yolox.models import YOLOX, YOLOPAFPN, YOLOXHead\n from yolox.models.coat import coat_small, coat_lite_small, coat_lite_tiny\n\n def init_yolo(M):\n for m in M.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eps = 1e-3\n m.momentum = 0.03\n\n if getattr(self, \"model\", None) is None:\n # Use CoaT as backbone\n # in_channels = [256, 256, 256] # 256, 512, 1024\n # backbone = coat_small(embed_dims_override=[152, 192, 192, 192], # 152, 320, 320, 320\n # out_features=['x2_nocls', 'x3_nocls', 'x4_nocls'],\n # return_interm_layers=True)\n\n # Use CoaT-Lite as backbone\n in_channels = [128 / 0.75, 256 / 0.75, 320 / 0.75] # 256, 512, 1024\n coatl = coat_lite_tiny(embed_dims_override=[64, 128, 256, 320],\n out_features=['x2_nocls', 'x3_nocls', 'x4_nocls'],\n return_interm_layers=True)\n backbone = YOLOPAFPN(self.depth, self.width, in_channels=in_channels, act=self.act,\n in_features=(0, 1, 2), backbone=coatl)\n\n head = YOLOXHead(self.num_classes, self.width, in_channels=in_channels, act=self.act)\n self.model = YOLOX(backbone, head)\n\n self.model.apply(init_yolo)\n self.model.head.initialize_biases(1e-2)\n return self.model\n\n def get_data_loader(self, batch_size, is_distributed, no_aug=False, cache_img=False):\n from yolox.data import (\n VOCDetection,\n TrainTransform,\n YoloBatchSampler,\n DataLoader,\n InfiniteSampler,\n MosaicDetection,\n worker_init_reset_seed,\n )\n from yolox.utils import (\n wait_for_the_master,\n get_local_rank,\n )\n local_rank = get_local_rank()\n\n with wait_for_the_master(local_rank):\n dataset = VOCDetection(\n data_dir=os.path.join(get_yolox_datadir(), \"VOCdevkit\"),\n image_sets=[('2007', 'trainval'), ('2012', 'trainval')],\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=50,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n cache=cache_img,\n )\n\n dataset = MosaicDetection(\n dataset,\n mosaic=not no_aug,\n img_size=self.input_size,\n preproc=TrainTransform(\n max_labels=120,\n flip_prob=self.flip_prob,\n hsv_prob=self.hsv_prob),\n degrees=self.degrees,\n translate=self.translate,\n mosaic_scale=self.mosaic_scale,\n mixup_scale=self.mixup_scale,\n shear=self.shear,\n enable_mixup=self.enable_mixup,\n mosaic_prob=self.mosaic_prob,\n mixup_prob=self.mixup_prob,\n )\n\n self.dataset = dataset\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n\n sampler = InfiniteSampler(\n len(self.dataset), seed=self.seed if self.seed else 0\n )\n\n batch_sampler = YoloBatchSampler(\n sampler=sampler,\n batch_size=batch_size,\n drop_last=False,\n mosaic=not no_aug,\n )\n\n dataloader_kwargs = {\"num_workers\": self.data_num_workers, \"pin_memory\": True}\n dataloader_kwargs[\"batch_sampler\"] = batch_sampler\n\n # Make sure each process has different random seed, especially for 'fork' method\n dataloader_kwargs[\"worker_init_fn\"] = worker_init_reset_seed\n\n train_loader = DataLoader(self.dataset, **dataloader_kwargs)\n\n return train_loader\n\n def get_eval_loader(self, batch_size, is_distributed, testdev=False, legacy=False):\n from yolox.data import VOCDetection, ValTransform\n\n valdataset = VOCDetection(\n data_dir=os.path.join(get_yolox_datadir(), \"VOCdevkit\"),\n image_sets=[('2007', 'test')],\n img_size=self.test_size,\n preproc=ValTransform(legacy=legacy),\n )\n\n if is_distributed:\n batch_size = batch_size // dist.get_world_size()\n sampler = torch.utils.data.distributed.DistributedSampler(\n valdataset, shuffle=False\n )\n else:\n sampler = torch.utils.data.SequentialSampler(valdataset)\n\n dataloader_kwargs = {\n \"num_workers\": self.data_num_workers,\n \"pin_memory\": True,\n \"sampler\": sampler,\n }\n dataloader_kwargs[\"batch_size\"] = batch_size\n val_loader = torch.utils.data.DataLoader(valdataset, **dataloader_kwargs)\n\n return val_loader\n\n def get_evaluator(self, batch_size, is_distributed, testdev=False, legacy=False):\n from yolox.evaluators import VOCEvaluator\n\n val_loader = self.get_eval_loader(batch_size, is_distributed, testdev, legacy)\n evaluator = VOCEvaluator(\n dataloader=val_loader,\n img_size=self.test_size,\n confthre=self.test_conf,\n nmsthre=self.nmsthre,\n num_classes=self.num_classes,\n )\n return evaluator\n\n\n #Coat AdamW optimizer\n def get_optimizer(self, batch_size):\n lr = self.basic_lr_per_img * batch_size\n self.optimizer = create_optimizer_v2(self.model, \"adamw\", lr, 0.05, self.momentum)\n\n return self.optimizer\n\n"
]
| [
[
"torch.distributed.get_world_size",
"torch.nn.functional.interpolate",
"torch.optim.SGD",
"torch.utils.data.SequentialSampler",
"torch.LongTensor",
"torch.utils.data.DataLoader",
"torch.utils.data.distributed.DistributedSampler",
"torch.distributed.barrier",
"torch.distributed.broadcast"
],
[
"torch.distributed.get_world_size",
"torch.utils.data.SequentialSampler",
"torch.utils.data.DataLoader",
"torch.utils.data.distributed.DistributedSampler"
]
]
|
xdevdev/ClapToChange | [
"eed6e5c8facfa157e99fb2cc4417453311535c92"
]
| [
"ASR research/frequency estimator.py"
]
| [
"import pyaudio\r\nimport time\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\nFORMAT = pyaudio.paInt16\r\nCHANNELS = 1\r\nRATE = 64000\r\nCHUNK = 1024\t# 1024\r\n\r\nall_pitches = []\r\n\r\nstream_buffer = []\r\n\r\np = pyaudio.PyAudio()\r\n\r\ndef empty_frame(length):\r\n\t\"\"\"Returns an empty 16bit audio frame of supplied length.\"\"\"\r\n\tframe = np.zeros(length, dtype='i2')\r\n\treturn to_raw_data(frame)\r\n\r\ndef callback_in(in_data, frame_count, time_info, status):\r\n\t\"\"\"Callback function for incoming data from an input stream.\"\"\"\r\n\tstream_buffer.append(in_data)\r\n\tprocess(in_data)\r\n\treturn (in_data, pyaudio.paContinue)\r\n\r\ndef callback_out(in_data, frame_count, time_info, status):\r\n\t\"\"\"Callback function for outgoing data to an output stream.\"\"\"\r\n\ttry:\r\n\t\tdata = stream_buffer.pop(0)\r\n\texcept:\r\n\t\tdata = empty_frame(frame_count)\r\n\treturn (data, pyaudio.paContinue)\r\n\r\ndef to_int_data(raw_data):\r\n\t\"\"\"Converts raw bytes data to .\"\"\"\r\n\treturn np.array([int.from_bytes(raw_data[i:i+2], byteorder='little', signed=True) for i in range(0, len(raw_data), 2)])\r\n\r\ndef to_raw_data(int_data):\r\n\tdata = int_data.clip(-32678, 32677)\r\n\tdata = data.astype(np.dtype('i2'))\r\n\treturn b''.join(data.astype(np.dtype('V2')))\r\n\r\ndef process(raw_data):\r\n\tst = time.time()\r\n\tdata = to_int_data(raw_data)\r\n\tdata = data*4\t\t# raise volume\r\n\tdetect_pitch(data)\r\n\tet = time.time()\r\n\treturn to_raw_data(data)\r\n\r\ndef normal_distribution(w):\r\n\twidth = w+1\r\n\tweights = np.exp(-np.square([2*x/width for x in range(width)]))\r\n\tweights = np.pad(weights, (width-1,0), 'reflect')\r\n\tweights = weights/np.sum(weights)\r\n\treturn weights\r\n\r\ndef detect_pitch(int_data):\r\n\tif 'avg' not in detect_pitch.__dict__:\r\n\t\tdetect_pitch.avg = 0\r\n\tWIND = 10\r\n\tCYCLE = 400\r\n\tweights = normal_distribution(WIND)\r\n\twindowed_data = np.pad(int_data, WIND, 'reflect')\r\n\tsmooth_data = np.convolve(int_data, weights, mode='valid')\r\n\tsmooth_pitches = [0]+[np.mean(smooth_data[:-delay] - smooth_data[delay:]) for delay in range(1,CYCLE)]\r\n\r\n\tdips = [x for x in range(WIND, CYCLE-WIND) if smooth_pitches[x] == np.min(smooth_pitches[x-WIND:x+WIND])]\r\n\tif len(dips) > 1:\r\n\t\tav_dip = np.mean(np.ediff1d(dips))\r\n\t\tcheq_freq = RATE / av_dip\r\n\t\tdetect_pitch.avg = detect_pitch.avg*0.5 + cheq_freq*0.5\r\n\t\tall_pitches.append(int(detect_pitch.avg))\r\n\t\tprint('\\r'+str(int(detect_pitch.avg))+' Hz ', end='')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tstream_in = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, stream_callback=callback_in)\r\n\tstream_out = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, stream_callback=callback_out)\r\n\r\n\tstream_in.start_stream()\r\n\tstream_out.start_stream()\r\n\r\n\ttxt = input()\t#stream until enter key press\r\n\r\n\tstream_in.stop_stream()\r\n\tstream_in.close()\r\n\tstream_out.stop_stream()\r\n\tstream_out.close()\r\n\r\n\tp.terminate()\r\n\r\n\t#plt.plot(all_pitches)\r\n\t#plt.show() "
]
| [
[
"numpy.pad",
"numpy.zeros",
"numpy.sum",
"numpy.min",
"numpy.mean",
"numpy.ediff1d",
"numpy.dtype",
"numpy.convolve"
]
]
|
Avin0323/CINN | [
"607f85ef89f65ba92ef7d91ca5e3ad33681f6ec2",
"607f85ef89f65ba92ef7d91ca5e3ad33681f6ec2"
]
| [
"tutorials/net_builder.py",
"python/cinn/auto_schedule/cost_model/xgb_cost_model.py"
]
| [
"# Copyright (c) 2021 CINN Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nRun model by using NetBuilder API\n=========================================================\n\nIn this tutorial, we will introduce the ways to build and run a model using NetBuilder APIs.\n\"\"\"\n\nimport cinn\nfrom cinn import frontend\nfrom cinn import common\nimport numpy as np\n# sphinx_gallery_thumbnail_path = './paddlepaddle.png'\n\n##################################################################\n#\n# Define the NetBuilder.\n# -----------------------------\n#\n# Using NetBuilder is a convenient way to build a model in CINN.\n# You can build and run a model by invoking NetBuilder's API as following.\n#\n# :code:`name`: the ID of NetBuilder\n#\n# Generally, the API in `NetBuilder` is coarse-grained operator, in other words,\n# the DL framework like Paddle's operator.\nbuilder = frontend.NetBuilder(name=\"batchnorm_conv2d\")\n\n##################################################################\n#\n# Define the input variable of the model.\n# ---------------------------------------------\n#\n# The input variable should be created by create_input API. Note that the variable\n# here is just a placeholder, does not need the actual data.\n#\n# :code:`type`: the data type of input variable, now support `Void`, `Int`, `UInt`,\n# `Float`, `Bool` and `String`, the parameter is the type's bit-widths, here the\n# data type is `float32`.\n#\n# :code:`shape`: The shape of the input variable, note that here does not support\n# dynamic shape, so the dimension value should be greater than 0 now.\n#\n# :code:`id_hint`: the name of variable, the defaule value is `\"\"`\na = builder.create_input(\n type=common.Float(32), shape=(8, 3, 224, 224), id_hint=\"x\")\nscale = builder.create_input(type=common.Float(32), shape=[3], id_hint=\"scale\")\nbias = builder.create_input(type=common.Float(32), shape=[3], id_hint=\"bias\")\nmean = builder.create_input(type=common.Float(32), shape=[3], id_hint=\"mean\")\nvariance = builder.create_input(\n type=common.Float(32), shape=[3], id_hint=\"variance\")\nweight = builder.create_input(\n type=common.Float(32), shape=(3, 3, 7, 7), id_hint=\"weight\")\n\n##################################################################\n#\n# Build the model by using NetBuilder API\n# ---------------------------------------------\n#\n# For convenience, here we build a simple model that only consists of batchnorm and conv2d\n# operators. Note that you can find the operator's detailed introduction in another\n# document, we won't go into detail here.\ny = builder.batchnorm(a, scale, bias, mean, variance, is_test=True)\nres = builder.conv2d(y[0], weight)\n\n##################################################################\n#\n# Set target\n# ---------------------\n#\n# The target identified where the model should run, now we support\n# two targets:\n#\n# :code:`DefaultHostTarget`: the model will running at cpu.\n#\n# :code:`DefaultNVGPUTarget`: the model will running at nv gpu.\nif common.is_compiled_with_cuda():\n target = common.DefaultNVGPUTarget()\nelse:\n target = common.DefaultHostTarget()\n\nprint(\"Model running at \", target.arch)\n\n##################################################################\n#\n# Generate the program\n# ---------------------\n#\n# After the model building, the `Computation` will generate a CINN execution program,\n# and you can get it like:\ncomputation = frontend.Computation.build_and_compile(target, builder)\n\n##################################################################\n#\n# Random fake input data\n# -----------------------------\n#\n# Before running, you should read or generate some data to feed the model's input.\n# :code:`get_tensor`: Get the tensor with specific name in computation.\n# :code:`from_numpy`: Fill the tensor with numpy data.\ntensor_data = [\n np.random.random([8, 3, 224, 224]).astype(\"float32\"), # a\n np.random.random([3]).astype(\"float32\"), # scale\n np.random.random([3]).astype(\"float32\"), # bias\n np.random.random([3]).astype(\"float32\"), # mean\n np.random.random([3]).astype(\"float32\"), # variance\n np.random.random([3, 3, 7, 7]).astype(\"float32\") # weight\n]\n\ncomputation.get_tensor(\"x\").from_numpy(tensor_data[0], target)\ncomputation.get_tensor(\"scale\").from_numpy(tensor_data[1], target)\ncomputation.get_tensor(\"bias\").from_numpy(tensor_data[2], target)\ncomputation.get_tensor(\"mean\").from_numpy(tensor_data[3], target)\ncomputation.get_tensor(\"variance\").from_numpy(tensor_data[4], target)\ncomputation.get_tensor(\"weight\").from_numpy(tensor_data[5], target)\n\n##################################################################\n#\n# Run program and print result\n# -----------------------------\n#\n# Finally, you can run the model by invoking function `execute()`.\n# After that, you can get the tensor you want by `get_tensor` with tensor's name.\ncomputation.execute()\nres_tensor = computation.get_tensor(str(res))\nres_data = res_tensor.numpy(target)\n\n# print result\nprint(res_data)\n",
"# Copyright (c) 2022 CINN Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport xgboost as xgb\n\n\nclass XgbCostModel(object):\n \"\"\"\n A cost model implemented by XgbCostModel\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n # Store the xgb.Booster, which is the output of xgb.train\n self.booster = None\n\n self.xgb_param = {}\n self.train_round = 10\n\n def train(self, samples, labels):\n \"\"\"\n Train the model.\n\n Args:\n samples(list|numpy): an array of numpy array representing a batch\n of input samples.\n labels(list|numpy): an array of float representing a batch of labels\n\n Returns:\n xgb.Booster\n \"\"\"\n lengths = [x.shape[0] for x in samples]\n if isinstance(samples, list):\n samples = np.concatenate(samples, axis=0)\n if isinstance(labels, list):\n labels = np.concatenate(\n [[y] * length for y, length in zip(labels, lengths)], axis=0)\n\n dmatrix = xgb.DMatrix(data=samples, label=labels)\n self.booster = xgb.train(self.xgb_param, dmatrix, self.train_round)\n return self.booster\n\n def predict(self, samples):\n \"\"\"\n Predict\n\n Args:\n samples(list|numpy): an array of numpy array representing a batch\n of input samples.\n Returns:\n np.array representing labels\n \"\"\"\n if isinstance(samples, list):\n samples = np.concatenate(samples, axis=0)\n dmatrix = xgb.DMatrix(data=samples, label=None)\n pred = self.booster.predict(dmatrix)\n return pred\n\n def save(self, path):\n \"\"\"\n Save the trained XgbCostModel\n\n Args:\n path(str): path to save\n \"\"\"\n assert self.booster is not None, \"Calling save on a XgbCostModel not been trained\"\n self.booster.save_model(path)\n\n def load(self, path):\n \"\"\"\n Load the trained XgbCostModel\n\n Args:\n path(str): path to load\n \"\"\"\n if self.booster is None:\n self.booster = xgb.Booster()\n self.booster.load_model(path)\n # Should we save/load config parameters? Not now because it is pre-set.\n # But we should do that here if that's changable in the future.\n\n def update(self, samples, labels):\n #xgb doesn't support incremental training, we leave this method as TODO\n pass\n"
]
| [
[
"numpy.random.random"
],
[
"numpy.concatenate"
]
]
|
KofClubs/DeepMG | [
"fef1905b4757ff3e23592f799d34d756972340fd"
]
| [
"geometry_translation/models/losses.py"
]
| [
"import torch\nimport torch.nn as nn\n\n\nclass SoftDiceLoss(nn.Module):\n def __init__(self):\n super(SoftDiceLoss, self).__init__()\n pass\n\n def forward(self, y_pred, y_true):\n smooth = 1.0 # may change\n i = torch.sum(y_true)\n j = torch.sum(y_pred)\n intersection = torch.sum(y_true * y_pred)\n score = (2. * intersection + smooth) / (i + j + smooth)\n loss = 1. - score.mean()\n return loss\n"
]
| [
[
"torch.sum"
]
]
|
chy7074646/mmdetection | [
"68589d36f67ce3e05e0c5cd936b6e7fa72a1101a"
]
| [
"mmdet/models/detectors/htc.py"
]
| [
"import torch\nimport torch.nn.functional as F\n\nfrom .cascade_rcnn import CascadeRCNN\nfrom .. import builder\nfrom ..registry import DETECTORS\nfrom mmdet.core import (bbox2roi, bbox2result, build_assigner, build_sampler,\n merge_aug_masks)\n\n\[email protected]_module\nclass HybridTaskCascade(CascadeRCNN):\n\n def __init__(self,\n num_stages,\n backbone,\n semantic_roi_extractor=None,\n semantic_head=None,\n semantic_fusion=('bbox', 'mask'),\n interleaved=True,\n mask_info_flow=True,\n **kwargs):\n super(HybridTaskCascade, self).__init__(num_stages, backbone, **kwargs)\n assert self.with_bbox and self.with_mask\n assert not self.with_shared_head # shared head not supported\n if semantic_head is not None:\n self.semantic_roi_extractor = builder.build_roi_extractor(\n semantic_roi_extractor)\n self.semantic_head = builder.build_head(semantic_head)\n\n self.semantic_fusion = semantic_fusion\n self.interleaved = interleaved\n self.mask_info_flow = mask_info_flow\n\n @property\n def with_semantic(self):\n if hasattr(self, 'semantic_head') and self.semantic_head is not None:\n return True\n else:\n return False\n\n def _bbox_forward_train(self,\n stage,\n x,\n sampling_results,\n gt_bboxes,\n gt_labels,\n rcnn_train_cfg,\n semantic_feat=None):\n rois = bbox2roi([res.bboxes for res in sampling_results])\n bbox_roi_extractor = self.bbox_roi_extractor[stage]\n bbox_head = self.bbox_head[stage]\n bbox_feats = bbox_roi_extractor(x[:bbox_roi_extractor.num_inputs],\n rois)\n # semantic feature fusion\n # element-wise sum for original features and pooled semantic features\n if self.with_semantic and 'bbox' in self.semantic_fusion:\n bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n rois)\n if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:\n bbox_semantic_feat = F.adaptive_avg_pool2d(\n bbox_semantic_feat, bbox_feats.shape[-2:])\n bbox_feats += bbox_semantic_feat\n\n cls_score, bbox_pred = bbox_head(bbox_feats)\n\n bbox_targets = bbox_head.get_target(sampling_results, gt_bboxes,\n gt_labels, rcnn_train_cfg)\n loss_bbox = bbox_head.loss(cls_score, bbox_pred, *bbox_targets)\n return loss_bbox, rois, bbox_targets, bbox_pred\n\n def _mask_forward_train(self,\n stage,\n x,\n sampling_results,\n gt_masks,\n rcnn_train_cfg,\n semantic_feat=None):\n mask_roi_extractor = self.mask_roi_extractor[stage]\n mask_head = self.mask_head[stage]\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n mask_feats = mask_roi_extractor(x[:mask_roi_extractor.num_inputs],\n pos_rois)\n\n # semantic feature fusion\n # element-wise sum for original features and pooled semantic features\n if self.with_semantic and 'mask' in self.semantic_fusion:\n mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n pos_rois)\n if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:\n mask_semantic_feat = F.adaptive_avg_pool2d(\n mask_semantic_feat, mask_feats.shape[-2:])\n mask_feats += mask_semantic_feat\n\n # mask information flow\n # forward all previous mask heads to obtain last_feat, and fuse it\n # with the normal mask feature\n if self.mask_info_flow:\n last_feat = None\n for i in range(stage):\n last_feat = self.mask_head[i](\n mask_feats, last_feat, return_logits=False)\n mask_pred = mask_head(mask_feats, last_feat, return_feat=False)\n else:\n mask_pred = mask_head(mask_feats)\n\n mask_targets = mask_head.get_target(sampling_results, gt_masks,\n rcnn_train_cfg)\n pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])\n loss_mask = mask_head.loss(mask_pred, mask_targets, pos_labels)\n return loss_mask\n\n def _bbox_forward_test(self, stage, x, rois, semantic_feat=None):\n bbox_roi_extractor = self.bbox_roi_extractor[stage]\n bbox_head = self.bbox_head[stage]\n bbox_feats = bbox_roi_extractor(\n x[:len(bbox_roi_extractor.featmap_strides)], rois)\n if self.with_semantic and 'bbox' in self.semantic_fusion:\n bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n rois)\n if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:\n bbox_semantic_feat = F.adaptive_avg_pool2d(\n bbox_semantic_feat, bbox_feats.shape[-2:])\n bbox_feats += bbox_semantic_feat\n cls_score, bbox_pred = bbox_head(bbox_feats)\n return cls_score, bbox_pred\n\n def _mask_forward_test(self, stage, x, bboxes, semantic_feat=None):\n mask_roi_extractor = self.mask_roi_extractor[stage]\n mask_head = self.mask_head[stage]\n mask_rois = bbox2roi([bboxes])\n mask_feats = mask_roi_extractor(\n x[:len(mask_roi_extractor.featmap_strides)], mask_rois)\n if self.with_semantic and 'mask' in self.semantic_fusion:\n mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],\n mask_rois)\n if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:\n mask_semantic_feat = F.adaptive_avg_pool2d(\n mask_semantic_feat, mask_feats.shape[-2:])\n mask_feats += mask_semantic_feat\n if self.mask_info_flow:\n last_feat = None\n last_pred = None\n for i in range(stage):\n mask_pred, last_feat = self.mask_head[i](mask_feats, last_feat)\n if last_pred is not None:\n mask_pred = mask_pred + last_pred\n last_pred = mask_pred\n mask_pred = mask_head(mask_feats, last_feat, return_feat=False)\n if last_pred is not None:\n mask_pred = mask_pred + last_pred\n else:\n mask_pred = mask_head(mask_feats)\n return mask_pred\n\n def forward_train(self,\n img,\n img_meta,\n gt_bboxes,\n gt_labels,\n gt_bboxes_ignore=None,\n gt_masks=None,\n gt_semantic_seg=None,\n proposals=None):\n x = self.extract_feat(img)\n\n losses = dict()\n\n # RPN part, the same as normal two-stage detectors\n if self.with_rpn:\n rpn_outs = self.rpn_head(x)\n rpn_loss_inputs = rpn_outs + (gt_bboxes, img_meta,\n self.train_cfg.rpn)\n rpn_losses = self.rpn_head.loss(\n *rpn_loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)\n losses.update(rpn_losses)\n\n proposal_cfg = self.train_cfg.get('rpn_proposal',\n self.test_cfg.rpn)\n proposal_inputs = rpn_outs + (img_meta, proposal_cfg)\n proposal_list = self.rpn_head.get_bboxes(*proposal_inputs)\n else:\n proposal_list = proposals\n\n # semantic segmentation part\n # 2 outputs: segmentation prediction and embedded features\n if self.with_semantic:\n semantic_pred, semantic_feat = self.semantic_head(x)\n loss_seg = self.semantic_head.loss(semantic_pred, gt_semantic_seg)\n losses['loss_semantic_seg'] = loss_seg\n else:\n semantic_feat = None\n\n for i in range(self.num_stages):\n self.current_stage = i\n rcnn_train_cfg = self.train_cfg.rcnn[i]\n lw = self.train_cfg.stage_loss_weights[i]\n\n # assign gts and sample proposals\n sampling_results = []\n bbox_assigner = build_assigner(rcnn_train_cfg.assigner)\n bbox_sampler = build_sampler(rcnn_train_cfg.sampler, context=self)\n num_imgs = img.size(0)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n\n for j in range(num_imgs):\n assign_result = bbox_assigner.assign(\n proposal_list[j], gt_bboxes[j], gt_bboxes_ignore[j],\n gt_labels[j])\n sampling_result = bbox_sampler.sample(\n assign_result,\n proposal_list[j],\n gt_bboxes[j],\n gt_labels[j],\n feats=[lvl_feat[j][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n\n # bbox head forward and loss\n loss_bbox, rois, bbox_targets, bbox_pred = \\\n self._bbox_forward_train(\n i, x, sampling_results, gt_bboxes, gt_labels,\n rcnn_train_cfg, semantic_feat)\n roi_labels = bbox_targets[0]\n\n for name, value in loss_bbox.items():\n losses['s{}.{}'.format(i, name)] = (\n value * lw if 'loss' in name else value)\n\n # mask head forward and loss\n if self.with_mask:\n # interleaved execution: use regressed bboxes by the box branch\n # to train the mask branch\n if self.interleaved:\n pos_is_gts = [res.pos_is_gt for res in sampling_results]\n with torch.no_grad():\n proposal_list = self.bbox_head[i].refine_bboxes(\n rois, roi_labels, bbox_pred, pos_is_gts, img_meta)\n # re-assign and sample 512 RoIs from 512 RoIs\n sampling_results = []\n for j in range(num_imgs):\n assign_result = bbox_assigner.assign(\n proposal_list[j], gt_bboxes[j],\n gt_bboxes_ignore[j], gt_labels[j])\n sampling_result = bbox_sampler.sample(\n assign_result,\n proposal_list[j],\n gt_bboxes[j],\n gt_labels[j],\n feats=[lvl_feat[j][None] for lvl_feat in x])\n sampling_results.append(sampling_result)\n loss_mask = self._mask_forward_train(i, x, sampling_results,\n gt_masks, rcnn_train_cfg,\n semantic_feat)\n for name, value in loss_mask.items():\n losses['s{}.{}'.format(i, name)] = (\n value * lw if 'loss' in name else value)\n\n # refine bboxes (same as Cascade R-CNN)\n if i < self.num_stages - 1 and not self.interleaved:\n pos_is_gts = [res.pos_is_gt for res in sampling_results]\n with torch.no_grad():\n proposal_list = self.bbox_head[i].refine_bboxes(\n rois, roi_labels, bbox_pred, pos_is_gts, img_meta)\n\n return losses\n\n def simple_test(self, img, img_meta, proposals=None, rescale=False):\n x = self.extract_feat(img)\n proposal_list = self.simple_test_rpn(\n x, img_meta, self.test_cfg.rpn) if proposals is None else proposals\n\n if self.with_semantic:\n _, semantic_feat = self.semantic_head(x)\n else:\n semantic_feat = None\n\n img_shape = img_meta[0]['img_shape']\n ori_shape = img_meta[0]['ori_shape']\n scale_factor = img_meta[0]['scale_factor']\n\n # \"ms\" in variable names means multi-stage\n ms_bbox_result = {}\n ms_segm_result = {}\n ms_scores = []\n rcnn_test_cfg = self.test_cfg.rcnn\n\n rois = bbox2roi(proposal_list)\n for i in range(self.num_stages):\n bbox_head = self.bbox_head[i]\n cls_score, bbox_pred = self._bbox_forward_test(\n i, x, rois, semantic_feat=semantic_feat)\n ms_scores.append(cls_score)\n\n if self.test_cfg.keep_all_stages:\n det_bboxes, det_labels = bbox_head.get_det_bboxes(\n rois,\n cls_score,\n bbox_pred,\n img_shape,\n scale_factor,\n rescale=rescale,\n nms_cfg=rcnn_test_cfg)\n bbox_result = bbox2result(det_bboxes, det_labels,\n bbox_head.num_classes)\n ms_bbox_result['stage{}'.format(i)] = bbox_result\n\n if self.with_mask:\n mask_head = self.mask_head[i]\n if det_bboxes.shape[0] == 0:\n segm_result = [\n [] for _ in range(mask_head.num_classes - 1)\n ]\n else:\n _bboxes = (\n det_bboxes[:, :4] * scale_factor\n if rescale else det_bboxes)\n mask_pred = self._mask_forward_test(\n i, x, _bboxes, semantic_feat=semantic_feat)\n segm_result = mask_head.get_seg_masks(\n mask_pred, _bboxes, det_labels, rcnn_test_cfg,\n ori_shape, scale_factor, rescale)\n ms_segm_result['stage{}'.format(i)] = segm_result\n\n if i < self.num_stages - 1:\n bbox_label = cls_score.argmax(dim=1)\n rois = bbox_head.regress_by_class(rois, bbox_label, bbox_pred,\n img_meta[0])\n\n cls_score = sum(ms_scores) / float(len(ms_scores))\n det_bboxes, det_labels = self.bbox_head[-1].get_det_bboxes(\n rois,\n cls_score,\n bbox_pred,\n img_shape,\n scale_factor,\n rescale=rescale,\n cfg=rcnn_test_cfg)\n bbox_result = bbox2result(det_bboxes, det_labels,\n self.bbox_head[-1].num_classes)\n ms_bbox_result['ensemble'] = bbox_result\n\n if self.with_mask:\n if det_bboxes.shape[0] == 0:\n segm_result = [\n [] for _ in range(self.mask_head[-1].num_classes - 1)\n ]\n else:\n _bboxes = (\n det_bboxes[:, :4] * scale_factor\n if rescale else det_bboxes)\n\n mask_rois = bbox2roi([_bboxes])\n aug_masks = []\n mask_roi_extractor = self.mask_roi_extractor[-1]\n mask_feats = mask_roi_extractor(\n x[:len(mask_roi_extractor.featmap_strides)], mask_rois)\n if self.with_semantic and 'mask' in self.semantic_fusion:\n mask_semantic_feat = self.semantic_roi_extractor(\n [semantic_feat], mask_rois)\n mask_feats += mask_semantic_feat\n last_feat = None\n for i in range(self.num_stages):\n mask_head = self.mask_head[i]\n if self.mask_info_flow:\n mask_pred, last_feat = mask_head(mask_feats, last_feat)\n else:\n mask_pred = mask_head(mask_feats)\n aug_masks.append(mask_pred.sigmoid().cpu().numpy())\n merged_masks = merge_aug_masks(aug_masks,\n [img_meta] * self.num_stages,\n self.test_cfg.rcnn)\n segm_result = self.mask_head[-1].get_seg_masks(\n merged_masks, _bboxes, det_labels, rcnn_test_cfg,\n ori_shape, scale_factor, rescale)\n ms_segm_result['ensemble'] = segm_result\n\n if not self.test_cfg.keep_all_stages:\n if self.with_mask:\n results = (ms_bbox_result['ensemble'],\n ms_segm_result['ensemble'])\n else:\n results = ms_bbox_result['ensemble']\n else:\n if self.with_mask:\n results = {\n stage: (ms_bbox_result[stage], ms_segm_result[stage])\n for stage in ms_bbox_result\n }\n else:\n results = ms_bbox_result\n\n return results\n\n def aug_test(self, img, img_meta, proposals=None, rescale=False):\n raise NotImplementedError\n"
]
| [
[
"torch.cat",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.no_grad"
]
]
|
pbogomolov1967/outliers_and_similarity | [
"101d170e1f49ae7ae93aa5eb6434d92ae9fce8f3"
]
| [
"similarity.py"
]
| [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nfrom sklearn.metrics import euclidean_distances\n\nfrom util_distances_in_clusters import plot_kmeans, annotate_data_points2\n\n\ndef run_sim_nb():\n\n # Generate data\n np.random.seed(0)\n data, y_true = make_blobs(n_samples=5, centers=1, cluster_std=0.80, random_state=0)\n data = data[:, ::-1] # flip axes for better plotting\n\n ix = 3\n x = data[ix]\n colors = np.zeros(data.shape[0])\n colors[ix] = 1\n\n distances1 = euclidean_distances(data, [x])\n distances1 = [d[0] for d in distances1]\n\n distances1_max = np.max(distances1)\n similarity_weights = [1. - d / distances1_max for d in distances1]\n prices = [120., 80., 80., 60., 50.]\n\n weighted_avg_price = np.average(prices, weights=similarity_weights)\n info = f'price was {prices[ix]} and its weighted_avg now is {round(weighted_avg_price,1)}'\n\n prices[3] = weighted_avg_price\n\n kmeans = KMeans(n_clusters=1, random_state=0)\n ax = plot_kmeans(plt, kmeans, data, title='Similarity: ' + info, colors=colors)\n annotate_data_points2(plt, data, prices, ax=ax)\n\n\nif __name__ == '__main__':\n run_sim_nb()\n plt.show()\n pass\n"
]
| [
[
"numpy.max",
"sklearn.datasets.make_blobs",
"numpy.zeros",
"numpy.random.seed",
"sklearn.cluster.KMeans",
"sklearn.metrics.euclidean_distances",
"numpy.average",
"matplotlib.pyplot.show"
]
]
|
subhamroy007/beta_codes | [
"d6399639d3dde194c3fc5f509a9bb39cafb3a9bc"
]
| [
"my_network.py"
]
| [
"#in this version og neural network sgc is implemented along mith multiclass\r\n#classification using softmax activation and categorical cross entropy loss\r\n\r\n\r\n#import necessery libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nimport math\r\n\r\n\r\n#uniform layer\r\nclass Uniform:\r\n def __init__(self,W,B):\r\n self.w = W\r\n self.x = None\r\n self.b = B\r\n self.forward_val = None\r\n self.db = None\r\n self.dx = None\r\n self.dw = None\r\n \r\n def forwardVal(self,x):\r\n self.x = x\r\n self.forward_val = np.dot(self.w,self.x) + self.b\r\n return self.forward_val\r\n\r\n def backwardVal(self):\r\n self.dw = self.x\r\n self.dx = self.w\r\n self.db = 1 \r\n \r\n \r\n \r\n#creating the relu computation node\r\nclass Relu:\r\n def __init__(self):\r\n self.x = None\r\n self.forward_val = None\r\n self.dx = None\r\n def forwardVal(self,x):\r\n self.x = x\r\n self.forward_val = self.x\r\n for i in range(self.forward_val.shape[0]):\r\n for j in range(self.forward_val.shape[1]):\r\n self.forward_val[i,j] = max(0,self.forward_val[i,j])\r\n return self.forward_val\r\n def backwardVal(self):\r\n self.dx = self.forward_val\r\n for i in range(self.forward_val.shape[0]):\r\n for j in range(self.forward_val.shape[1]):\r\n if self.forward_val[i,j] == 0:\r\n self.dx[i,j] = 0\r\n else:\r\n self.dx[i,j] = 1\r\n \r\n \r\n \r\n#creating the sigmoid node\r\nclass Sigmoid:\r\n def __init__(self):\r\n self.x = None\r\n self.dx = None\r\n self.forward_val = None\r\n \r\n def forwardVal(self,x):\r\n self.x = x\r\n self.forward_val = (1 + np.exp(-self.x)) ** -1\r\n return self.forward_val\r\n \r\n def backwardVal(self):\r\n self.dx = self.forward_val * (1-self.forward_val)\r\n \r\n\r\n\r\nclass LogLoss:\r\n def __init__(self):\r\n self.y = None\r\n self.pred = None\r\n self.l = None\r\n self.dl = None\r\n \r\n def calculateLoss(self,y,pred):\r\n self.y = y\r\n self.pred = pred\r\n self.l = self.y*np.log10(self.pred)+(1-self.y)*np.log10(1-self.pred)\r\n self.l = -self.l\r\n return self.l\r\n \r\n def calculateGradient(self):\r\n self.dl = (self.y-self.pred) / (self.pred * (1-self.pred))\r\n\r\n\r\n\r\n\r\n#categorical cross entropy loss node\r\nclass CategoricalCrossEntropy:\r\n def __init__(self):\r\n self.y = None\r\n self.pred = None\r\n self.l = None\r\n self.dl = None\r\n \r\n def calculateLoss(self,y,pred):\r\n self.y = y\r\n self.pred = pred\r\n self.l = -y*np.log10(pred)\r\n return self.l\r\n\r\n def calculateGradient(self):\r\n self.dl = -self.y * (self.pred ** -1)\r\n\r\n\r\n\r\n#creating softmax activation node\r\n \r\nclass Softmax:\r\n def __init__(self):\r\n self.x = None\r\n self.dx = None\r\n self.forward_val = None\r\n \r\n def forwardVal(self,x):\r\n self.x = x\r\n self.forward_val = np.zeros(x.shape,dtype = np.float64)\r\n \r\n for i in range(x.shape[0]):\r\n self.forward_val[i,0] = np.exp(x[i,0])/np.exp(x).sum()\r\n #self.forward_val = self.forward_val / self.forward_val.sum()\r\n \r\n return self.forward_val\r\n\r\n def backwardVal(self):\r\n #self.dx = np.zeros(self.forward_val.shape,dtype = np.float64)\r\n self.dx = np.zeros((self.forward_val.shape[0],self.forward_val.shape[0]),dtype = np.float64)\r\n for i in range(self.dx.shape[0]):\r\n for j in range(self.dx.shape[0]):\r\n if i == j:\r\n self.dx[i,j] = self.forward_val[i,0]*(1-self.forward_val[j,0])\r\n else:\r\n self.dx[i,j] = -self.forward_val[i,0]*self.forward_val[j,0]\r\n #self.dx = (temp.sum(axis = 1).reshape(self.dx.shape))\r\n \r\n \r\n \r\nclass Network:\r\n def __init__(self,input_size,layer_size,output_size):\r\n self.input_size = input_size\r\n self.layer_size = layer_size\r\n self.output_size = output_size\r\n self.layer_stack = []\r\n self.loss_list = []\r\n self.fitness = None\r\n \r\n \r\n #initializing all the neccessery computation nodes \r\n self.layer_stack.append(Uniform(self.init_weight(self.layer_size,self.input_size),self.init_bias(self.layer_size,1)))\r\n self.layer_stack.append(Relu())\r\n self.layer_stack.append(Uniform(self.init_weight(self.output_size,self.layer_size),self.init_bias(self.output_size,1)))\r\n self.layer_stack.append(Softmax())\r\n self.layer_stack.append(CategoricalCrossEntropy())\r\n\r\n @classmethod\r\n def init_weight(self,r,c):\r\n arr = np.zeros((r,c),dtype = np.float64)\r\n for i in range(r):\r\n for j in range(c):\r\n arr[i,j] = np.random.randn() #initialize by gausian \r\n return arr\r\n \r\n @classmethod\r\n def init_bias(self,r,c):\r\n arr = np.zeros((r,c),dtype = np.float64)\r\n for i in range(r):\r\n for j in range(c):\r\n arr[i,j] = np.random.randn() #initialize by gausian \r\n return arr\r\n \r\n\r\n def forwardPass(self,sample_x,sample_y):\r\n temp = self.layer_stack[0].forwardVal(sample_x)\r\n #print(\"first sum = \",temp)\r\n temp = self.layer_stack[1].forwardVal(temp)\r\n #print(\"relu = \",temp)\r\n temp = self.layer_stack[2].forwardVal(temp)\r\n #print(\"second sum = \",temp)\r\n temp = self.layer_stack[3].forwardVal(temp)\r\n #print(\"softmax = \",temp)\r\n temp = self.layer_stack[4].calculateLoss(sample_y,temp)\r\n self.loss_list.append(temp)\r\n #print(\"loss = \",temp)\r\n \r\n \r\n \r\n def generate(self,parent,mu):\r\n\r\n w0 = self.layer_stack[0].w\r\n w0 = w0.reshape(w0.shape[0]*w0.shape[1],)\r\n b0 = self.layer_stack[0].b\r\n b0 = b0.reshape(b0.shape[0]*b0.shape[1],)\r\n w1 = self.layer_stack[2].w\r\n w1 = w1.reshape(w1.shape[0]*w1.shape[1],)\r\n b1 = self.layer_stack[2].b\r\n b1 = b1.reshape(b1.shape[0]*b1.shape[1],)\r\n my_weights = np.concatenate([w0,b0,w1,b1])\r\n w0 = parent.layer_stack[0].w\r\n w0 = w0.reshape(w0.shape[0]*w0.shape[1],)\r\n b0 = parent.layer_stack[0].b\r\n b0 = b0.reshape(b0.shape[0]*b0.shape[1],)\r\n w1 = parent.layer_stack[2].w\r\n w1 = w1.reshape(w1.shape[0]*w1.shape[1],)\r\n b1 = parent.layer_stack[2].b\r\n b1 = b1.reshape(b1.shape[0]*b1.shape[1],)\r\n patner_weights = np.concatenate([w0,b0,w1,b1])\r\n new_weights = np.concatenate([my_weights[:round(len(my_weights)/4)],patner_weights[round(len(my_weights)/4):round(len(my_weights)/2)],my_weights[round(len(my_weights)/2):round(len(my_weights)*3/4)],patner_weights[round(len(my_weights)*3/4):]]) \r\n for a in range(len(new_weights)):\r\n if random.random() <= mu:\r\n new_weights[a] += np.random.randn()\r\n #new_weights = []\r\n #c = -1\r\n #for x,y in zip(my_weights,patner_weights):\r\n # c += 1\r\n # k1 = random.random()\r\n # k2 = random.random()\r\n # new_weights.append(x*.4+y*(1-.6))\r\n #if k2 <= mu:\r\n # new_weights[c] += np.random.uniform(-1.0, 1.0, 1)\r\n \r\n \r\n new_weights = np.array(new_weights,dtype = np.float64)\r\n #print(len(new_weights))\r\n ww0 = new_weights[0:len(w0)].reshape(self.layer_stack[0].w.shape)\r\n bb0 = new_weights[len(w0):len(w0)+len(b0)].reshape(self.layer_stack[0].b.shape)\r\n ww1 = new_weights[len(w0)+len(b0):len(w0)+len(b0)+len(w1)].reshape(self.layer_stack[2].w.shape)\r\n bb1 = new_weights[len(w0)+len(b0)+len(w1):].reshape(self.layer_stack[2].b.shape)\r\n \r\n child = Network(12,40,2)\r\n child.layer_stack[0] = Uniform(ww0,bb0)\r\n child.layer_stack[2] = Uniform(ww1,bb1)\r\n \r\n return child\r\n \r\n \r\n \r\n def run(self,data_x,data_y):\r\n right = 0\r\n wrong = 0\r\n for x,y in zip(data_x,data_y):\r\n self.forwardPass(x,y)\r\n if round(self.layer_stack[4].pred[0,0]) == self.layer_stack[4].y[0,0]:\r\n right += 1\r\n else:\r\n wrong += 1\r\n self.fitness = 100 * right/(right+wrong)\r\n \r\n \r\n\r\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.dot",
"numpy.zeros",
"numpy.random.randn",
"numpy.exp",
"numpy.log10"
]
]
|
SufiyanDilawarkhan/Domain-Classification-Of-Customer-Messages-using-NLP | [
"b0ad90df2740308d0d1f3d0903e8e8df3aa1cc27"
]
| [
"code.py"
]
| [
"# --------------\nimport pandas as pd\r\nimport os\r\nimport numpy as np\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\n# path_train : location of test file\r\n# Code starts here\r\n\r\ndf = pd.read_csv(path_train)\r\n\r\nprint (df.head())\r\n\r\ndef label_race(row):\r\n if row['food'] == \"T\":\r\n return 'food'\r\n elif row['recharge'] == \"T\":\r\n return 'recharge'\r\n elif row['support'] == \"T\":\r\n return 'support'\r\n elif row['reminders'] == \"T\":\r\n return 'reminders'\r\n elif row['nearby'] == \"T\":\r\n return 'nearby'\r\n elif row['movies'] == \"T\":\r\n return 'movies'\r\n elif row['casual'] == \"T\":\r\n return 'casual'\r\n elif row['other'] == \"T\":\r\n return 'other'\r\n elif row['travel'] == \"T\":\r\n return 'travel'\r\n\r\ndf['category'] = df.apply(lambda row: label_race(row), axis=1)\r\n\r\ndf.drop(columns=['food', 'recharge', 'support', 'reminders', 'nearby', 'movies', 'casual', 'other', 'travel'], inplace=True)\r\n\r\nprint(\"\")\r\n\r\nprint (df.head())\n\n\n# --------------\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n# Sampling only 1000 samples of each category\r\ndf = df.groupby('category').apply(lambda x: x.sample(n=1000, random_state=0))\r\n\r\n# Code starts here\r\n\r\nall_text = df[\"message\"].str.lower()\r\n\r\ntfidf_vectorizer = TfidfVectorizer(stop_words=\"english\")\r\n\r\nX = tfidf_vectorizer.fit_transform(all_text).toarray()\r\n\r\nprint (X)\r\n\r\nle = LabelEncoder()\r\n\r\ny = le.fit_transform(df['category'])\r\n\r\nprint (\"\")\r\nprint (\"\")\r\nprint (y)\n\n\n# --------------\nfrom sklearn.metrics import accuracy_score, classification_report\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import LinearSVC\r\n\r\n# Code starts here\r\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)\r\n\r\n\r\n#Logistic Regression Model\r\nlog_reg = LogisticRegression(random_state=0)\r\n\r\nlog_reg.fit(X_train, y_train)\r\n\r\ny_pred = log_reg.predict(X_val)\r\n\r\nlog_accuracy = accuracy_score(y_val, y_pred)\r\nprint (\"Logistic Regression Accuracy = \", log_accuracy)\r\n\r\n\r\n#Naive Bayes Model\r\nnb = MultinomialNB()\r\n\r\nnb.fit(X_train, y_train)\r\n\r\ny_pred = nb.predict(X_val)\r\n\r\nnb_accuracy = accuracy_score(y_val, y_pred)\r\nprint (\"Naive Bayes Accuracy = \", nb_accuracy)\r\n\r\n\r\n#Linear SVM Model\r\nlsvm = LinearSVC(random_state=0)\r\n\r\nlsvm.fit(X_train, y_train)\r\n\r\ny_pred = lsvm.predict(X_val)\r\n\r\nlsvm_accuracy = accuracy_score(y_val, y_pred)\r\nprint (\"Linear SVM Accuracy = \", lsvm_accuracy)\r\n\n\n\n# --------------\n# path_test : Location of test data\r\n\r\n#Loading the dataframe\r\ndf_test = pd.read_csv(path_test)\r\n\r\n#Creating the new column category\r\ndf_test[\"category\"] = df_test.apply (lambda row: label_race (row),axis=1)\r\n\r\n#Dropping the other columns\r\ndrop= [\"food\", \"recharge\", \"support\", \"reminders\", \"nearby\", \"movies\", \"casual\", \"other\", \"travel\"]\r\ndf_test= df_test.drop(drop,1)\r\n\r\n# Code starts here\r\nall_text = df_test['message'].str.lower()\r\n\r\nX_test = tfidf_vectorizer.transform(all_text).toarray()\r\n\r\ny_test = le.transform(df_test['category'])\r\n\r\n\r\n#Logistic Regression Model\r\ny_pred = log_reg.predict(X_test)\r\n\r\nlog_accuracy_2 = accuracy_score(y_test, y_pred)\r\nprint (\"Logistic Regression Accuracy = \", log_accuracy_2)\r\n\r\n\r\n#Naive Bayes Model\r\ny_pred = nb.predict(X_test)\r\n\r\nnb_accuracy_2 = accuracy_score(y_test, y_pred)\r\nprint (\"Naive Bayes Accuracy = \", nb_accuracy_2)\r\n\r\n\r\n#Linear SVM Model\r\ny_pred = lsvm.predict(X_test)\r\n\r\nlsvm_accuracy_2 = accuracy_score(y_test, y_pred)\r\nprint (\"Linear SVM = \", lsvm_accuracy_2)\n\n\n# --------------\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.wordnet import WordNetLemmatizer\r\nimport string\r\nimport gensim\r\nfrom gensim.models.lsimodel import LsiModel\r\nfrom gensim import corpora\r\nfrom pprint import pprint\r\n# import nltk\r\n# nltk.download('wordnet')\r\n\r\n# Creating a stopwords list\r\nstop = set(stopwords.words('english'))\r\nexclude = set(string.punctuation)\r\nlemma = WordNetLemmatizer()\r\n# Function to lemmatize and remove the stopwords\r\ndef clean(doc):\r\n stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\r\n punc_free = \"\".join(ch for ch in stop_free if ch not in exclude)\r\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\r\n return normalized\r\n\r\n# Creating a list of documents from the complaints column\r\nlist_of_docs = df[\"message\"].tolist()\r\n\r\n# Implementing the function for all the complaints of list_of_docs\r\ndoc_clean = [clean(doc).split() for doc in list_of_docs]\r\n\r\n# Code starts here\r\n\r\ndictionary = corpora.Dictionary(doc_clean)\r\n\r\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]\r\n\r\nlsimodel = LsiModel(corpus=doc_term_matrix, num_topics=5, id2word=dictionary)\r\n\r\npprint(lsimodel.print_topics())\n\n\n# --------------\nfrom gensim.models import LdaModel\r\nfrom gensim.models import CoherenceModel\r\n\r\n# doc_term_matrix - Word matrix created in the last task\r\n# dictionary - Dictionary created in the last task\r\n\r\n# Function to calculate coherence values\r\ndef compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):\r\n \"\"\"\r\n Compute c_v coherence for various number of topics\r\n\r\n Parameters:\r\n ----------\r\n dictionary : Gensim dictionary\r\n corpus : Gensim corpus\r\n texts : List of input texts\r\n limit : Max num of topics\r\n\r\n Returns:\r\n -------\r\n topic_list : No. of topics chosen\r\n coherence_values : Coherence values corresponding to the LDA model with respective number of topics\r\n \"\"\"\r\n coherence_values = []\r\n topic_list = []\r\n for num_topics in range(start, limit, step):\r\n model = gensim.models.ldamodel.LdaModel(doc_term_matrix, random_state = 0, num_topics=num_topics, id2word = dictionary, iterations=10)\r\n topic_list.append(num_topics)\r\n coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')\r\n coherence_values.append(coherencemodel.get_coherence())\r\n\r\n return topic_list, coherence_values\r\n\r\n\r\n# Code starts here\r\ntopic_list, coherence_value_list = compute_coherence_values(dictionary=dictionary, corpus=doc_term_matrix, texts=doc_clean, start=1, limit=41, step=5)\r\n\r\nopt_topic = topic_list[np.argmax(coherence_value_list)]\r\n\r\nlda_model = LdaModel(corpus=doc_term_matrix, num_topics=opt_topic, id2word = dictionary, iterations=10 , passes=30, random_state=0)\r\n\r\npprint(lda_model.print_topics(5))\n\n\n"
]
| [
[
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.accuracy_score",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.linear_model.LogisticRegression",
"numpy.argmax",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.svm.LinearSVC"
]
]
|
JacobARose/pyleaves | [
"27b4016c850148981f3d021028c9272f18df121d"
]
| [
"pyleaves/utils/callback_utils.py"
]
| [
"# @Author: Jacob A Rose\n# @Date: Wed, July 22nd 2020, 9:51 pm\n# @Email: [email protected]\n# @Filename: callback_utils.py\n\n\n'''\nCreated (7/22/2020) by Jacob A Rose\n-This script was originally located at pyleaves.train.callbacks\n-All scripts that reference original location should be transitioned to here\n\n'''\n\n\nimport io\nimport os\nimport random\nimport signal\nimport sys\nimport tensorflow as tf\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.distribute import collective_all_reduce_strategy\nfrom tensorflow.python.distribute import distribute_lib\nfrom tensorflow.python.distribute import distributed_file_utils\nfrom tensorflow.python.distribute import mirrored_strategy\nfrom tensorflow.python.framework import ops\nfrom tensorflow.compat.v1.keras.callbacks import (Callback,\n\t\t\t\t\t\t\t\t\t\t\t\t CSVLogger,\n\t\t\t\t\t\t\t\t\t\t\t\t ModelCheckpoint,\n\t\t\t\t\t\t\t\t\t\t\t\t TensorBoard,\n\t\t\t\t\t\t\t\t\t\t\t\t LearningRateScheduler,\n\t\t\t\t\t\t\t\t\t\t\t\t EarlyStopping)\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scikitplot.metrics import plot_confusion_matrix, plot_roc\nimport neptune\nimport cv2\n# from mlxtend import evaluate, plotting\nfrom pyleaves.models.vgg16 import visualize_activations#, get_layers_by_index\nfrom pyleaves.utils.model_utils import WorkerTrainingState\n\nclass BackupAndRestore(Callback):\n\t\"\"\"\n\tBased on official tf.keras.callbacks.BackupAndRestore\n\n\tCallback to back up and restore the training state.\n\t`BackupAndRestore` callback is intended to recover from interruptions that\n\thappened in the middle of a model.fit execution by backing up the\n\ttraining states in a temporary checkpoint file (based on TF CheckpointManager)\n\tat the end of each epoch. If training restarted before completion, the\n\ttraining state and model are restored to the most recently saved state at the\n\tbeginning of a new model.fit() run.\n\n\tNote:\n\t1. This callback is not compatible with disabling eager execution.\n\t2. A checkpoint is saved at the end of each epoch, when restoring we'll redo\n\tany partial work from an unfinished epoch in which the training got restarted\n\t(so the work done before a interruption doesn't affect the final model state).\n\t3. This works for both single worker and multi-worker mode, only\n\tMirroredStrategy and MultiWorkerMirroredStrategy are supported for now.\n\tExample:\n\t>>> class InterruptingCallback(tf.keras.callbacks.Callback):\n\t... def on_epoch_begin(self, epoch, logs=None):\n\t... if epoch == 4:\n\t... raise RuntimeError('Interrupting!')\n\t>>> callback = tf.keras.callbacks.experimental.BackupAndRestore(\n\t... backup_dir=\"/tmp\")\n\t>>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])\n\t>>> model.compile(tf.keras.optimizers.SGD(), loss='mse')\n\t>>> try:\n\t... model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10,\n\t... batch_size=1, callbacks=[callback, InterruptingCallback()],\n\t... verbose=0)\n\t... except:\n\t... pass\n\t>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10,\n\t... batch_size=1, callbacks=[callback], verbose=0)\n\t>>> # Only 6 more epochs are run, since first trainning got interrupted at\n\t>>> # zero-indexed epoch 4, second training will continue from 4 to 9.\n\t>>> len(history.history['loss'])\n\n\tArguments:\n\t backup_dir: String,\n\t\tpath to save the model file. This is the directory in\n\t\twhich the system stores temporary files to recover the model from jobs\n\t\tterminated unexpectedly. The directory cannot be reused elsewhere to\n\t\tstore other checkpoints, e.g. by BackupAndRestore callback of another\n\t\ttraining, or by another callback (ModelCheckpoint) of the same training.\n\t\"\"\"\n\n\tdef __init__(self, backup_dir):\n\t\tsuper(BackupAndRestore, self).__init__()\n\t\tself.backup_dir = backup_dir\n\t\tself._supports_tf_logs = True\n\t\t# self._supported_strategies = (\n\t\t# \tdistribute_lib._DefaultDistributionStrategy,\n\t\t# \tmirrored_strategy.MirroredStrategy,\n\t\t# \tcollective_all_reduce_strategy.CollectiveAllReduceStrategy)\n\n\t\tif not context.executing_eagerly():\n\t\t\tif ops.inside_function():\n\t\t\t\traise ValueError('This Callback\\'s method contains Python state and '\n\t\t\t\t\t\t\t 'should be called outside of `tf.function`s.')\n\t\t\telse: # Legacy graph mode:\n\t\t\t\traise ValueError(\n\t\t\t\t\t'BackupAndRestore only supports eager mode. In graph '\n\t\t\t\t\t'mode, consider using ModelCheckpoint to manually save '\n\t\t\t\t\t'and restore weights with `model.load_weights()` and by '\n\t\t\t\t\t'providing `initial_epoch` in `model.fit()` for fault tolerance.')\n\n\t\t# Only the chief worker writes model checkpoints, but all workers\n\t\t# restore checkpoint at on_train_begin().\n\t\tself._chief_worker_only = False\n\n\tdef set_model(self, model):\n\t\tself.model = model\n\n\tdef on_train_begin(self, logs=None):\n\t\t# TrainingState is used to manage the training state needed for\n\t\t# failure-recovery of a worker in training.\n\t\t# pylint: disable=protected-access\n\t\t# if not isinstance(self.model.distribute_strategy,self._supported_strategies):\n\t\t# \traise NotImplementedError(\n\t\t# \t\t\t\t\t\t\t 'Currently only support empty strategy, MirroredStrategy and '\n\t\t# \t\t\t\t\t\t\t 'MultiWorkerMirroredStrategy.')\n\t\tself.model._training_state = (WorkerTrainingState(self.model, self.backup_dir))\n\t\tself._training_state = self.model._training_state\n\t\tself._training_state.restore()\n\t\t# signal.signal(signal.SIGINT, self._delete_backup_signal)\n\n\tdef on_train_end(self, logs=None):\n\t\t# pylint: disable=protected-access\n\t\t# On exit of training, delete the training state backup file that was saved\n\t\t# for the purpose of worker recovery.\n\t\tif self.model._in_multi_worker_mode():\n\t\t\tif self.model.stop_training or getattr(self.model, '_successful_loop_finish', False):\n\t\t\t\tself._training_state.delete_backup()\n\t\t\t\t# del self._training_state\n\t\t\t\t# del self.model._training_state\n\n\tdef on_epoch_end(self, epoch, logs=None):\n\t\t# Back up the model and current epoch for possible future recovery.\n\t\tself._training_state.back_up(epoch)\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass BaseCallback(Callback):\n\n\tdef __init__(self, log_dir, seed = None):\n\t\tsuper().__init__()\n\t\tself.log_dir = log_dir\n\t\tself.seed = seed\n\t\tself.writer = tf.compat.v1.summary.FileWriter(self.log_dir)\n\n\n\tdef write_image_summary(self, input_image, title='images', epoch=0):\n\t\timage_summary = tf.summary.image(title, input_image)\n\t\timg_sum = self.sess.run(image_summary)\n\t\tself.writer.add_summary(img_sum, global_step=epoch)\n\t\tprint('Finished image summary writing')\n\n\tdef get_batch(self):\n\t\tbatch = self.sess.run(self.validation_data)\n\t\treturn batch\n\n\tdef get_random_batch(self, max=40):\n\t\ti = random.randint(1,max)\n\t\tfor _ in range(i):\n\t\t\tbatch = self.get_batch()\n\t\treturn batch\n\n\tdef variable_summaries(self, var):\n\t\t\"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n\t\twith tf.compat.v1.name_scope('summaries'):\n\t\t\tmean = tf.reduce_mean(input_tensor=var)\n\t\t\ttf.compat.v1.summary.scalar('mean', mean)\n\t\twith tf.compat.v1.name_scope('stddev'):\n\t\t\tstddev = tf.sqrt(tf.reduce_mean(input_tensor=tf.square(var - mean)))\n\t\t\ttf.compat.v1.summary.scalar('stddev', stddev)\n\t\ttf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var))\n\t\ttf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var))\n\t\ttf.compat.v1.summary.histogram('histogram', var)\n\n\t@property\n\tdef seed(self):\n\t\treturn self._seed\n\n\[email protected]\n\tdef seed(self, seed=None):\n\t\tself._seed = seed or random.randint(-1e5,1e5)\n\t\trandom.seed(self.seed)\n\n\n\n\n\n\nclass NeptuneVisualizationCallback(Callback):\n\t\"\"\"Callback for logging to Neptune.\n\n\t1. on_batch_end: Logs all performance metrics to neptune\n\t2. on_epoch_end: Logs all performance metrics + confusion matrix + roc plot to neptune\n\n\tParameters\n\t----------\n\tmodel : type\n\t\tDescription of parameter `model`.\n\tvalidation_data : list\n\t\tlen==2 list containing [images, labels]\n\timage_dir : type\n\t\tDescription of parameter `image_dir`.\n\n\tExamples\n\t-------\n\tExamples should be written in doctest format, and\n\tshould illustrate how to use the function/class.\n\t>>>\n\n\tAttributes\n\t----------\n\tmodel\n\tvalidation_data\n\n\t\"\"\"\n\tdef __init__(self, validation_data):\n\t\tsuper().__init__()\n\t\t# self.model = model\n\t\tself.validation_data = validation_data\n\n\tdef on_batch_end(self, batch, logs={}):\n\t\tfor log_name, log_value in logs.items():\n\t\t\tneptune.log_metric(f'batch_{log_name}', log_value)\n\n\tdef on_epoch_end(self, epoch, logs={}):\n\t\tfor log_name, log_value in logs.items():\n\t\t\tneptune.log_metric(f'epoch_{log_name}', log_value)\n\n\t\ty_pred = np.asarray(self.model.predict(self.validation_data[0]))\n\t\ty_true = self.validation_data[1]\n\n\t\ty_pred_class = np.argmax(y_pred, axis=1)\n\n\t\tfig, ax = plt.subplots(figsize=(16, 12))\n\t\tplot_confusion_matrix(y_true, y_pred_class, ax=ax)\n\t\tneptune.log_image('confusion_matrix', fig)\n\n\t\tfig, ax = plt.subplots(figsize=(16, 12))\n\t\tplot_roc(y_true, y_pred, ax=ax)\n\t\tneptune.log_image('roc_curve', fig)\n\n\n\n\n\n\n\n\n\n\nclass ConfusionMatrixCallback(Callback):\n\n\tdef __init__(self, log_dir, val_imgs, val_labels, classes, freq=1, seed=None):\n\t\tsuper().__init__()\n\t\tself.file_writer = tf.contrib.summary.create_file_writer(log_dir)\n\t\tself.log_dir = log_dir\n\t\tself.seed = seed\n\t\tself._counter = 0\n\t\tself.val_imgs = val_imgs\n\n\t\tif val_labels.ndim==2:\n\t\t\tval_labels = tf.argmax(val_labels,axis=1)\n\t\tself.val_labels = val_labels\n\t\tself.num_samples = val_labels.numpy().shape[0]\n\t\tself.classes = classes\n\t\tself.freq = freq\n\n\tdef log_confusion_matrix(self, model, imgs, labels, epoch, norm_cm=False):\n\n\t\tpred_labels = model.predict_classes(imgs)# = tf.reshape(imgs, (-1,PARAMS['image_size'], PARAMS['num_channels'])))\n\t\tpred_labels = pred_labels[:,None]\n\n\t\tcon_mat = tf.math.confusion_matrix(labels=labels, predictions=pred_labels, num_classes=len(self.classes)).numpy()\n\t\tif norm_cm:\n\t\t\tcon_mat = np.around(con_mat.astype('float') / con_mat.sum(axis=1)[:, np.newaxis], decimals=2)\n\t\tcon_mat_df = pd.DataFrame(con_mat,\n\t\t\t\t\t\t index = self.classes,\n\t\t\t\t\t\t columns = self.classes)\n\n\t\tfigure = plt.figure(figsize=(16, 16))\n\t\tsns.heatmap(con_mat_df, annot=True,cmap=plt.cm.Blues)\n\t\tplt.tight_layout()\n\t\tplt.ylabel('True label')\n\t\tplt.xlabel('Predicted label')\n\n\t\tbuf = io.BytesIO()\n\t\tplt.savefig(buf, format='png')\n\t\tbuf.seek(0)\n\n\t\timage = tf.image.decode_png(buf.getvalue(), channels=4)\n\t\timage = tf.expand_dims(image, 0)\n\n\t\twith self.file_writer.as_default(), tf.contrib.summary.always_record_summaries():\n\t\t\ttf.contrib.summary.image(name='val_confusion_matrix',\n\t\t\t\t\t\t\t\t\t tensor=image,\n\t\t\t\t\t\t\t\t\t step=self._counter)\n\n\t\tneptune.log_image(log_name='val_confusion_matrix',\n\t\t\t\t\t\t x=self._counter,\n\t\t\t\t\t\t y=figure)\n\t\tplt.close(figure)\n\n\t\tself._counter += 1\n\n\t\treturn image\n\n\tdef on_epoch_end(self, epoch, logs={}):\n\n\t\tif (not self.freq) or (epoch%self.freq != 0):\n\t\t\treturn\n\t\tself.log_confusion_matrix(self.model, self.val_imgs, self.val_labels, epoch=epoch)\n\n\n################################################\n\nclass VisualizeActivationsCallback(BaseCallback):\n\n\tdef __init__(self, val_data, log_dir, freq=10, seed=None, sess=None):\n\t\tsuper().__init__(log_dir=log_dir, seed=seed)\n\t\tself.graph = tf.get_default_graph() #self.sess.graph #\n\t\tself.sess = sess or tf.Session()\n\t\tself.validation_iterator = val_data.make_one_shot_iterator()\n\t\tself.validation_data = self.validation_iterator.get_next()\n\t\tself.freq = freq\n\n\tdef write_activation_summaries(self, model, input_images, input_labels, epoch=0):\n\t\tif type(model.layers[0])==tf.python.keras.engine.training.Model:\n\t\t\t#In case model was constructed from a base model\n\t\t\tmodel = model.layers[0]\n\n\t\tactivation_grids_list = visualize_activations(input_images, model, self.sess, self.graph, group='vgg16_conv_block_outputs')[:1]\n\t\ti=0\n\t\tfor activation_grid in activation_grids_list:\n\t\t\t# layer_name = get_layers_by_index(model,[i])[0].name\n\t\t\tlayer_name, grid_summary = self.sess.run(*activation_grid)\n\t\t\tself.write_image_summary(grid_summary, title=f'Layer : {layer_name}', epoch=epoch)\n\n\tdef on_epoch_end(self, epoch, logs={}):\n\n\t\tif self.freq==0:\n\t\t\treturn\n\t\tif epoch % self.freq != 0:\n\t\t\treturn\n\n\t\tinput_images, input_labels = self.get_random_batch()\n\t\tself.seed += 1\n\n\t\t# with self.sess.as_default():\n\t\tself.write_activation_summaries(self.model, input_images, input_labels, epoch=epoch)\n\n#############################################################\n\n\n# class ConfusionMatrixCallback(BaseCallback):\n#\n# def __init__(self, val_data, batches_per_epoch, log_dir, freq=10, sess=None):\n# super().__init__(log_dir)\n# # self.sess = tf.Session()\n# self.graph = tf.get_default_graph() #self.sess.graph #\n# self.sess = sess or tf.Session()\n# self.validation_iterator = val_data.make_one_shot_iterator()\n# self.validation_data = self.validation_iterator.get_next()\n# self.batches_per_epoch = batches_per_epoch\n# self.freq = freq\n# print('EXECUTING EAGERLY: ', tf.executing_eagerly())\n# # self.writer = tf.compat.v1.summary.FileWriter(self.log_dir)\n#\n# def confusion_matrix(self, y_target, y_predicted, binary=False, positive_label=1):\n# # import pdb; pdb.set_trace()\n# cm = evaluate.confusion_matrix(y_target, y_predicted, binary=binary, positive_label=positive_label)\n# fig, ax = plotting.plot_confusion_matrix(conf_mat=cm)\n# buffer = io.BytesIO()\n# fig.savefig(buffer, format='png')\n# buffer.seek(0)\n# img = tf.image.decode_png(buffer.getvalue(), channels=4)\n# img = tf.expand_dims(img, 0)\n# return img\n#\n# def on_epoch_end(self, epoch, logs={}):\n# # import pdb;pdb.set_trace()\n# image_summary = []\n#\n# if self.freq==0:\n# return\n# if epoch % self.freq != 0:\n# return\n#\n# val_data = (self.get_batch() for _ in range(self.batches_per_epoch))\n# real_fake = {'y_pred':[],'labels':[]}\n# for imgs, labels in val_data:\n# y_logits = self.model.predict(imgs)\n# y_pred = np.argmax(y_logits, axis=1).tolist()\n# y_true = np.argmax(labels, axis=1).tolist()\n# real_fake['y_pred'].extend(y_pred)\n# real_fake['labels'].extend(y_true)\n# cm = self.confusion_matrix(real_fake['labels'], real_fake['y_pred'])\n# self.write_image_summary(cm, 'confusion matrix', epoch=epoch)\n# if 'confusion_matrix' not in logs:\n# logs['confusion_matrix'] = []\n#\n# logs['confusion_matrix'].append(cm)\n\t\t# return epoch, logs\n\n\n\n\n\n\n\n\n\n# class TensorflowImageLogger(Callback):\n#\n# def __init__(self, val_data, log_dir, max_images=25, freq=10, sess=None):\n# super().__init__()\n# self.log_dir = log_dir\n# self.graph = tf.get_default_graph() #self.sess.graph #\n# self.sess = sess or tf.Session()\n# # self.sess = tf.Session()\n# self.validation_iterator = val_data.make_one_shot_iterator()\n# self.validation_data = self.validation_iterator.get_next()\n#\n# self.max_images = max_images\n# self.freq = freq\n# print('EXECUTING EAGERLY: ', tf.executing_eagerly())\n#\n# self.writer = tf.compat.v1.summary.FileWriter(self.log_dir)\n#\n# def get_batch(self):\n# batch = self.sess.run(self.validation_data)\n# return batch\n#\n# @tfmpl.figure_tensor\n# def image_grid(self, input_images=[], titles=[]):\n# \"\"\"Return a 5x5 grid of the MNIST images as a matplotlib figure.\"\"\"\n# max_images = self.max_images\n#\n# r, c = 3, 5\n# # figure = plt.figure(figsize=(10,10))\n# figs = tfmpl.create_figures(1, figsize=(20,30))\n# cnt = 0\n# for idx, f in enumerate(figs):\n# for i in range(r):\n# for j in range(c):\n# ax = f.add_subplot(r,c, cnt + 1)#, title=input_labels[cnt])\n# ax.set_xticklabels([])\n# ax.set_yticklabels([])\n# img = input_images[cnt]\n# ax.set_title(titles[cnt])\n# ax.imshow(img)\n# cnt+=1\n# f.tight_layout()\n# return figs\n#\n# def write_image_summary(self, input_images, input_labels, titles):\n# # with K.get_session() as sess:\n# if True:\n# image_summary = tf.summary.image(f'images', self.image_grid(input_images, titles))\n# img_sum = self.sess.run(image_summary)\n# self.writer.add_summary(img_sum)\n# print('Finished image summary writing')\n#\n# def on_epoch_end(self, epoch, logs={}):\n# image_summary = []\n# # batch_size = self.max_images\n# input_images, input_labels = self.get_batch()\n#\n#\n# print(input_images.shape)\n# titles = []\n# for idx in range(15):\n# img = input_images[idx]\n#\n# img_min, img_max = np.min(img), np.max(img)\n# if (img_max <= 1.0) and (img_min >= -1.0):\n# #Scale from [-1.0,1.0] to [0.0,1.0] for visualization\n# titles.append(f'(min,max) pixels = ({img_min:0.1f},{img_max:0.1f})|rescaled->[0.0,1.0]')\n# img += 1\n# img /= 2\n# else:\n# titles.append(f'(min,max) pixels = ({img_min:0.1f},{img_max:0.1f})')\n#\n# self.write_image_summary(input_images, input_labels, titles)\n\n\ndef get_callbacks(weights_best=r'./model_ckpt.h5',\n\t\t\t\t logs_dir=r'/media/data/jacob',\n\t\t\t\t restore_best_weights=False,\n\t\t\t\t val_data=None,\n\t\t\t\t batches_per_epoch=20,\n\t\t\t\t histogram_freq=10,\n\t\t\t\t freq=10,\n\t\t\t\t seed=None,\n\t\t\t\t patience=25,\n\t\t\t\t sess=None):\n\n\n\tcheckpoint = ModelCheckpoint(weights_best, monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=False, mode='min',restore_best_weights=restore_best_weights)\n\n\ttfboard = TensorBoard(log_dir=logs_dir, histogram_freq=histogram_freq)#, write_images=True)\n\tcsv = CSVLogger(os.path.join(logs_dir,'training_log.csv'))\n\tearly = EarlyStopping(monitor='val_loss', patience=patience, verbose=1)\n\n\tcallback_list = [checkpoint,tfboard,early,csv]\n\n\tif val_data is not None:\n\t\t# callback_list.append(VisualizeActivationsCallback(val_data, logs_dir, freq=freq, seed=seed, sess=sess))\n\t\tcallback_list.append(ConfusionMatrixCallback(val_data, batches_per_epoch, logs_dir, freq=freq, sess=sess))\n\t\t# callback_list.append(TensorflowImageLogger(val_data, log_dir = logs_dir, freq=freq))\n\t\tif sess is not None:\n\t\t\tsess.run(tf.initialize_all_variables())\n\treturn callback_list\n"
]
| [
[
"tensorflow.reduce_min",
"tensorflow.compat.v1.summary.histogram",
"tensorflow.python.framework.ops.inside_function",
"tensorflow.compat.v1.keras.callbacks.ModelCheckpoint",
"tensorflow.contrib.summary.image",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.compat.v1.summary.FileWriter",
"tensorflow.compat.v1.name_scope",
"tensorflow.get_default_graph",
"pandas.DataFrame",
"matplotlib.pyplot.savefig",
"tensorflow.argmax",
"matplotlib.pyplot.subplots",
"tensorflow.compat.v1.keras.callbacks.EarlyStopping",
"numpy.argmax",
"matplotlib.pyplot.tight_layout",
"tensorflow.initialize_all_variables",
"tensorflow.expand_dims",
"tensorflow.Session",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"tensorflow.contrib.summary.create_file_writer",
"tensorflow.compat.v1.summary.scalar",
"tensorflow.summary.image",
"matplotlib.pyplot.xlabel",
"tensorflow.contrib.summary.always_record_summaries",
"tensorflow.reduce_max",
"tensorflow.compat.v1.keras.callbacks.TensorBoard",
"matplotlib.pyplot.ylabel",
"tensorflow.reduce_mean",
"tensorflow.square"
]
]
|
Ocete/TFG | [
"baf0853276aef8f6fd6c5cccbe69ede7ca7987c3"
]
| [
"dwave/2 - simulated/2.py"
]
| [
"# ref: https://github.com/prince-ph0en1x/QuASeR/blob/819fcfa85a3a9486ee27a95808f245e51ab1d5de/QA_DeNovoAsb/denovo_009.py\n\n\"\"\"\nExplore embedding\n\"\"\"\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport sys\nimport time\nfrom collections import defaultdict\n\nimport dimod\nimport neal\nimport minorminer\nimport dwave_networkx as dnx\nfrom dwave.cloud import Client\nfrom dwave.embedding import embed_ising, unembed_sampleset\nfrom dwave.embedding.utils import edgelist_to_adjacency\nfrom dwave.system.samplers import DWaveSampler\nfrom dwave.embedding.chain_breaks import majority_vote\n\n\"\"\"\nRead *.qubo file to form the QUBO model\n\"\"\"\ndef quboFile_to_quboDict(filename):\n\tf = open(filename, \"r\")\n\tqubo_header = f.readline().split()\n\tQ = {}\n\tfor i in range(0,int(qubo_header[4])):\n\t\tx = f.readline().split()\n\t\tQ[(x[0],x[1])] = float(x[2])\n\tfor i in range(0,int(qubo_header[5])):\n\t\tx = f.readline().split()\n\t\tQ[(x[0],x[1])] = float(x[2])\n\tf.close()\n\treturn Q\n\n\"\"\"\nOverlap between pair-wise reads\n\"\"\"\ndef align(read1, read2, mm):\n\tl1 = len(read1)\n\tl2 = len(read2)\n\tfor shift in range(l1-l2,l1):\n\t\tmmr = 0\n\t\tr2i = 0\n\t\tfor r1i in range(shift,l1):\n\t\t\tif read1[r1i] != read2[r2i]:\n\t\t\t\tmmr += 1\n\t\t\tr2i += 1\n\t\t\tif mmr > mm:\n\t\t\t\tbreak\n\t\tif mmr <= mm:\n\t\t\treturn l2-shift\n\treturn 0\n\n\"\"\"\nConvert set of reads to adjacency matrix of pair-wise overlap for TSP\n\"\"\"\ndef reads_to_tspAdjM(reads, max_mismatch = 0):\n\tn_reads = len(reads)\n\tO_matrix = np.zeros((n_reads,n_reads)) # edge directivity = (row id, col id)\n\tfor r1 in range(0,n_reads):\n\t\tfor r2 in range(0,n_reads):\n\t\t\tif r1!=r2:\n\t\t\t\tO_matrix[r1][r2] = align(reads[r1],reads[r2],max_mismatch)\n\tO_matrix = O_matrix / np.linalg.norm(O_matrix)\n\treturn O_matrix\n\n\"\"\"\nConvert adjacency matrix of pair-wise overlap for TSP to QUBO matrix of TSP\n\"\"\"\ndef tspAdjM_to_quboAdjM(tspAdjM, p0, p1, p2):\n\tn_reads = len(tspAdjM)\n\t# Initialize\n\tQ_matrix = np.zeros((n_reads**2,n_reads**2)) # Qubit index semantics: {c(0)t(0) |..| c(i)-t(j) | c(i)t(j+1) |..| c(i)t(n-1) | c(i+1)t(0) |..| c(n-1)t(n-1)}\n\t# Assignment reward (self-bias)\n\tp0 = -1.6\n\tfor ct in range(0,n_reads**2):\n\t\tQ_matrix[ct][ct] += p0\n\t# Multi-location penalty\n\tp1 = -p0 # fixed emperically by trail-and-error\n\tfor c in range(0,n_reads):\n\t\tfor t1 in range(0,n_reads):\n\t\t\tfor t2 in range(0,n_reads):\n\t\t\t\tif t1!=t2:\n\t\t\t\t\tQ_matrix[c*n_reads+t1][c*n_reads+t2] += p1\n\t# Visit repetation penalty\n\tp2 = p1\n\tfor t in range(0,n_reads):\n\t\tfor c1 in range(0,n_reads):\n\t\t\tfor c2 in range(0,n_reads):\n\t\t\t\tif c1!=c2:\n\t\t\t\t\tQ_matrix[c1*n_reads+t][c2*n_reads+t] += p2\n\t# Path cost\n\t# kron of tspAdjM and a shifted diagonal matrix\n\tfor ci in range(0,n_reads):\n\t\tfor cj in range(0,n_reads):\n\t\t\tfor ti in range(0,n_reads):\n\t\t\t\ttj = (ti+1)%n_reads\n\t\t\t\tQ_matrix[ci*n_reads+ti][cj*n_reads+tj] += -tspAdjM[ci][cj]\n\treturn Q_matrix\n\n\"\"\"\nConvert QUBO matrix of TSP to QUBO dictionary of weighted adjacency list\n\"\"\"\ndef quboAdjM_to_quboDict(Q_matrix):\n\tn_reads = int(math.sqrt(len(Q_matrix)))\n\tQ = {}\n\tfor i in range(0,n_reads**2):\n\t\tni = 'n'+str(int(i/n_reads))+'t'+str(int(i%n_reads))\n\t\tfor j in range(0,n_reads**2):\n\t\t\tnj = 'n'+str(int(j/n_reads))+'t'+str(int(j%n_reads))\n\t\t\tif Q_matrix[i][j] != 0:\n\t\t\t\tQ[(ni,nj)] = Q_matrix[i][j]\n\treturn Q\n\n\"\"\"\nSolve a QUBO model using dimod exact solver\n\"\"\"\ndef solve_qubo_simulated(Q, all=False, print_it=False, save_it=False, num_reads=10000):\n\t#solver = dimod.SimulatedAnnealingSampler()\n\tsampler = neal.SimulatedAnnealingSampler()\n\t\n\tstart = time.time()\n\tresponse = sampler.sample_qubo(Q, num_reads=num_reads)\n\tqpu_time = time.time() - start\n\n\t# Count the number of ocurrences\n\tocurrences = defaultdict(int)\n\tfor sample, energy in response.data(['sample', 'energy']):\n\t\tfrozen_sample = frozenset(sample.items())\n\t\tocurrences[frozen_sample] += 1\n\n\t# Print the results\n\tif print_it:\n\t\tprinted = defaultdict(bool)\n\t\tfor sample, energy in response.data(['sample', 'energy']):\n\t\t\tfrozen_sample = frozenset(sample.items())\n\t\t\tif not printed[frozen_sample]:\n\t\t\t\tprinted[frozen_sample] = True\n\t\t\t\tprint('({}, {}) --> {:.4f}'.format(sample, ocurrences[frozen_sample], energy))\n\n\tif save_it:\n\t\ttarget = open('results.txt', 'w')\n\t\ttarget.write('{\\n')\n\t\tprinted_2 = defaultdict(bool)\n\n\t\tfor sample, energy in response.data(['sample', 'energy']):\n\t\t\tfrozen_sample = frozenset(sample.items())\n\t\t\tif not printed_2[frozen_sample]:\n\t\t\t\tprinted_2[frozen_sample] = True\n\t\t\t\ttarget.write('{}: ({}, {:.4f}),\\n'.format(frozen_sample, ocurrences[frozen_sample], energy))\n\n\t\ttarget.write('}')\n\n\treturn qpu_time\n\n\"\"\"\nSolve de novo assembly on D-Wave annealer\n\"\"\"\ndef deNovo_on_DWave(print_it=False, save_it=False):\n\treads = ['ATGGCGTGCA', 'GCGTGCAATG', 'TGCAATGGCG', 'AATGGCGTGC']\n\t# print('reads: {}'.format(reads))\n\n\ttspAdjM = reads_to_tspAdjM(reads)\n\t# print('tspAdjM: {}'.format(tspAdjM))\n\n\tquboAdjM = tspAdjM_to_quboAdjM(tspAdjM, -1.6, 1.6, 1.6) # self-bias, multi-location, repetition\n\t# print('quboAdjM: {}'.format(quboAdjM))\n\n\tquboDict = quboAdjM_to_quboDict(quboAdjM)\n\t# print('quboDict: {}'.format(quboDict))\n\n\treturn solve_qubo_simulated(quboDict, all=False, print_it=print_it, save_it=save_it)\n\n\ndef compute_mean_time(repeat=10):\n\tmean = 0.0\n\tfor _ in range(repeat):\n\t\tmean += deNovo_on_DWave()\n\tprint('Mean time in {} executions: {}'.format(repeat, mean/repeat))\n\n\n\"\"\"\nEXPERIMENT 2\n\"\"\"\n\n#deNovo_on_DWave(print_it=False, save_it=False)\n\ncompute_mean_time()\n"
]
| [
[
"numpy.linalg.norm",
"numpy.zeros"
]
]
|
MyPyDavid/ECpy | [
"b74842b64eca86d2181067fdb22bfa8fa4b2c8bb"
]
| [
"src/elchempy/indexer/EC_index.py"
]
| [
"\"\"\" Collects the files of index files of a folder\"\"\"\n\nfrom pathlib import Path\nfrom collections import Counter\nfrom functools import wraps\n\nimport datetime\nfrom typing import Tuple, List, Dict, Union, Collection\n\n# import re\n# import copy\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\n\nfrom elchempy.indexer.data import DATABASE\n\n# from elchempy.dataloaders.files_func_collector import run_func_on_files\n# from elchempy.experiments.dataloaders.fetcher import ElChemData\n\nfrom elchempy.indexer.helpers import find_relevant_files_in_folder\n\nfrom elchempy.indexer.creator import create_index\n\n\n### for Developing\nfrom elchempy.config import LOCAL_FILES, RAW_DATA_DIR, DEST_DATA_DIR\n\n### 3rd Party imports\n\nimport pandas as pd\nfrom pyarrow import ArrowInvalid\n\n#%%\nclass ElChemIndex:\n \"\"\"\n\n Creates an index of files in a given folder.\n\n Collects the parsers instances for a list of files.\n Can include metadata from file instrospection or only from parsing the filename\n\n \"\"\"\n\n supported_store_types = [\"feather\", \"sqlite\"]\n\n def __init__(\n self,\n folder,\n dest_dir=None,\n include_metadata=False,\n multi_run=False,\n store_type=\"feather\",\n force_reload=False,\n ):\n self._folder = Path(folder)\n self._dest_dir = Path(dest_dir)\n self._multi_run = multi_run\n self._include_metadata = include_metadata\n self._store_type = store_type\n self._force_reload = force_reload\n\n self.files = find_relevant_files_in_folder(self._folder)\n # = files#[500::]\n self.store_file = self.get_store_file(\n store_type=self._store_type, dest_dir=self._dest_dir\n )\n\n loaded_index = self.load_index(self.store_file)\n if isinstance(loaded_index, pd.DataFrame) and not self._force_reload:\n index = loaded_index\n ecpps, ecds = None, None # class instance objects are not reloaded\n else:\n index, ecpps, ecds = create_index(\n self.files,\n multi_run=self._multi_run,\n include_metadata=self._include_metadata,\n )\n self.store_index(index, self.store_file, overwrite=True)\n\n self.index = index\n self.ecpps = ecpps\n self.ecds = ecds\n\n def add_methods(self):\n \"\"\"for persistence and loading of this 'collection' in eg a database or pkl file\"\"\"\n\n def get_store_file(self, store_type=\"\", dest_dir=None, filename=\"index\"):\n if not (store_type and dest_dir):\n return None\n\n if store_type not in self.supported_store_types:\n logger.warning(\"store type {store_type} is not supported\")\n return None\n\n if dest_dir.is_file():\n dest_dir = dest_dir.parent\n\n daily_filepath = dest_dir.joinpath(f\"{datetime.date.today()}_{filename}\")\n\n if \"feather\" in store_type:\n store_file = daily_filepath.with_suffix(\".feather\")\n\n return store_file\n\n def store_index(self, index, store_file: Path = None, overwrite=False):\n if not store_file:\n logger.warning(f\"No store file given: {store_file}\")\n return None\n if not isinstance(index, pd.DataFrame):\n logger.warning(f\"Index type is not pd.DataFrame: {type(index)}\")\n return None\n if store_file.exists() and not overwrite:\n logger.warning(f\"Index file exists and will not be overwritten.\")\n return None\n\n index = index.reset_index()\n\n try:\n index.to_feather(store_file)\n except ArrowInvalid as exc:\n logger.error(f\"error to_feather: {store_file}\\n{exc}\")\n\n logger.info(f\"Index saved to : {store_file}\")\n\n def load_index(self, store_file: Path = None):\n if not store_file.exists():\n logger.warning(f\"Store file does not exist: {store_file}\")\n return None\n try:\n index = pd.read_feather(store_file)\n except ArrowInvalid as exc:\n logger.error(f\"error read_feather: {store_file}\\n{exc}\")\n index = None\n\n logger.info(f\"Index loaded from : {store_file}\")\n return index\n\n\n#%%\ndef _dev_testing():\n files = self.files\n ElChemPathParser(files[159])\n\n\nif __name__ == \"__main__\":\n\n folder = LOCAL_FILES[0].parent.parent\n # folder = '/mnt/DATA/EKTS_CloudStation/CloudStation/Experimental data/Raw_data/VERSASTAT'\n\n ecppcol = ElChemIndex(\n RAW_DATA_DIR,\n dest_dir=DEST_DATA_DIR,\n multi_run=True,\n include_metadata=True,\n force_reload=False,\n )\n self = ecppcol\n idx = self.index\n # print(self.index.ecpp_token_remainder.values)\n # print(self.index['ecpp_token_remainder'].dropna().unique())\n"
]
| [
[
"pandas.read_feather"
]
]
|
gcfntnu/small-rna | [
"459f946dfb338017e8beb350da215aaac6a37c59",
"459f946dfb338017e8beb350da215aaac6a37c59"
]
| [
"rules/bfq/scripts/plot_highly_expressed.py",
"rules/bfq/scripts/plotpca.py"
]
| [
"#!/usr/bin env python\n\nimport sys\nimport argparse\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\n\nimport yaml\nimport pandas as pd\nimport numpy as np\nimport scanpy as sc\n\nfrom scipy.sparse import issparse\n\ndef higly_expressed_yaml(adata, n_top=10, biotype=None):\n \"\"\"plot the top 10 highest expressed genes\n \"\"\"\n adata = adata.copy()\n norm_dict = sc.pp.normalize_total(adata, target_sum=100, inplace=False)\n adata.layers['CPM'] = norm_dict['X']\n adata.obs['norm_factor'] = norm_dict['norm_factor']\n \n if issparse(norm_dict['X']):\n mean_percent = norm_dict['X'].mean(axis=0).A1\n top_idx = np.argsort(mean_percent)[::-1][:n_top]\n else:\n mean_percent = norm_dict['X'].mean(axis=0)\n top_idx = np.argsort(mean_percent)[::-1][:n_top]\n top_genes = adata.var_names[top_idx]\n top_adata = adata[:,top_genes]\n \n keys = {}\n default_colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',\n '#8085e9','#f15c80', '#e4d354', '#2b908f',\n '#f45b5b', '#91e8e1']\n for i, name in enumerate(top_genes):\n color = default_colors[i]\n keys[name] = {'color': color, 'name': name}\n \n # Config for the plot\n data_labels= [{'name': 'CPM', 'ylab': 'CPM'}, {'name': 'counts', 'ylab': '# reads'}]\n data = [top_adata.to_df(layer='CPM').to_dict(orient='index'), top_adata.to_df().to_dict(orient='index')]\n pconfig = {\n 'id': 'gene_high',\n 'cpswitch': False,\n 'title': 'Higly Expressed miRNA',\n 'data_labels': data_labels\n }\n \n section = {}\n section['id'] = 'gene_high'\n section['section_name'] = 'Higly Expressed miRNA'\n section['description'] = 'Summary of the 10 most highly expressed miRNA.'\n section['plot_type'] = 'bargraph'\n section['pconfig'] = pconfig\n section['categories'] = keys\n section['data'] = data\n\n return section\n\n\ndef argparser():\n parser = argparse.ArgumentParser(description=\"Higly expressed genes figure for QC report\")\n parser.add_argument(\"adata\", help=\"scanpy formatted file (.h5ad0) \")\n parser.add_argument(\"-o \", \"--output\", default=\"top10_mqc.pyaml\", help=\"Output filename. Will default to top10_mqc.yaml\")\n\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = argparser()\n adata = sc.read(args.adata)\n section = higly_expressed_yaml(adata)\n with open(args.output, 'w') as fh:\n yaml.dump(section, fh, default_flow_style=False, sort_keys=False)\n",
"#!/usr/bin env python\n\nimport sys\nimport argparse\nimport warnings\nwarnings.filterwarnings('ignore', message='numpy.dtype size changed')\n\nimport pandas as pd\nimport numpy as np\nimport scanpy as sc\nsc.settings.verbosity = 3\nsc.settings.set_figure_params(dpi=80, facecolor='white')\nsc.settings.autoshow = False\nsc.settings.figdir = '.'\nsc.plot_suffix = ''\n\n\nimport yaml\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nplt.ioff()\n\ndef argparser():\n parser = argparse.ArgumentParser(description='Dimred plot from anndata')\n parser.add_argument('-i', '--input',\n help='Input filename. Anndata file (.h5ad)')\n parser.add_argument('-o', '--output', default='umap_mqc.png',\n help='Output filename. Will default to umap_mqc.png, Optional')\n parser.add_argument('--recipe', default='mirna', choices = ['smallrna', 'rna', 'microbiome', 'deicode', 'vsd'],\n help='Preprocess recipe. ')\n parser.add_argument('--method', default='auto', choices = ['auto', 'umap', 'pca'],\n help='Dimension reduction method.') \n args = parser.parse_args()\n return args\n\n\ndef multiqc_png(adata, args):\n if use_umap:\n if args.output.endswith('.png'):\n sc.pl.umap(adata, color=color, save=args.output)\n else:\n tab_pc = pd.DataFrame(adata.obsm['X_umap'], index=adata.obs_names, columns=['UMAP1', 'UMAP2']) \n tab_pc.index.name = 'Sample_ID'\n tab_pc.to_csv(args.output, sep='\\t')\n else:\n if args.output.endswith('.png'):\n sc.pl.pca(adata, color=color, save=args.output)\n else:\n tab_pc = pd.DataFrame(adata.obsm['X_pca'], index=adata.obs_names, columns=['PC1', 'PC2']) \n tab_pc.index.name = 'Sample_ID'\n tab_pc.to_csv(args.output, sep='\\t')\n \n\ndef multiqc_section(args):\n section = {}\n section['parent_id'] = 'exploratory'\n section['parent_name'] = 'Exploratory analysis'\n section['parent_description'] = 'Exploratory analysis of feature table. A feature table is a count matrix with feature counts for each sample.'\n \n if args.method == 'pca':\n section['id'] = 'pca'\n section['section_name'] = 'PCA'\n section['description'] = 'Principal Component Analysis of tabulated counts.'\n elif args.method == 'umap':\n section['id'] = 'umap'\n section['section_name'] = 'UMAP'\n section['description'] = 'Uniform Manifold Approximation of tabulated counts.' \n section['plot_type'] = 'scatter'\n return section\n\ndef multiqc_pconfig(args):\n pconfig = {}\n pconfig['id'] = 'pca_scatter'\n pconfig['title'] = 'PCA'\n pconfig['xlab'] = 'PC1'\n pconfig['ylab'] = 'PC2'\n pconfig['tt_label'] = 'PC1 {point.x:.2f}: PC2 {point.y:.2f}'\n return pconfig\n\ndef multiqc_yaml(adata, args):\n if 'X_umap' in adata.obsm:\n x = adata.obsm['X_umap'].copy()\n else:\n x = adata.obsm['X_pca'].copy()\n max_comp = x.shape[1]\n T = pd.DataFrame(x[:,:2], index=adata.obs_names, columns=['x', 'y']) \n T.index.name = 'Sample_ID'\n S = adata.obs.copy()\n df1 = pd.concat([T, S], axis=\"columns\")\n if max_comp > 3:\n T2 = pd.DataFrame(x[:,2:4], index=adata.obs_names, columns=['x', 'y']) \n T2.index.name = 'Sample_ID'\n df2 = pd.concat([T2, S], axis=\"columns\")\n \n section = multiqc_section(args)\n pconfig = multiqc_pconfig(args)\n \n\n #pconfig['xmax'] = float(T['x'].max() + 0.1*T['x'].max())\n #pconfig['xmin'] = float(T['x'].min() + 0.1*T['x'].min())\n #pconfig['ymax'] = float(T['y'].max() + 0.1*T['y'].max())\n #pconfig['ymin'] = float(T['y'].min() + 0.1*T['y'].min())\n\n data_labels = [{'name': 'PC1 vs PC2', 'xlab': 'PC1', 'ylab': 'PC2'}]\n \n if max_comp > 3:\n data_labels.append({'name': 'PC3 vs PC4', 'xlab': 'PC3', 'ylab': 'PC4'})\n pconfig['data_labels'] = data_labels\n\n data = []\n data1 = {}\n default_colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9',\n '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1']\n if 'Sample_Group' in df1.columns:\n groups = set(df1['Sample_Group'])\n g_df = df1.groupby('Sample_Group')\n for i, g in enumerate(groups):\n sub = g_df.get_group(g)[['x', 'y']]\n sub['color'] = default_colors[i]\n sub['name'] = g\n this_series = sub.to_dict(orient='index')\n data1.update(this_series)\n else:\n data1.update(T.to_dict(orient='index'))\n data.append(data1)\n \n if max_comp > 3:\n df2 = pd.concat([T2, S], axis=\"columns\")\n data2 = {}\n if 'Sample_Group' in df2.columns:\n groups = set(df2['Sample_Group'])\n g_df = df2.groupby('Sample_Group')\n for i, g in enumerate(groups):\n sub = g_df.get_group(g)[['x', 'y']]\n sub['color'] = default_colors[i]\n sub['name'] = g\n this_series = sub.to_dict(orient='index')\n data2.update(this_series)\n else:\n data2.update(T2.to_dict(orient='index')) \n data.append(data2)\n \n section['pconfig'] = pconfig\n section['data'] = data\n return section\n\ndef rpca(adata):\n from deicode.matrix_completion import MatrixCompletion\n from deicode.preprocessing import rclr\n min_samples = max(3, np.floor(n_samples * 0.1))\n sc.pp.filter_genes(adata, min_cells=min_samples) \n X = rclr(adata.raw.X)\n opt = MatrixCompletion(n_components=n_comps, max_iterations=10).fit(X)\n n_components = opt.s.shape[0]\n X = opt.sample_weights @ opt.s @ opt.feature_weights.T\n X = X - X.mean(axis=0)\n X = X - X.mean(axis=1).reshape(-1, 1)\n adata.obsm['X_deicode'] = sc.tl.pca(X, svd_solver='arpack', n_comps=n_comps)\n return adata\n\nif __name__ == \"__main__\":\n args = argparser()\n \n adata = sc.read(args.input)\n\n #adata.obs['Sample_Group'] = adata.obs['Tissue'].copy()\n \n n_samples, n_genes = adata.shape\n if args.method == 'auto':\n if n_samples >= 20:\n args.method = 'umap'\n else:\n args.method = 'pca'\n\n color = ['Sample_Group'] if 'Sample_Group' in adata.obs.columns else None\n adata.raw = adata\n n_comps = min(20, min(adata.shape)-1)\n \n if args.recipe == 'mirna':\n min_samples = max(3, np.floor(n_samples * 0.1))\n sc.pp.filter_genes(adata, min_cells=min_samples)\n sc.pp.normalize_total(adata, target_sum=1e6)\n sc.pp.log1p(adata)\n sc.pp.highly_variable_genes(adata, min_mean=0.1, max_mean=20, min_disp=0.2)\n adata = adata[:, adata.var.highly_variable]\n \n elif args.recipe == 'deicode':\n min_samples = max(3, np.floor(n_samples * 0.1))\n sc.pp.filter_genes(adata, min_cells=min_samples) \n adata = rpca(adata)\n \n elif args.recipe == 'mrna':\n sc.pp.filter_genes(adata, min_cells=min_samples)\n sc.pp.normalize_total(adata, target_sum=1e6)\n sc.pp.log1p(adata)\n sc.pp.highly_variable_genes(adata, min_mean=0.8, max_mean=20, min_disp=0.2)\n adata = adata[:, adata.var.highly_variable]\n\n elif args.recipe == 'vsd':\n pass\n \n sc.tl.pca(adata, svd_solver='arpack', n_comps=n_comps)\n\n if args.method == 'umap':\n sc.pp.neighbors(adata, n_neighbors=min(7, np.ceil(n_samples/3.0)), n_pcs=min(15, n_comps))\n sc.tl.leiden(adata, resolution=0.5)\n sc.tl.paga(adata)\n sc.pl.paga(adata, plot=False)\n sc.tl.umap(adata, init_pos='paga')\n\n if args.method == 'umap':\n if args.output.endswith('_mqc.png'):\n fig = sc.pl.umap(adata, color=color, show=False, return_fig=True)\n fig.savefig(args.output, dpi=300, transparent=True)\n elif args.output.endswith('_mqc.yaml'):\n section = multiqc_yaml(adata, args)\n with open(args.output, 'w') as fh:\n yaml.dump(section, fh, default_flow_style=False, sort_keys=False)\n else:\n tab_pc = pd.DataFrame(adata.obsm['X_umap'], index=adata.obs_names, columns=['UMAP1', 'UMAP2']) \n tab_pc.index.name = 'Sample_ID'\n tab_pc.to_csv(args.output, sep='\\t')\n else:\n if args.output.endswith('_mqc.png'):\n fig = sc.pl.pca(adata, color=color, return_fig=True, show=False)\n fig.savefig(args,output, dpi=300, transparent=True)\n elif args.output.endswith('_mqc.yaml'):\n section = multiqc_yaml(adata, args)\n with open(args.output, 'w') as fh:\n yaml.dump(section, fh, default_flow_style=False, sort_keys=False)\n else:\n tab_pc = pd.DataFrame(adata.obsm['X_pca'], index=adata.obs_names, columns=['PC1', 'PC2']) \n tab_pc.index.name = 'Sample_ID'\n tab_pc.to_csv(args.output, sep='\\t')\n\n"
]
| [
[
"scipy.sparse.issparse",
"numpy.argsort"
],
[
"matplotlib.use",
"numpy.ceil",
"pandas.DataFrame",
"pandas.concat",
"matplotlib.pyplot.ioff",
"numpy.floor"
]
]
|
anshulparihar/scikit-learn | [
"3bb138f87964dde5f25846f4380afba012cf26bc"
]
| [
"sklearn/utils/extmath.py"
]
| [
"\"\"\"\nExtended math utilities.\n\"\"\"\n# Authors: Gael Varoquaux\n# Alexandre Gramfort\n# Alexandre T. Passos\n# Olivier Grisel\n# Lars Buitinck\n# Stefan van der Walt\n# Kyle Kastner\n# Giorgio Patrini\n# License: BSD 3 clause\n\nimport warnings\n\nimport numpy as np\nfrom scipy import linalg, sparse\n\nfrom . import check_random_state\nfrom ._logistic_sigmoid import _log_logistic_sigmoid\nfrom .sparsefuncs_fast import csr_row_norms\nfrom .validation import check_array\nfrom .validation import _deprecate_positional_args\n\n\ndef squared_norm(x):\n \"\"\"Squared Euclidean or Frobenius norm of x.\n\n Faster than norm(x) ** 2.\n\n Parameters\n ----------\n x : array-like\n\n Returns\n -------\n float\n The Euclidean norm when x is a vector, the Frobenius norm when x\n is a matrix (2-d array).\n \"\"\"\n x = np.ravel(x, order='K')\n if np.issubdtype(x.dtype, np.integer):\n warnings.warn('Array type is integer, np.dot may overflow. '\n 'Data should be float type to avoid this issue',\n UserWarning)\n return np.dot(x, x)\n\n\ndef row_norms(X, squared=False):\n \"\"\"Row-wise (squared) Euclidean norm of X.\n\n Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse\n matrices and does not create an X.shape-sized temporary.\n\n Performs no input validation.\n\n Parameters\n ----------\n X : array-like\n The input array.\n squared : bool, default=False\n If True, return squared norms.\n\n Returns\n -------\n array-like\n The row-wise (squared) Euclidean norm of X.\n \"\"\"\n if sparse.issparse(X):\n if not isinstance(X, sparse.csr_matrix):\n X = sparse.csr_matrix(X)\n norms = csr_row_norms(X)\n else:\n norms = np.einsum('ij,ij->i', X, X)\n\n if not squared:\n np.sqrt(norms, norms)\n return norms\n\n\ndef fast_logdet(A):\n \"\"\"Compute log(det(A)) for A symmetric.\n\n Equivalent to : np.log(nl.det(A)) but more robust.\n It returns -Inf if det(A) is non positive or is not defined.\n\n Parameters\n ----------\n A : array-like\n The matrix.\n \"\"\"\n sign, ld = np.linalg.slogdet(A)\n if not sign > 0:\n return -np.inf\n return ld\n\n\ndef density(w, **kwargs):\n \"\"\"Compute density of a sparse vector.\n\n Parameters\n ----------\n w : array-like\n The sparse vector.\n\n Returns\n -------\n float\n The density of w, between 0 and 1.\n \"\"\"\n if hasattr(w, \"toarray\"):\n d = float(w.nnz) / (w.shape[0] * w.shape[1])\n else:\n d = 0 if w is None else float((w != 0).sum()) / w.size\n return d\n\n\n@_deprecate_positional_args\ndef safe_sparse_dot(a, b, *, dense_output=False):\n \"\"\"Dot product that handle the sparse matrix case correctly.\n\n Parameters\n ----------\n a : {ndarray, sparse matrix}\n b : {ndarray, sparse matrix}\n dense_output : bool, default=False\n When False, ``a`` and ``b`` both being sparse will yield sparse output.\n When True, output will always be a dense array.\n\n Returns\n -------\n dot_product : {ndarray, sparse matrix}\n Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``.\n \"\"\"\n if a.ndim > 2 or b.ndim > 2:\n if sparse.issparse(a):\n # sparse is always 2D. Implies b is 3D+\n # [i, j] @ [k, ..., l, m, n] -> [i, k, ..., l, n]\n b_ = np.rollaxis(b, -2)\n b_2d = b_.reshape((b.shape[-2], -1))\n ret = a @ b_2d\n ret = ret.reshape(a.shape[0], *b_.shape[1:])\n elif sparse.issparse(b):\n # sparse is always 2D. Implies a is 3D+\n # [k, ..., l, m] @ [i, j] -> [k, ..., l, j]\n a_2d = a.reshape(-1, a.shape[-1])\n ret = a_2d @ b\n ret = ret.reshape(*a.shape[:-1], b.shape[1])\n else:\n ret = np.dot(a, b)\n else:\n ret = a @ b\n\n if (sparse.issparse(a) and sparse.issparse(b)\n and dense_output and hasattr(ret, \"toarray\")):\n return ret.toarray()\n return ret\n\n\n@_deprecate_positional_args\ndef randomized_range_finder(A, *, size, n_iter,\n power_iteration_normalizer='auto',\n random_state=None):\n \"\"\"Computes an orthonormal matrix whose range approximates the range of A.\n\n Parameters\n ----------\n A : 2D array\n The input data matrix.\n\n size : int\n Size of the return array.\n\n n_iter : int\n Number of power iterations used to stabilize the result.\n\n power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'\n Whether the power iterations are normalized with step-by-step\n QR factorization (the slowest but most accurate), 'none'\n (the fastest but numerically unstable when `n_iter` is large, e.g.\n typically 5 or larger), or 'LU' factorization (numerically stable\n but can lose slightly in accuracy). The 'auto' mode applies no\n normalization if `n_iter` <= 2 and switches to LU otherwise.\n\n .. versionadded:: 0.18\n\n random_state : int, RandomState instance or None, default=None\n The seed of the pseudo random number generator to use when shuffling\n the data, i.e. getting the random vectors to initialize the algorithm.\n Pass an int for reproducible results across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Returns\n -------\n Q : ndarray\n A (size x size) projection matrix, the range of which\n approximates well the range of the input matrix A.\n\n Notes\n -----\n\n Follows Algorithm 4.3 of\n Finding structure with randomness: Stochastic algorithms for constructing\n approximate matrix decompositions\n Halko, et al., 2009 (arXiv:909) https://arxiv.org/pdf/0909.4061.pdf\n\n An implementation of a randomized algorithm for principal component\n analysis\n A. Szlam et al. 2014\n \"\"\"\n random_state = check_random_state(random_state)\n\n # Generating normal random vectors with shape: (A.shape[1], size)\n Q = random_state.normal(size=(A.shape[1], size))\n if A.dtype.kind == 'f':\n # Ensure f32 is preserved as f32\n Q = Q.astype(A.dtype, copy=False)\n\n # Deal with \"auto\" mode\n if power_iteration_normalizer == 'auto':\n if n_iter <= 2:\n power_iteration_normalizer = 'none'\n else:\n power_iteration_normalizer = 'LU'\n\n # Perform power iterations with Q to further 'imprint' the top\n # singular vectors of A in Q\n for i in range(n_iter):\n if power_iteration_normalizer == 'none':\n Q = safe_sparse_dot(A, Q)\n Q = safe_sparse_dot(A.T, Q)\n elif power_iteration_normalizer == 'LU':\n Q, _ = linalg.lu(safe_sparse_dot(A, Q), permute_l=True)\n Q, _ = linalg.lu(safe_sparse_dot(A.T, Q), permute_l=True)\n elif power_iteration_normalizer == 'QR':\n Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')\n Q, _ = linalg.qr(safe_sparse_dot(A.T, Q), mode='economic')\n\n # Sample the range of A using by linear projection of Q\n # Extract an orthonormal basis\n Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')\n return Q\n\n\n@_deprecate_positional_args\ndef randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n power_iteration_normalizer='auto', transpose='auto',\n flip_sign=True, random_state=0):\n \"\"\"Computes a truncated randomized SVD.\n\n Parameters\n ----------\n M : {ndarray, sparse matrix}\n Matrix to decompose.\n\n n_components : int\n Number of singular values and vectors to extract.\n\n n_oversamples : int, default=10\n Additional number of random vectors to sample the range of M so as\n to ensure proper conditioning. The total number of random vectors\n used to find the range of M is n_components + n_oversamples. Smaller\n number can improve speed but can negatively impact the quality of\n approximation of singular vectors and singular values.\n\n n_iter : int or 'auto', default='auto'\n Number of power iterations. It can be used to deal with very noisy\n problems. When 'auto', it is set to 4, unless `n_components` is small\n (< .1 * min(X.shape)) `n_iter` in which case is set to 7.\n This improves precision with few components.\n\n .. versionchanged:: 0.18\n\n power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'\n Whether the power iterations are normalized with step-by-step\n QR factorization (the slowest but most accurate), 'none'\n (the fastest but numerically unstable when `n_iter` is large, e.g.\n typically 5 or larger), or 'LU' factorization (numerically stable\n but can lose slightly in accuracy). The 'auto' mode applies no\n normalization if `n_iter` <= 2 and switches to LU otherwise.\n\n .. versionadded:: 0.18\n\n transpose : bool or 'auto', default='auto'\n Whether the algorithm should be applied to M.T instead of M. The\n result should approximately be the same. The 'auto' mode will\n trigger the transposition if M.shape[1] > M.shape[0] since this\n implementation of randomized SVD tend to be a little faster in that\n case.\n\n .. versionchanged:: 0.18\n\n flip_sign : bool, default=True\n The output of a singular value decomposition is only unique up to a\n permutation of the signs of the singular vectors. If `flip_sign` is\n set to `True`, the sign ambiguity is resolved by making the largest\n loadings for each component in the left singular vectors positive.\n\n random_state : int, RandomState instance or None, default=None\n The seed of the pseudo random number generator to use when shuffling\n the data, i.e. getting the random vectors to initialize the algorithm.\n Pass an int for reproducible results across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Notes\n -----\n This algorithm finds a (usually very good) approximate truncated\n singular value decomposition using randomization to speed up the\n computations. It is particularly fast on large matrices on which\n you wish to extract only a small number of components. In order to\n obtain further speed up, `n_iter` can be set <=2 (at the cost of\n loss of precision).\n\n References\n ----------\n * Finding structure with randomness: Stochastic algorithms for constructing\n approximate matrix decompositions\n Halko, et al., 2009 https://arxiv.org/abs/0909.4061\n\n * A randomized algorithm for the decomposition of matrices\n Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert\n\n * An implementation of a randomized algorithm for principal component\n analysis\n A. Szlam et al. 2014\n \"\"\"\n if isinstance(M, (sparse.lil_matrix, sparse.dok_matrix)):\n warnings.warn(\"Calculating SVD of a {} is expensive. \"\n \"csr_matrix is more efficient.\".format(\n type(M).__name__),\n sparse.SparseEfficiencyWarning)\n\n random_state = check_random_state(random_state)\n n_random = n_components + n_oversamples\n n_samples, n_features = M.shape\n\n if n_iter == 'auto':\n # Checks if the number of iterations is explicitly specified\n # Adjust n_iter. 7 was found a good compromise for PCA. See #5299\n n_iter = 7 if n_components < .1 * min(M.shape) else 4\n\n if transpose == 'auto':\n transpose = n_samples < n_features\n if transpose:\n # this implementation is a bit faster with smaller shape[1]\n M = M.T\n\n Q = randomized_range_finder(\n M, size=n_random, n_iter=n_iter,\n power_iteration_normalizer=power_iteration_normalizer,\n random_state=random_state)\n\n # project M to the (k + p) dimensional space using the basis vectors\n B = safe_sparse_dot(Q.T, M)\n\n # compute the SVD on the thin matrix: (k + p) wide\n Uhat, s, Vt = linalg.svd(B, full_matrices=False)\n\n del B\n U = np.dot(Q, Uhat)\n\n if flip_sign:\n if not transpose:\n U, Vt = svd_flip(U, Vt)\n else:\n # In case of transpose u_based_decision=false\n # to actually flip based on u and not v.\n U, Vt = svd_flip(U, Vt, u_based_decision=False)\n\n if transpose:\n # transpose back the results according to the input convention\n return Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T\n else:\n return U[:, :n_components], s[:n_components], Vt[:n_components, :]\n\n\n@_deprecate_positional_args\ndef weighted_mode(a, w, *, axis=0):\n \"\"\"Returns an array of the weighted modal (most common) value in a.\n\n If there is more than one such value, only the first is returned.\n The bin-count for the modal bins is also returned.\n\n This is an extension of the algorithm in scipy.stats.mode.\n\n Parameters\n ----------\n a : array-like\n n-dimensional array of which to find mode(s).\n w : array-like\n n-dimensional array of weights for each value.\n axis : int, default=0\n Axis along which to operate. Default is 0, i.e. the first axis.\n\n Returns\n -------\n vals : ndarray\n Array of modal values.\n score : ndarray\n Array of weighted counts for each mode.\n\n Examples\n --------\n >>> from sklearn.utils.extmath import weighted_mode\n >>> x = [4, 1, 4, 2, 4, 2]\n >>> weights = [1, 1, 1, 1, 1, 1]\n >>> weighted_mode(x, weights)\n (array([4.]), array([3.]))\n\n The value 4 appears three times: with uniform weights, the result is\n simply the mode of the distribution.\n\n >>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's\n >>> weighted_mode(x, weights)\n (array([2.]), array([3.5]))\n\n The value 2 has the highest score: it appears twice with weights of\n 1.5 and 2: the sum of these is 3.5.\n\n See Also\n --------\n scipy.stats.mode\n \"\"\"\n if axis is None:\n a = np.ravel(a)\n w = np.ravel(w)\n axis = 0\n else:\n a = np.asarray(a)\n w = np.asarray(w)\n\n if a.shape != w.shape:\n w = np.full(a.shape, w, dtype=w.dtype)\n\n scores = np.unique(np.ravel(a)) # get ALL unique values\n testshape = list(a.shape)\n testshape[axis] = 1\n oldmostfreq = np.zeros(testshape)\n oldcounts = np.zeros(testshape)\n for score in scores:\n template = np.zeros(a.shape)\n ind = (a == score)\n template[ind] = w[ind]\n counts = np.expand_dims(np.sum(template, axis), axis)\n mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)\n oldcounts = np.maximum(counts, oldcounts)\n oldmostfreq = mostfrequent\n return mostfrequent, oldcounts\n\n\ndef cartesian(arrays, out=None):\n \"\"\"Generate a cartesian product of input arrays.\n\n Parameters\n ----------\n arrays : list of array-like\n 1-D arrays to form the cartesian product of.\n out : ndarray, default=None\n Array to place the cartesian product in.\n\n Returns\n -------\n out : ndarray\n 2-D array of shape (M, len(arrays)) containing cartesian products\n formed of input arrays.\n\n Examples\n --------\n >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))\n array([[1, 4, 6],\n [1, 4, 7],\n [1, 5, 6],\n [1, 5, 7],\n [2, 4, 6],\n [2, 4, 7],\n [2, 5, 6],\n [2, 5, 7],\n [3, 4, 6],\n [3, 4, 7],\n [3, 5, 6],\n [3, 5, 7]])\n\n Notes\n -----\n This function may not be used on more than 32 arrays\n because the underlying numpy functions do not support it.\n \"\"\"\n arrays = [np.asarray(x) for x in arrays]\n shape = (len(x) for x in arrays)\n dtype = arrays[0].dtype\n\n ix = np.indices(shape)\n ix = ix.reshape(len(arrays), -1).T\n\n if out is None:\n out = np.empty_like(ix, dtype=dtype)\n\n for n, arr in enumerate(arrays):\n out[:, n] = arrays[n][ix[:, n]]\n\n return out\n\n\ndef svd_flip(u, v, u_based_decision=True):\n \"\"\"Sign correction to ensure deterministic output from SVD.\n\n Adjusts the columns of u and the rows of v such that the loadings in the\n columns in u that are largest in absolute value are always positive.\n\n Parameters\n ----------\n u : ndarray\n u and v are the output of `linalg.svd` or\n :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner\n dimensions so one can compute `np.dot(u * s, v)`.\n\n v : ndarray\n u and v are the output of `linalg.svd` or\n :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner\n dimensions so one can compute `np.dot(u * s, v)`.\n The input v should really be called vt to be consistent with scipy's\n ouput.\n\n u_based_decision : bool, default=True\n If True, use the columns of u as the basis for sign flipping.\n Otherwise, use the rows of v. The choice of which variable to base the\n decision on is generally algorithm dependent.\n\n\n Returns\n -------\n u_adjusted, v_adjusted : arrays with the same dimensions as the input.\n\n \"\"\"\n if u_based_decision:\n # columns of u, rows of v\n max_abs_cols = np.argmax(np.abs(u), axis=0)\n signs = np.sign(u[max_abs_cols, range(u.shape[1])])\n u *= signs\n v *= signs[:, np.newaxis]\n else:\n # rows of v, columns of u\n max_abs_rows = np.argmax(np.abs(v), axis=1)\n signs = np.sign(v[range(v.shape[0]), max_abs_rows])\n u *= signs\n v *= signs[:, np.newaxis]\n return u, v\n\n\ndef log_logistic(X, out=None):\n \"\"\"Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``.\n\n This implementation is numerically stable because it splits positive and\n negative values::\n\n -log(1 + exp(-x_i)) if x_i > 0\n x_i - log(1 + exp(x_i)) if x_i <= 0\n\n For the ordinary logistic function, use ``scipy.special.expit``.\n\n Parameters\n ----------\n X : array-like of shape (M, N) or (M,)\n Argument to the logistic function.\n\n out : array-like of shape (M, N) or (M,), default=None\n Preallocated output array.\n\n Returns\n -------\n out : ndarray of shape (M, N) or (M,)\n Log of the logistic function evaluated at every point in x.\n\n Notes\n -----\n See the blog post describing this implementation:\n http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/\n \"\"\"\n is_1d = X.ndim == 1\n X = np.atleast_2d(X)\n X = check_array(X, dtype=np.float64)\n\n n_samples, n_features = X.shape\n\n if out is None:\n out = np.empty_like(X)\n\n _log_logistic_sigmoid(n_samples, n_features, X, out)\n\n if is_1d:\n return np.squeeze(out)\n return out\n\n\ndef softmax(X, copy=True):\n \"\"\"\n Calculate the softmax function.\n\n The softmax function is calculated by\n np.exp(X) / np.sum(np.exp(X), axis=1)\n\n This will cause overflow when large values are exponentiated.\n Hence the largest value in each row is subtracted from each data\n point to prevent this.\n\n Parameters\n ----------\n X : array-like of float of shape (M, N)\n Argument to the logistic function.\n\n copy : bool, default=True\n Copy X or not.\n\n Returns\n -------\n out : ndarray of shape (M, N)\n Softmax function evaluated at every point in x.\n \"\"\"\n if copy:\n X = np.copy(X)\n max_prob = np.max(X, axis=1).reshape((-1, 1))\n X -= max_prob\n np.exp(X, X)\n sum_prob = np.sum(X, axis=1).reshape((-1, 1))\n X /= sum_prob\n return X\n\n\ndef make_nonnegative(X, min_value=0):\n \"\"\"Ensure `X.min()` >= `min_value`.\n\n Parameters\n ----------\n X : array-like\n The matrix to make non-negative.\n min_value : float, default=0\n The threshold value.\n\n Returns\n -------\n array-like\n The thresholded array.\n\n Raises\n ------\n ValueError\n When X is sparse.\n \"\"\"\n min_ = X.min()\n if min_ < min_value:\n if sparse.issparse(X):\n raise ValueError(\"Cannot make the data matrix\"\n \" nonnegative because it is sparse.\"\n \" Adding a value to every entry would\"\n \" make it no longer sparse.\")\n X = X + (min_value - min_)\n return X\n\n\n# Use at least float64 for the accumulating functions to avoid precision issue\n# see https://github.com/numpy/numpy/issues/9393. The float64 is also retained\n# as it is in case the float overflows\ndef _safe_accumulator_op(op, x, *args, **kwargs):\n \"\"\"\n This function provides numpy accumulator functions with a float64 dtype\n when used on a floating point input. This prevents accumulator overflow on\n smaller floating point dtypes.\n\n Parameters\n ----------\n op : function\n A numpy accumulator function such as np.mean or np.sum.\n x : ndarray\n A numpy array to apply the accumulator function.\n *args : positional arguments\n Positional arguments passed to the accumulator function after the\n input x.\n **kwargs : keyword arguments\n Keyword arguments passed to the accumulator function.\n\n Returns\n -------\n result\n The output of the accumulator function passed to this function.\n \"\"\"\n if np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize < 8:\n result = op(x, *args, **kwargs, dtype=np.float64)\n else:\n result = op(x, *args, **kwargs)\n return result\n\n\ndef _incremental_weighted_mean_and_var(X, sample_weight,\n last_mean,\n last_variance,\n last_weight_sum):\n \"\"\"Calculate weighted mean and weighted variance incremental update.\n\n .. versionadded:: 0.24\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Data to use for mean and variance update.\n\n sample_weight : array-like of shape (n_samples,) or None\n Sample weights. If None, then samples are equally weighted.\n\n last_mean : array-like of shape (n_features,)\n Mean before the incremental update.\n\n last_variance : array-like of shape (n_features,) or None\n Variance before the incremental update.\n If None, variance update is not computed (in case scaling is not\n required).\n\n last_weight_sum : array-like of shape (n_features,)\n Sum of weights before the incremental update.\n\n Returns\n -------\n updated_mean : array of shape (n_features,)\n\n updated_variance : array of shape (n_features,) or None\n If None, only mean is computed.\n\n updated_weight_sum : array of shape (n_features,)\n\n Notes\n -----\n NaNs in `X` are ignored.\n\n `last_mean` and `last_variance` are statistics computed at the last step\n by the function. Both must be initialized to 0.0.\n The mean is always required (`last_mean`) and returned (`updated_mean`),\n whereas the variance can be None (`last_variance` and `updated_variance`).\n\n For further details on the algorithm to perform the computation in a\n numerically stable way, see [Finch2009]_, Sections 4 and 5.\n\n References\n ----------\n .. [Finch2009] `Tony Finch,\n \"Incremental calculation of weighted mean and variance\",\n University of Cambridge Computing Service, February 2009.\n <https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf>`_\n\n \"\"\"\n # last = stats before the increment\n # new = the current increment\n # updated = the aggregated stats\n if sample_weight is None:\n return _incremental_mean_and_var(X, last_mean, last_variance,\n last_weight_sum)\n nan_mask = np.isnan(X)\n sample_weight_T = np.reshape(sample_weight, (1, -1))\n # new_weight_sum with shape (n_features,)\n new_weight_sum = \\\n _safe_accumulator_op(np.dot, sample_weight_T, ~nan_mask).ravel()\n total_weight_sum = _safe_accumulator_op(np.sum, sample_weight, axis=0)\n\n X_0 = np.where(nan_mask, 0, X)\n new_mean = \\\n _safe_accumulator_op(np.average, X_0, weights=sample_weight, axis=0)\n new_mean *= total_weight_sum / new_weight_sum\n updated_weight_sum = last_weight_sum + new_weight_sum\n updated_mean = (\n (last_weight_sum * last_mean + new_weight_sum * new_mean)\n / updated_weight_sum)\n\n if last_variance is None:\n updated_variance = None\n else:\n X_0 = np.where(nan_mask, 0, (X-new_mean)**2)\n new_variance =\\\n _safe_accumulator_op(\n np.average, X_0, weights=sample_weight, axis=0)\n new_variance *= total_weight_sum / new_weight_sum\n new_term = (\n new_weight_sum *\n (new_variance +\n (new_mean - updated_mean) ** 2))\n last_term = (\n last_weight_sum *\n (last_variance +\n (last_mean - updated_mean) ** 2))\n updated_variance = (new_term + last_term) / updated_weight_sum\n\n return updated_mean, updated_variance, updated_weight_sum\n\n\ndef _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count):\n \"\"\"Calculate mean update and a Youngs and Cramer variance update.\n\n last_mean and last_variance are statistics computed at the last step by the\n function. Both must be initialized to 0.0. In case no scaling is required\n last_variance can be None. The mean is always required and returned because\n necessary for the calculation of the variance. last_n_samples_seen is the\n number of samples encountered until now.\n\n From the paper \"Algorithms for computing the sample variance: analysis and\n recommendations\", by Chan, Golub, and LeVeque.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Data to use for variance update.\n\n last_mean : array-like of shape (n_features,)\n\n last_variance : array-like of shape (n_features,)\n\n last_sample_count : array-like of shape (n_features,)\n\n Returns\n -------\n updated_mean : ndarray of shape (n_features,)\n\n updated_variance : ndarray of shape (n_features,)\n If None, only mean is computed.\n\n updated_sample_count : ndarray of shape (n_features,)\n\n Notes\n -----\n NaNs are ignored during the algorithm.\n\n References\n ----------\n T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample\n variance: recommendations, The American Statistician, Vol. 37, No. 3,\n pp. 242-247\n\n Also, see the sparse implementation of this in\n `utils.sparsefuncs.incr_mean_variance_axis` and\n `utils.sparsefuncs_fast.incr_mean_variance_axis0`\n \"\"\"\n # old = stats until now\n # new = the current increment\n # updated = the aggregated stats\n last_sum = last_mean * last_sample_count\n new_sum = _safe_accumulator_op(np.nansum, X, axis=0)\n\n new_sample_count = np.sum(~np.isnan(X), axis=0)\n updated_sample_count = last_sample_count + new_sample_count\n\n updated_mean = (last_sum + new_sum) / updated_sample_count\n\n if last_variance is None:\n updated_variance = None\n else:\n new_unnormalized_variance = (\n _safe_accumulator_op(np.nanvar, X, axis=0) * new_sample_count)\n last_unnormalized_variance = last_variance * last_sample_count\n\n with np.errstate(divide='ignore', invalid='ignore'):\n last_over_new_count = last_sample_count / new_sample_count\n updated_unnormalized_variance = (\n last_unnormalized_variance + new_unnormalized_variance +\n last_over_new_count / updated_sample_count *\n (last_sum / last_over_new_count - new_sum) ** 2)\n\n zeros = last_sample_count == 0\n updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]\n updated_variance = updated_unnormalized_variance / updated_sample_count\n\n return updated_mean, updated_variance, updated_sample_count\n\n\ndef _deterministic_vector_sign_flip(u):\n \"\"\"Modify the sign of vectors for reproducibility.\n\n Flips the sign of elements of all the vectors (rows of u) such that\n the absolute maximum element of each vector is positive.\n\n Parameters\n ----------\n u : ndarray\n Array with vectors as its rows.\n\n Returns\n -------\n u_flipped : ndarray with same shape as u\n Array with the sign flipped vectors as its rows.\n \"\"\"\n max_abs_rows = np.argmax(np.abs(u), axis=1)\n signs = np.sign(u[range(u.shape[0]), max_abs_rows])\n u *= signs[:, np.newaxis]\n return u\n\n\ndef stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):\n \"\"\"Use high precision for cumsum and check that final value matches sum.\n\n Parameters\n ----------\n arr : array-like\n To be cumulatively summed as flat.\n axis : int, default=None\n Axis along which the cumulative sum is computed.\n The default (None) is to compute the cumsum over the flattened array.\n rtol : float, default=1e-05\n Relative tolerance, see ``np.allclose``.\n atol : float, default=1e-08\n Absolute tolerance, see ``np.allclose``.\n \"\"\"\n out = np.cumsum(arr, axis=axis, dtype=np.float64)\n expected = np.sum(arr, axis=axis, dtype=np.float64)\n if not np.all(np.isclose(out.take(-1, axis=axis), expected, rtol=rtol,\n atol=atol, equal_nan=True)):\n warnings.warn('cumsum was found to be unstable: '\n 'its last element does not correspond to sum',\n RuntimeWarning)\n return out\n"
]
| [
[
"numpy.dot",
"numpy.copy",
"scipy.linalg.svd",
"numpy.rollaxis",
"numpy.exp",
"numpy.where",
"numpy.cumsum",
"numpy.issubdtype",
"numpy.max",
"numpy.full",
"numpy.sqrt",
"scipy.sparse.csr_matrix",
"numpy.empty_like",
"numpy.atleast_2d",
"scipy.sparse.issparse",
"numpy.reshape",
"numpy.zeros",
"numpy.einsum",
"numpy.squeeze",
"numpy.linalg.slogdet",
"numpy.isnan",
"numpy.asarray",
"numpy.errstate",
"numpy.sum",
"numpy.ravel",
"numpy.abs",
"numpy.indices",
"numpy.maximum"
]
]
|
Carlitosh/PyKrige | [
"8d837ac60a03ecdc28ee034384c429c32c4c28f8"
]
| [
"pykrige/ok3d.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n__doc__ = \"\"\"\nPyKrige\n=======\n\nCode by Benjamin S. Murphy and the PyKrige Developers\[email protected]\n\nSummary\n-------\nContains class OrdinaryKriging3D.\n\nReferences\n----------\n.. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in\n Hydrogeology, (Cambridge University Press, 1997) 272 p.\n\nCopyright (c) 2015-2018, PyKrige Developers\n\"\"\"\n\nimport numpy as np\nimport scipy.linalg\nfrom scipy.spatial.distance import cdist\nimport matplotlib.pyplot as plt\nfrom . import variogram_models\nfrom . import core\nfrom .core import _adjust_for_anisotropy, _initialize_variogram_model, \\\n _make_variogram_parameter_list, _find_statistics\nimport warnings\n\n\nclass OrdinaryKriging3D:\n \"\"\"Three-dimensional ordinary kriging\n\n Parameters\n ----------\n x : array_like\n X-coordinates of data points.\n y : array_like\n Y-coordinates of data points.\n z : array_like\n Z-coordinates of data points.\n val : array_like\n Values at data points.\n variogram_model : str or GSTools CovModel, optional\n Specified which variogram model to use; may be one of the following:\n linear, power, gaussian, spherical, exponential, hole-effect.\n Default is linear variogram model. To utilize a custom variogram model,\n specify 'custom'; you must also provide variogram_parameters and\n variogram_function. Note that the hole-effect model is only technically\n correct for one-dimensional problems.\n You can also use a\n `GSTools <https://github.com/GeoStat-Framework/GSTools>`_ CovModel.\n variogram_parameters : list or dict, optional\n Parameters that define the specified variogram model. If not provided,\n parameters will be automatically calculated using a \"soft\" L1 norm\n minimization scheme. For variogram model parameters provided in a dict,\n the required dict keys vary according to the specified variogram\n model: ::\n linear - {'slope': slope, 'nugget': nugget}\n power - {'scale': scale, 'exponent': exponent, 'nugget': nugget}\n gaussian - {'sill': s, 'range': r, 'nugget': n}\n OR\n {'psill': p, 'range': r, 'nugget':n}\n spherical - {'sill': s, 'range': r, 'nugget': n}\n OR\n {'psill': p, 'range': r, 'nugget':n}\n exponential - {'sill': s, 'range': r, 'nugget': n}\n OR\n {'psill': p, 'range': r, 'nugget':n}\n hole-effect - {'sill': s, 'range': r, 'nugget': n}\n OR\n {'psill': p, 'range': r, 'nugget':n}\n Note that either the full sill or the partial sill\n (psill = sill - nugget) can be specified in the dict.\n For variogram model parameters provided in a list, the entries\n must be as follows: ::\n linear - [slope, nugget]\n power - [scale, exponent, nugget]\n gaussian - [sill, range, nugget]\n spherical - [sill, range, nugget]\n exponential - [sill, range, nugget]\n hole-effect - [sill, range, nugget]\n Note that the full sill (NOT the partial sill) must be specified\n in the list format.\n For a custom variogram model, the parameters are required, as custom\n variogram models will not automatically be fit to the data.\n Furthermore, the parameters must be specified in list format, in the\n order in which they are used in the callable function (see\n variogram_function for more information). The code does not check\n that the provided list contains the appropriate number of parameters\n for the custom variogram model, so an incorrect parameter list in\n such a case will probably trigger an esoteric exception someplace\n deep in the code.\n NOTE that, while the list format expects the full sill, the code\n itself works internally with the partial sill.\n variogram_function : callable, optional\n A callable function that must be provided if variogram_model is\n specified as 'custom'. The function must take only two arguments:\n first, a list of parameters for the variogram model;\n second, the distances at which to calculate the variogram model.\n The list provided in variogram_parameters will be passed to the\n function as the first argument.\n nlags : int, optional\n Number of averaging bins for the semivariogram. Default is 6.\n weight : boolean, optional\n Flag that specifies if semivariance at smaller lags should be weighted\n more heavily when automatically calculating variogram model.\n The routine is currently hard-coded such that the weights are\n calculated from a logistic function, so weights at small lags are ~1\n and weights at the longest lags are ~0; the center of the logistic\n weighting is hard-coded to be at 70% of the distance from the shortest\n lag to the largest lag. Setting this parameter to True indicates that\n weights will be applied. Default is False.\n (Kitanidis suggests that the values at smaller lags are more\n important in fitting a variogram model, so the option is provided\n to enable such weighting.)\n anisotropy_scaling_y : float, optional\n Scalar stretching value to take into account anisotropy\n in the y direction. Default is 1 (effectively no stretching).\n Scaling is applied in the y direction in the rotated data frame\n (i.e., after adjusting for the anisotropy_angle_x/y/z,\n if anisotropy_angle_x/y/z is/are not 0).\n anisotropy_scaling_z : float, optional\n Scalar stretching value to take into account anisotropy\n in the z direction. Default is 1 (effectively no stretching).\n Scaling is applied in the z direction in the rotated data frame\n (i.e., after adjusting for the anisotropy_angle_x/y/z,\n if anisotropy_angle_x/y/z is/are not 0).\n anisotropy_angle_x : float, optional\n CCW angle (in degrees) by which to rotate coordinate system about\n the x axis in order to take into account anisotropy.\n Default is 0 (no rotation). Note that the coordinate system is rotated.\n X rotation is applied first, then y rotation, then z rotation.\n Scaling is applied after rotation.\n anisotropy_angle_y : float, optional\n CCW angle (in degrees) by which to rotate coordinate system about\n the y axis in order to take into account anisotropy.\n Default is 0 (no rotation). Note that the coordinate system is rotated.\n X rotation is applied first, then y rotation, then z rotation.\n Scaling is applied after rotation.\n anisotropy_angle_z : float, optional\n CCW angle (in degrees) by which to rotate coordinate system about\n the z axis in order to take into account anisotropy.\n Default is 0 (no rotation). Note that the coordinate system is rotated.\n X rotation is applied first, then y rotation, then z rotation.\n Scaling is applied after rotation.\n verbose : bool, optional\n Enables program text output to monitor kriging process.\n Default is False (off).\n enable_plotting : bool, optional\n Enables plotting to display variogram. Default is False (off).\n\n References\n ----------\n .. [1] P.K. Kitanidis, Introduction to Geostatistcs: Applications in\n Hydrogeology, (Cambridge University Press, 1997) 272 p.\n \"\"\"\n\n eps = 1.e-10 # Cutoff for comparison to zero\n variogram_dict = {'linear': variogram_models.linear_variogram_model,\n 'power': variogram_models.power_variogram_model,\n 'gaussian': variogram_models.gaussian_variogram_model,\n 'spherical': variogram_models.spherical_variogram_model,\n 'exponential': variogram_models.exponential_variogram_model,\n 'hole-effect': variogram_models.hole_effect_variogram_model}\n\n def __init__(self, x, y, z, val, variogram_model='linear',\n variogram_parameters=None, variogram_function=None, nlags=6,\n weight=False, anisotropy_scaling_y=1., anisotropy_scaling_z=1.,\n anisotropy_angle_x=0., anisotropy_angle_y=0.,\n anisotropy_angle_z=0., verbose=False, enable_plotting=False):\n\n # set up variogram model and parameters...\n self.variogram_model = variogram_model\n self.model = None\n # check if a GSTools covariance model is given\n if hasattr(self.variogram_model, \"pykrige_kwargs\"):\n # save the model in the class\n self.model = self.variogram_model\n if self.model.dim < 3:\n raise ValueError(\"GSTools: model dim is not 3\")\n self.variogram_model = \"custom\"\n variogram_function = self.model.pykrige_vario\n variogram_parameters = []\n anisotropy_scaling_y = self.model.pykrige_anis_y\n anisotropy_scaling_z = self.model.pykrige_anis_z\n anisotropy_angle_x = self.model.pykrige_angle_x\n anisotropy_angle_y = self.model.pykrige_angle_y\n anisotropy_angle_z = self.model.pykrige_angle_z\n if self.variogram_model not in self.variogram_dict.keys() and \\\n self.variogram_model != 'custom':\n raise ValueError(\"Specified variogram model '%s' \"\n \"is not supported.\" % variogram_model)\n elif self.variogram_model == 'custom':\n if variogram_function is None or not callable(variogram_function):\n raise ValueError(\"Must specify callable function for \"\n \"custom variogram model.\")\n else:\n self.variogram_function = variogram_function\n else:\n self.variogram_function = self.variogram_dict[self.variogram_model]\n\n # Code assumes 1D input arrays. Ensures that any extraneous dimensions\n # don't get in the way. Copies are created to avoid any problems with\n # referencing the original passed arguments.\n self.X_ORIG = \\\n np.atleast_1d(np.squeeze(np.array(x, copy=True, dtype=np.float64)))\n self.Y_ORIG = \\\n np.atleast_1d(np.squeeze(np.array(y, copy=True, dtype=np.float64)))\n self.Z_ORIG = \\\n np.atleast_1d(np.squeeze(np.array(z, copy=True, dtype=np.float64)))\n self.VALUES = \\\n np.atleast_1d(np.squeeze(np.array(val, copy=True, dtype=np.float64)))\n\n self.verbose = verbose\n self.enable_plotting = enable_plotting\n if self.enable_plotting and self.verbose:\n print(\"Plotting Enabled\\n\")\n\n self.XCENTER = (np.amax(self.X_ORIG) + np.amin(self.X_ORIG))/2.0\n self.YCENTER = (np.amax(self.Y_ORIG) + np.amin(self.Y_ORIG))/2.0\n self.ZCENTER = (np.amax(self.Z_ORIG) + np.amin(self.Z_ORIG))/2.0\n self.anisotropy_scaling_y = anisotropy_scaling_y\n self.anisotropy_scaling_z = anisotropy_scaling_z\n self.anisotropy_angle_x = anisotropy_angle_x\n self.anisotropy_angle_y = anisotropy_angle_y\n self.anisotropy_angle_z = anisotropy_angle_z\n if self.verbose:\n print(\"Adjusting data for anisotropy...\")\n self.X_ADJUSTED, self.Y_ADJUSTED, self.Z_ADJUSTED = \\\n _adjust_for_anisotropy(np.vstack((self.X_ORIG, self.Y_ORIG, self.Z_ORIG)).T,\n [self.XCENTER, self.YCENTER, self.ZCENTER],\n [self.anisotropy_scaling_y, self.anisotropy_scaling_z],\n [self.anisotropy_angle_x, self.anisotropy_angle_y, self.anisotropy_angle_z]).T\n\n if self.verbose:\n print(\"Initializing variogram model...\")\n\n vp_temp = _make_variogram_parameter_list(self.variogram_model,\n variogram_parameters)\n self.lags, self.semivariance, self.variogram_model_parameters = \\\n _initialize_variogram_model(np.vstack((self.X_ADJUSTED,\n self.Y_ADJUSTED,\n self.Z_ADJUSTED)).T,\n self.VALUES, self.variogram_model,\n vp_temp, self.variogram_function,\n nlags, weight, 'euclidean')\n\n if self.verbose:\n if self.variogram_model == 'linear':\n print(\"Using '%s' Variogram Model\" % 'linear')\n print(\"Slope:\", self.variogram_model_parameters[0])\n print(\"Nugget:\", self.variogram_model_parameters[1], '\\n')\n elif self.variogram_model == 'power':\n print(\"Using '%s' Variogram Model\" % 'power')\n print(\"Scale:\", self.variogram_model_parameters[0])\n print(\"Exponent:\", self.variogram_model_parameters[1])\n print(\"Nugget:\", self.variogram_model_parameters[2], '\\n')\n elif self.variogram_model == 'custom':\n print(\"Using Custom Variogram Model\")\n else:\n print(\"Using '%s' Variogram Model\" % self.variogram_model)\n print(\"Partial Sill:\", self.variogram_model_parameters[0])\n print(\"Full Sill:\", self.variogram_model_parameters[0] +\n self.variogram_model_parameters[2])\n print(\"Range:\", self.variogram_model_parameters[1])\n print(\"Nugget:\", self.variogram_model_parameters[2], '\\n')\n if self.enable_plotting:\n self.display_variogram_model()\n\n if self.verbose:\n print(\"Calculating statistics on variogram model fit...\")\n self.delta, self.sigma, self.epsilon = \\\n _find_statistics(np.vstack((self.X_ADJUSTED,\n self.Y_ADJUSTED,\n self.Z_ADJUSTED)).T,\n self.VALUES, self.variogram_function,\n self.variogram_model_parameters, 'euclidean')\n self.Q1 = core.calcQ1(self.epsilon)\n self.Q2 = core.calcQ2(self.epsilon)\n self.cR = core.calc_cR(self.Q2, self.sigma)\n if self.verbose:\n print(\"Q1 =\", self.Q1)\n print(\"Q2 =\", self.Q2)\n print(\"cR =\", self.cR, '\\n')\n\n def update_variogram_model(self, variogram_model, variogram_parameters=None,\n variogram_function=None, nlags=6, weight=False,\n anisotropy_scaling_y=1., anisotropy_scaling_z=1.,\n anisotropy_angle_x=0., anisotropy_angle_y=0.,\n anisotropy_angle_z=0.):\n \"\"\"Changes the variogram model and variogram parameters for\n the kriging system.\n\n Parameters\n ----------\n variogram_model : str or GSTools CovModel\n May be any of the variogram models listed above.\n May also be 'custom', in which case variogram_parameters and\n variogram_function must be specified.\n You can also use a\n `GSTools <https://github.com/GeoStat-Framework/GSTools>`_ CovModel.\n variogram_parameters : list or dict, optional\n List or dict of variogram model parameters, as explained above.\n If not provided, a best fit model will be calculated as\n described above.\n variogram_function : callable, optional\n A callable function that must be provided if variogram_model is\n specified as 'custom'. See above for more information.\n nlags : int, optional\n Number of averaging bins for the semivariogram. Default is 6.\n weight : bool, optional\n Flag that specifies if semivariance at smaller lags should be\n weighted more heavily when automatically calculating\n variogram model. See above for more information. True indicates\n that weights will be applied. Default is False.\n anisotropy_scaling_y : float, optional\n Scalar stretching value to take into account anisotropy\n in y-direction. Default is 1 (effectively no stretching).\n See above for more information.\n anisotropy_scaling_z : float, optional\n Scalar stretching value to take into account anisotropy\n in z-direction. Default is 1 (effectively no stretching).\n See above for more information.\n anisotropy_angle_x : float, optional\n Angle (in degrees) by which to rotate coordinate system about\n the x axis in order to take into account anisotropy.\n Default is 0 (no rotation). See above for more information.\n anisotropy_angle_y : float, optional\n Angle (in degrees) by which to rotate coordinate system about\n the y axis in order to take into account anisotropy.\n Default is 0 (no rotation). See above for more information.\n anisotropy_angle_z : float, optional\n Angle (in degrees) by which to rotate coordinate system about\n the z axis in order to take into account anisotropy.\n Default is 0 (no rotation). See above for more information.\n \"\"\"\n\n # set up variogram model and parameters...\n self.variogram_model = variogram_model\n self.model = None\n # check if a GSTools covariance model is given\n if hasattr(self.variogram_model, \"pykrige_kwargs\"):\n # save the model in the class\n self.model = self.variogram_model\n if self.model.dim < 3:\n raise ValueError(\"GSTools: model dim is not 3\")\n self.variogram_model = \"custom\"\n variogram_function = self.model.pykrige_vario\n variogram_parameters = []\n anisotropy_scaling_y = self.model.pykrige_anis_y\n anisotropy_scaling_z = self.model.pykrige_anis_z\n anisotropy_angle_x = self.model.pykrige_angle_x\n anisotropy_angle_y = self.model.pykrige_angle_y\n anisotropy_angle_z = self.model.pykrige_angle_z\n if self.variogram_model not in self.variogram_dict.keys() and \\\n self.variogram_model != 'custom':\n raise ValueError(\"Specified variogram model '%s' \"\n \"is not supported.\" % variogram_model)\n elif self.variogram_model == 'custom':\n if variogram_function is None or not callable(variogram_function):\n raise ValueError(\"Must specify callable function for \"\n \"custom variogram model.\")\n else:\n self.variogram_function = variogram_function\n else:\n self.variogram_function = self.variogram_dict[self.variogram_model]\n\n if anisotropy_scaling_y != self.anisotropy_scaling_y or anisotropy_scaling_z != self.anisotropy_scaling_z or \\\n anisotropy_angle_x != self.anisotropy_angle_x or anisotropy_angle_y != self.anisotropy_angle_y or \\\n anisotropy_angle_z != self.anisotropy_angle_z:\n if self.verbose:\n print(\"Adjusting data for anisotropy...\")\n self.anisotropy_scaling_y = anisotropy_scaling_y\n self.anisotropy_scaling_z = anisotropy_scaling_z\n self.anisotropy_angle_x = anisotropy_angle_x\n self.anisotropy_angle_y = anisotropy_angle_y\n self.anisotropy_angle_z = anisotropy_angle_z\n self.X_ADJUSTED, self.Y_ADJUSTED, self.Z_ADJUSTED = \\\n _adjust_for_anisotropy(np.vstack((self.X_ORIG, self.Y_ORIG, self.Z_ORIG)).T,\n [self.XCENTER, self.YCENTER, self.ZCENTER],\n [self.anisotropy_scaling_y, self.anisotropy_scaling_z],\n [self.anisotropy_angle_x, self.anisotropy_angle_y, self.anisotropy_angle_z]).T\n\n if self.verbose:\n print(\"Updating variogram mode...\")\n\n vp_temp = _make_variogram_parameter_list(self.variogram_model,\n variogram_parameters)\n self.lags, self.semivariance, self.variogram_model_parameters = \\\n _initialize_variogram_model(np.vstack((self.X_ADJUSTED,\n self.Y_ADJUSTED,\n self.Z_ADJUSTED)).T,\n self.VALUES, self.variogram_model,\n vp_temp, self.variogram_function,\n nlags, weight, 'euclidean')\n\n if self.verbose:\n if self.variogram_model == 'linear':\n print(\"Using '%s' Variogram Model\" % 'linear')\n print(\"Slope:\", self.variogram_model_parameters[0])\n print(\"Nugget:\", self.variogram_model_parameters[1], '\\n')\n elif self.variogram_model == 'power':\n print(\"Using '%s' Variogram Model\" % 'power')\n print(\"Scale:\", self.variogram_model_parameters[0])\n print(\"Exponent:\", self.variogram_model_parameters[1])\n print(\"Nugget:\", self.variogram_model_parameters[2], '\\n')\n elif self.variogram_model == 'custom':\n print(\"Using Custom Variogram Model\")\n else:\n print(\"Using '%s' Variogram Model\" % self.variogram_model)\n print(\"Partial Sill:\", self.variogram_model_parameters[0])\n print(\"Full Sill:\", self.variogram_model_parameters[0] +\n self.variogram_model_parameters[2])\n print(\"Range:\", self.variogram_model_parameters[1])\n print(\"Nugget:\", self.variogram_model_parameters[2], '\\n')\n if self.enable_plotting:\n self.display_variogram_model()\n\n if self.verbose:\n print(\"Calculating statistics on variogram model fit...\")\n self.delta, self.sigma, self.epsilon = \\\n _find_statistics(np.vstack((self.X_ADJUSTED,\n self.Y_ADJUSTED,\n self.Z_ADJUSTED)).T,\n self.VALUES, self.variogram_function,\n self.variogram_model_parameters, 'euclidean')\n self.Q1 = core.calcQ1(self.epsilon)\n self.Q2 = core.calcQ2(self.epsilon)\n self.cR = core.calc_cR(self.Q2, self.sigma)\n if self.verbose:\n print(\"Q1 =\", self.Q1)\n print(\"Q2 =\", self.Q2)\n print(\"cR =\", self.cR, '\\n')\n\n def display_variogram_model(self):\n \"\"\"Displays variogram model with the actual binned data.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(self.lags, self.semivariance, 'r*')\n ax.plot(self.lags,\n self.variogram_function(self.variogram_model_parameters,\n self.lags), 'k-')\n plt.show()\n\n def switch_verbose(self):\n \"\"\"Allows user to switch code talk-back on/off. Takes no arguments.\"\"\"\n self.verbose = not self.verbose\n\n def switch_plotting(self):\n \"\"\"Allows user to switch plot display on/off. Takes no arguments.\"\"\"\n self.enable_plotting = not self.enable_plotting\n\n def get_epsilon_residuals(self):\n \"\"\"Returns the epsilon residuals for the variogram fit.\"\"\"\n return self.epsilon\n\n def plot_epsilon_residuals(self):\n \"\"\"Plots the epsilon residuals for the variogram fit.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(range(self.epsilon.size), self.epsilon, c='k', marker='*')\n ax.axhline(y=0.0)\n plt.show()\n\n def get_statistics(self):\n \"\"\"Returns the Q1, Q2, and cR statistics for the\n variogram fit (in that order). No arguments.\n \"\"\"\n return self.Q1, self.Q2, self.cR\n\n def print_statistics(self):\n \"\"\"Prints out the Q1, Q2, and cR statistics for the variogram fit.\n NOTE that ideally Q1 is close to zero, Q2 is close to 1,\n and cR is as small as possible.\n \"\"\"\n print(\"Q1 =\", self.Q1)\n print(\"Q2 =\", self.Q2)\n print(\"cR =\", self.cR)\n\n def _get_kriging_matrix(self, n):\n \"\"\"Assembles the kriging matrix.\"\"\"\n\n xyz = np.concatenate((self.X_ADJUSTED[:, np.newaxis],\n self.Y_ADJUSTED[:, np.newaxis],\n self.Z_ADJUSTED[:, np.newaxis]), axis=1)\n d = cdist(xyz, xyz, 'euclidean')\n a = np.zeros((n+1, n+1))\n a[:n, :n] = - self.variogram_function(self.variogram_model_parameters, d)\n np.fill_diagonal(a, 0.)\n a[n, :] = 1.0\n a[:, n] = 1.0\n a[n, n] = 0.0\n\n return a\n\n def _exec_vector(self, a, bd, mask):\n \"\"\"Solves the kriging system as a vectorized operation. This method\n can take a lot of memory for large grids and/or large datasets.\"\"\"\n\n npt = bd.shape[0]\n n = self.X_ADJUSTED.shape[0]\n zero_index = None\n zero_value = False\n\n a_inv = scipy.linalg.inv(a)\n\n if np.any(np.absolute(bd) <= self.eps):\n zero_value = True\n zero_index = np.where(np.absolute(bd) <= self.eps)\n\n b = np.zeros((npt, n+1, 1))\n b[:, :n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)\n if zero_value:\n b[zero_index[0], zero_index[1], 0] = 0.0\n b[:, n, 0] = 1.0\n\n if (~mask).any():\n mask_b = np.repeat(mask[:, np.newaxis, np.newaxis], n+1, axis=1)\n b = np.ma.array(b, mask=mask_b)\n\n x = np.dot(a_inv, b.reshape((npt, n+1)).T).reshape((1, n+1, npt)).T\n kvalues = np.sum(x[:, :n, 0] * self.VALUES, axis=1)\n sigmasq = np.sum(x[:, :, 0] * -b[:, :, 0], axis=1)\n\n return kvalues, sigmasq\n\n def _exec_loop(self, a, bd_all, mask):\n \"\"\"Solves the kriging system by looping over all specified points.\n Less memory-intensive, but involves a Python-level loop.\"\"\"\n\n npt = bd_all.shape[0]\n n = self.X_ADJUSTED.shape[0]\n kvalues = np.zeros(npt)\n sigmasq = np.zeros(npt)\n\n a_inv = scipy.linalg.inv(a)\n\n for j in np.nonzero(~mask)[0]: # Note that this is the same thing as range(npt) if mask is not defined,\n bd = bd_all[j] # otherwise it takes the non-masked elements.\n if np.any(np.absolute(bd) <= self.eps):\n zero_value = True\n zero_index = np.where(np.absolute(bd) <= self.eps)\n else:\n zero_value = False\n zero_index = None\n\n b = np.zeros((n+1, 1))\n b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)\n if zero_value:\n b[zero_index[0], 0] = 0.0\n b[n, 0] = 1.0\n\n x = np.dot(a_inv, b)\n kvalues[j] = np.sum(x[:n, 0] * self.VALUES)\n sigmasq[j] = np.sum(x[:, 0] * -b[:, 0])\n\n return kvalues, sigmasq\n\n def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx):\n \"\"\"Solves the kriging system by looping over all specified points.\n Uses only a certain number of closest points. Not very memory intensive,\n but the loop is done in pure Python.\n \"\"\"\n import scipy.linalg.lapack\n\n npt = bd_all.shape[0]\n n = bd_idx.shape[1]\n kvalues = np.zeros(npt)\n sigmasq = np.zeros(npt)\n\n for i in np.nonzero(~mask)[0]:\n b_selector = bd_idx[i]\n bd = bd_all[i]\n\n a_selector = np.concatenate((b_selector, np.array([a_all.shape[0] - 1])))\n a = a_all[a_selector[:, None], a_selector]\n\n if np.any(np.absolute(bd) <= self.eps):\n zero_value = True\n zero_index = np.where(np.absolute(bd) <= self.eps)\n else:\n zero_value = False\n zero_index = None\n b = np.zeros((n+1, 1))\n b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd)\n if zero_value:\n b[zero_index[0], 0] = 0.0\n b[n, 0] = 1.0\n\n x = scipy.linalg.solve(a, b)\n\n kvalues[i] = x[:n, 0].dot(self.VALUES[b_selector])\n sigmasq[i] = - x[:, 0].dot(b[:, 0])\n\n return kvalues, sigmasq\n\n def execute(self, style, xpoints, ypoints, zpoints, mask=None,\n backend='vectorized', n_closest_points=None):\n \"\"\"Calculates a kriged grid and the associated variance.\n\n This is now the method that performs the main kriging calculation.\n Note that currently measurements (i.e., z values) are\n considered 'exact'. This means that, when a specified coordinate\n for interpolation is exactly the same as one of the data points,\n the variogram evaluated at the point is forced to be zero.\n Also, the diagonal of the kriging matrix is also always forced\n to be zero. In forcing the variogram evaluated at data points\n to be zero, we are effectively saying that there is no variance\n at that point (no uncertainty, so the value is 'exact').\n\n In the future, the code may include an extra 'exact_values' boolean\n flag that can be adjusted to specify whether to treat the\n measurements as 'exact'. Setting the flag to false would indicate\n that the variogram should not be forced to be zero at zero distance\n (i.e., when evaluated at data points). Instead, the uncertainty in the\n point will be equal to the nugget. This would mean that the diagonal\n of the kriging matrix would be set to the nugget instead of to zero.\n\n Parameters\n ----------\n style : str\n Specifies how to treat input kriging points.\n Specifying 'grid' treats xpoints, ypoints, and zpoints as arrays of\n x, y, and z coordinates that define a rectangular grid.\n Specifying 'points' treats xpoints, ypoints, and zpoints as arrays\n that provide coordinates at which to solve the kriging system.\n Specifying 'masked' treats xpoints, ypoints, and zpoints as arrays\n of x, y, and z coordinates that define a rectangular grid and uses\n mask to only evaluate specific points in the grid.\n xpoints : array_like, shape (N,) or (N, 1)\n If style is specific as 'grid' or 'masked', x-coordinates of\n LxMxN grid. If style is specified as 'points', x-coordinates of\n specific points at which to solve kriging system.\n ypoints : array-like, shape (M,) or (M, 1)\n If style is specified as 'grid' or 'masked', y-coordinates of\n LxMxN grid. If style is specified as 'points', y-coordinates of\n specific points at which to solve kriging system.\n Note that in this case, xpoints, ypoints, and zpoints must have the\n same dimensions (i.e., L = M = N).\n zpoints : array-like, shape (L,) or (L, 1)\n If style is specified as 'grid' or 'masked', z-coordinates of\n LxMxN grid. If style is specified as 'points', z-coordinates of\n specific points at which to solve kriging system.\n Note that in this case, xpoints, ypoints, and zpoints must have the\n same dimensions (i.e., L = M = N).\n mask : boolean array, shape (L, M, N), optional\n Specifies the points in the rectangular grid defined by xpoints,\n ypoints, zpoints that are to be excluded in the\n kriging calculations. Must be provided if style is specified\n as 'masked'. False indicates that the point should not be masked,\n so the kriging system will be solved at the point.\n True indicates that the point should be masked, so the kriging\n system should will not be solved at the point.\n backend : str, optional\n Specifies which approach to use in kriging. Specifying 'vectorized'\n will solve the entire kriging problem at once in a\n vectorized operation. This approach is faster but also can consume a\n significant amount of memory for large grids and/or large datasets.\n Specifying 'loop' will loop through each point at which the kriging\n system is to be solved. This approach is slower but also less\n memory-intensive. Default is 'vectorized'.\n n_closest_points : int, optional\n For kriging with a moving window, specifies the number of nearby\n points to use in the calculation. This can speed up the calculation\n for large datasets, but should be used with caution.\n As Kitanidis notes, kriging with a moving window can produce\n unexpected oddities if the variogram model is not carefully chosen.\n\n Returns\n -------\n kvalues : ndarray, shape (L, M, N) or (N, 1)\n Interpolated values of specified grid or at the specified set\n of points. If style was specified as 'masked', kvalues will be a\n numpy masked array.\n sigmasq : ndarray, shape (L, M, N) or (N, 1)\n Variance at specified grid points or at the specified set of points.\n If style was specified as 'masked', sigmasq will be a numpy\n masked array.\n \"\"\"\n\n if self.verbose:\n print(\"Executing Ordinary Kriging...\\n\")\n\n if style != 'grid' and style != 'masked' and style != 'points':\n raise ValueError(\"style argument must be 'grid', 'points', \"\n \"or 'masked'\")\n\n xpts = np.atleast_1d(np.squeeze(np.array(xpoints, copy=True)))\n ypts = np.atleast_1d(np.squeeze(np.array(ypoints, copy=True)))\n zpts = np.atleast_1d(np.squeeze(np.array(zpoints, copy=True)))\n n = self.X_ADJUSTED.shape[0]\n nx = xpts.size\n ny = ypts.size\n nz = zpts.size\n a = self._get_kriging_matrix(n)\n\n if style in ['grid', 'masked']:\n if style == 'masked':\n if mask is None:\n raise IOError(\"Must specify boolean masking array when \"\n \"style is 'masked'.\")\n if mask.ndim != 3:\n raise ValueError(\"Mask is not three-dimensional.\")\n if mask.shape[0] != nz or mask.shape[1] != ny or mask.shape[2] != nx:\n if mask.shape[0] == nx and mask.shape[2] == nz and mask.shape[1] == ny:\n mask = mask.swapaxes(0, 2)\n else:\n raise ValueError(\"Mask dimensions do not match \"\n \"specified grid dimensions.\")\n mask = mask.flatten()\n npt = nz * ny * nx\n grid_z, grid_y, grid_x = np.meshgrid(zpts, ypts, xpts, indexing='ij')\n xpts = grid_x.flatten()\n ypts = grid_y.flatten()\n zpts = grid_z.flatten()\n elif style == 'points':\n if xpts.size != ypts.size and ypts.size != zpts.size:\n raise ValueError(\"xpoints, ypoints, and zpoints must have \"\n \"same dimensions when treated as listing \"\n \"discrete points.\")\n npt = nx\n else:\n raise ValueError(\"style argument must be 'grid', \"\n \"'points', or 'masked'\")\n\n xpts, ypts, zpts = \\\n _adjust_for_anisotropy(np.vstack((xpts, ypts, zpts)).T,\n [self.XCENTER, self.YCENTER, self.ZCENTER],\n [self.anisotropy_scaling_y, self.anisotropy_scaling_z],\n [self.anisotropy_angle_x, self.anisotropy_angle_y, self.anisotropy_angle_z]).T\n\n if style != 'masked':\n mask = np.zeros(npt, dtype='bool')\n\n xyz_points = np.concatenate((zpts[:, np.newaxis], ypts[:, np.newaxis],\n xpts[:, np.newaxis]), axis=1)\n xyz_data = np.concatenate((self.Z_ADJUSTED[:, np.newaxis],\n self.Y_ADJUSTED[:, np.newaxis],\n self.X_ADJUSTED[:, np.newaxis]), axis=1)\n bd = cdist(xyz_points, xyz_data, 'euclidean')\n\n if n_closest_points is not None:\n from scipy.spatial import cKDTree\n tree = cKDTree(xyz_data)\n bd, bd_idx = tree.query(xyz_points, k=n_closest_points, eps=0.0)\n if backend == 'loop':\n kvalues, sigmasq = \\\n self._exec_loop_moving_window(a, bd, mask, bd_idx)\n else:\n raise ValueError(\"Specified backend '{}' not supported \"\n \"for moving window.\".format(backend))\n else:\n if backend == 'vectorized':\n kvalues, sigmasq = self._exec_vector(a, bd, mask)\n elif backend == 'loop':\n kvalues, sigmasq = self._exec_loop(a, bd, mask)\n else:\n raise ValueError('Specified backend {} is not supported for '\n '3D ordinary kriging.'.format(backend))\n\n if style == 'masked':\n kvalues = np.ma.array(kvalues, mask=mask)\n sigmasq = np.ma.array(sigmasq, mask=mask)\n\n if style in ['masked', 'grid']:\n kvalues = kvalues.reshape((nz, ny, nx))\n sigmasq = sigmasq.reshape((nz, ny, nx))\n\n return kvalues, sigmasq\n"
]
| [
[
"numpy.concatenate",
"scipy.spatial.cKDTree",
"numpy.dot",
"numpy.meshgrid",
"numpy.fill_diagonal",
"numpy.zeros",
"numpy.array",
"numpy.absolute",
"numpy.sum",
"numpy.nonzero",
"matplotlib.pyplot.figure",
"numpy.ma.array",
"numpy.amax",
"numpy.amin",
"numpy.repeat",
"matplotlib.pyplot.show",
"scipy.spatial.distance.cdist",
"numpy.vstack"
]
]
|
melling/kaggle | [
"3071082d27293750140b5ece9ed0c3135925ecac"
]
| [
"PredictFutureSales/xgboost_example01/build_model.py"
]
| [
"# Kaggle Score: 0.91993, 3022/10421, Top 29%\n\nimport pickle\nimport time\nimport gc\nimport numpy as np\nimport pandas as pd\n\nfrom xgboost import XGBRegressor\n\n## Reread test\n\ntest = pd.read_csv('test_modified.csv').set_index('ID')\n\n# Part 2, xgboost\n\ndata = pd.read_pickle('data.pkl')\n\n# Select perfect features\n\ndata = data[[\n 'date_block_num',\n 'shop_id',\n 'item_id',\n 'item_cnt_month',\n 'city_code',\n 'item_category_id',\n 'type_code',\n 'subtype_code',\n 'item_cnt_month_lag_1',\n 'item_cnt_month_lag_2',\n 'item_cnt_month_lag_3',\n 'item_cnt_month_lag_6',\n 'item_cnt_month_lag_12',\n 'date_avg_item_cnt_lag_1',\n 'date_item_avg_item_cnt_lag_1',\n 'date_item_avg_item_cnt_lag_2',\n 'date_item_avg_item_cnt_lag_3',\n 'date_item_avg_item_cnt_lag_6',\n 'date_item_avg_item_cnt_lag_12',\n 'date_shop_avg_item_cnt_lag_1',\n 'date_shop_avg_item_cnt_lag_2',\n 'date_shop_avg_item_cnt_lag_3',\n 'date_shop_avg_item_cnt_lag_6',\n 'date_shop_avg_item_cnt_lag_12',\n 'date_cat_avg_item_cnt_lag_1',\n 'date_shop_cat_avg_item_cnt_lag_1',\n #'date_shop_type_avg_item_cnt_lag_1',\n #'date_shop_subtype_avg_item_cnt_lag_1',\n 'date_city_avg_item_cnt_lag_1',\n 'date_item_city_avg_item_cnt_lag_1',\n #'date_type_avg_item_cnt_lag_1',\n #'date_subtype_avg_item_cnt_lag_1',\n 'delta_price_lag',\n 'month',\n 'days',\n 'item_shop_last_sale',\n 'item_last_sale',\n 'item_shop_first_sale',\n 'item_first_sale',\n]]\n\n# Validation strategy is 34 month for the test set, 33 month for the validation set and 13-33 months for the train.\n\nX_train = data[data.date_block_num < 33].drop(['item_cnt_month'], axis=1)\nY_train = data[data.date_block_num < 33]['item_cnt_month']\nX_valid = data[data.date_block_num == 33].drop(['item_cnt_month'], axis=1)\nY_valid = data[data.date_block_num == 33]['item_cnt_month']\nX_test = data[data.date_block_num == 34].drop(['item_cnt_month'], axis=1)\n# # In[43]:\n\ndel data\ngc.collect()\n# #In[44]:\n\nts = time.time()\n\nmodel = XGBRegressor(\n max_depth=8,\n n_estimators=1000,\n min_child_weight=300,\n colsample_bytree=0.8,\n subsample=0.8,\n eta=0.3,\n seed=42)\n\nmodel.fit(\n X_train,\n Y_train,\n eval_metric=\"rmse\",\n eval_set=[(X_train, Y_train), (X_valid, Y_valid)],\n verbose=True,\n early_stopping_rounds=10)\n\nprint(f\"Model Fit time: {time.time() - ts}\")\n\nY_pred = model.predict(X_valid).clip(0, 20)\nY_test = model.predict(X_test).clip(0, 20)\n\n## Submission File\n\nsubmission = pd.DataFrame({\n \"ID\": test.index,\n \"item_cnt_month\": Y_test\n})\nsubmission.to_csv('xgb_submission.csv', index=False)\n\n# save predictions for an ensemble\npickle.dump(Y_pred, open('xgb_train.pickle', 'wb'))\npickle.dump(Y_test, open('xgb_test.pickle', 'wb'))\n# #In[46]:\n\n# plot_features(model, (10, 14))\n# #Out[46]:\n"
]
| [
[
"pandas.read_pickle",
"pandas.DataFrame",
"pandas.read_csv"
]
]
|
stanford-iprl-lab/Concept2Robot | [
"a5c6f40198634f167823f8c864f9d89bcf312db6"
]
| [
"rl/master.py"
]
| [
"import copy\nimport numpy as np\nimport os\nimport sys\nimport time\nnp.set_printoptions(precision=4,suppress=False)\n\nimport importlib\nimport glob\nimport imageio\nimport math\nimport datetime\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nimport torchvision.models as models\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torchvision import transforms\n\n\ndef set_init(layers):\n for layer in layers:\n nn.init.normal_(layer.weight, mean=0., std=0.05)\n nn.init.constant_(layer.bias, 0.)\n\n\nclass Master(nn.Module):\n def __init__(self, state_dim, action_dim, task_dim, max_action, params):\n super(Master, self).__init__()\n self.params = params\n self.model = models.resnet18(pretrained=True) \n self.action_dim = action_dim\n self.max_action = max_action\n self.feature_extractor = torch.nn.Sequential(*list(self.model.children())[:-2]) \n self.img_feat_block1 = nn.Sequential(\n nn.Conv2d(in_channels=512,out_channels=256,kernel_size=(3,3),stride=(2,2),padding=(1,1),bias=True),\n nn.ReLU(),\n )\n self.img_feat_dim = 256\n self.img_feat_block2 = nn.Linear(256 * 2 * 3, 256)\n self.img_feat_block3 = nn.Linear(256, 256)\n self.img_feat_block4 = nn.Linear(256, self.img_feat_dim)\n\n self.task_feat_block1 = nn.Linear(1024, 512)\n self.task_feat_block2 = nn.Linear(512, 256)\n self.task_feat_block3 = nn.Linear(256, 256)\n\n self.action_feat_block1 = nn.Linear(256+self.img_feat_dim, 256)\n self.action_feat_block5 = nn.Linear(256, 256)\n self.action_feat_block2 = nn.Linear(256, 256)\n self.action_feat_block3 = nn.Linear(256, 256)\n self.action_feat_block4 = nn.Linear(256, self.action_dim)\n\n#####3 Force \n # 1\n self.force_feat_block1 = nn.Sequential(\n nn.ConvTranspose1d(in_channels=256+self.img_feat_dim,out_channels=512,kernel_size=4,stride=1,bias=True),\n nn.ReLU(),\n )\n\n # 3\n self.force_feat_block2 = nn.Sequential(\n nn.ConvTranspose1d(in_channels=512,out_channels=256,kernel_size=3,stride=2,padding=1,bias=True),\n nn.ReLU(),\n )\n\n # 7\n self.force_feat_block3 = nn.Sequential(\n nn.ConvTranspose1d(in_channels=256,out_channels=256,kernel_size=3,stride=2,padding=1,bias=True),\n nn.ReLU(),\n )\n\n # \n self.force_feat_block4 = nn.Sequential(\n nn.ConvTranspose1d(in_channels=256,out_channels=256,kernel_size=3,stride=2,padding=1,bias=True),\n nn.ReLU(),\n )\n\n self.force_feat_block5 = nn.Sequential(\n nn.ConvTranspose1d(in_channels=256,out_channels=self.params.a_dim,kernel_size=3,stride=2,padding=1,bias=False),\n )\n\n set_init([self.img_feat_block2, self.img_feat_block3, self.img_feat_block4, self.task_feat_block1, self.task_feat_block2, self.task_feat_block3,\\\n self.action_feat_block1, self.action_feat_block2, self.action_feat_block3, self.action_feat_block4,\\\n self.action_feat_block5])\n\n def forward(self, state, task_vec):\n img_feat = self.feature_extractor(state) \n img_feat = torch.tanh(self.img_feat_block1(img_feat))\n img_feat = img_feat.view(-1,256 * 2 * 3)\n img_feat = F.relu(self.img_feat_block2(img_feat))\n img_feat = F.relu(self.img_feat_block3(img_feat))\n img_feat = F.relu(torch.tanh(self.img_feat_block4(img_feat)))\n \n task_feat = F.relu(self.task_feat_block1(task_vec))\n task_feat = F.relu(self.task_feat_block2(task_feat))\n task_feat = F.relu(self.task_feat_block3(task_feat))\n\n task_feat = torch.cat([img_feat,task_feat],-1)\n \n###################################################################\n action_feat = F.relu(self.action_feat_block1(task_feat))\n action_feat = F.relu(self.action_feat_block5(action_feat))\n action_feat = F.relu(self.action_feat_block2(action_feat))\n action_feat = F.relu(self.action_feat_block3(action_feat))\n goal = self.action_feat_block4(action_feat)\n\n force_feat_raw = task_feat\n force_feat = force_feat_raw.unsqueeze(2)\n force_feat = F.relu(self.force_feat_block1(force_feat))\n force_feat = F.relu(self.force_feat_block2(force_feat))\n force_feat = F.relu(self.force_feat_block3(force_feat))\n force_feat = F.relu(self.force_feat_block4(force_feat))\n force_feat = self.force_feat_block5(force_feat)\n _, n_dim, timesteps = force_feat.size()\n force = torch.transpose(force_feat, 1, 2)\n weights = np.linspace(1, 0, self.params.traj_timesteps).reshape((1, self.params.traj_timesteps, 1)) * float(\n self.params.traj_timesteps)\n weights = torch.FloatTensor(weights).to(\"cuda\")\n force = weights * force\n return goal, force\n\n\nclass Master_F(nn.Module):\n def __init__(self, state_dim, action_dim, task_dim, max_action, params):\n super(Master_F, self).__init__()\n self.params = params\n self.model = models.resnet18(pretrained=True)\n self.action_dim = action_dim\n self.max_action = max_action\n self.feature_extractor = torch.nn.Sequential(*list(self.model.children())[:-2])\n self.img_feat_block1 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=True),\n nn.ReLU(),\n # nn.BatchNorm2d(256),\n )\n self.img_feat_dim = 128\n self.img_feat_block2 = nn.Linear(256 * 2 * 3, 256)\n self.img_feat_block3 = nn.Linear(256 * self.params.stack_num, 128)\n self.img_feat_block4 = nn.Linear(128, self.img_feat_dim)\n\n self.task_feat_block1 = nn.Linear(1024, 512)\n self.task_feat_block2 = nn.Linear(512, 256)\n self.task_feat_block3 = nn.Linear(256, 256)\n\n self.action_feat_block1 = nn.Linear(256 + self.img_feat_dim, 256)\n self.action_feat_block2 = nn.Linear(256, 128)\n self.action_feat_block3 = nn.Linear(128, 64)\n self.action_feat_block4 = nn.Linear(64, self.action_dim)\n\n set_init(\n [self.img_feat_block2, self.img_feat_block3, self.img_feat_block4, self.task_feat_block1, self.task_feat_block2,\n self.task_feat_block3, \\\n self.action_feat_block1, self.action_feat_block2, self.action_feat_block3, self.action_feat_block4])\n\n def forward(self, state, task_vec):\n img_feat = self.feature_extractor(state)\n img_feat = torch.tanh(self.img_feat_block1(img_feat))\n img_feat = img_feat.view(-1, 256 * 2 * 3)\n img_feat = F.relu(self.img_feat_block2(img_feat))\n img_feat = img_feat.view(-1, 256 * self.params.stack_num)\n img_feat = F.relu(self.img_feat_block3(img_feat))\n img_feat = F.relu(torch.tanh(self.img_feat_block4(img_feat)))\n\n task_feat = F.relu(self.task_feat_block1(task_vec))\n task_feat = F.relu(self.task_feat_block2(task_feat))\n task_feat = F.relu(self.task_feat_block3(task_feat))\n\n task_feat = torch.cat([img_feat, task_feat], -1)\n\n ###################################################################\n feedback = F.relu(self.action_feat_block1(task_feat))\n feedback = F.relu(self.action_feat_block2(feedback))\n feedback = F.relu(self.action_feat_block3(feedback))\n feedback = self.action_feat_block4(feedback)\n feedback = self.max_action * torch.tanh(feedback)\n return feedback\n"
]
| [
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.ConvTranspose1d",
"torch.nn.init.constant_",
"numpy.set_printoptions",
"torch.tanh",
"torch.FloatTensor",
"torch.nn.ReLU",
"torch.nn.init.normal_",
"torch.nn.Conv2d",
"torch.transpose",
"numpy.linspace"
]
]
|
benjisidi/transformer-explainability | [
"8c0278a152ef29e26cb479850afebcbfb013d5c8"
]
| [
"plot_attr_histograms.py"
]
| [
"from matplotlib import pyplot as plt\nfrom utils.compare_gradients import get_cos_similarites_batch, get_n_best_matches\nfrom utils.process_data import encode, pad_to_equal_length\nfrom utils.compute_gradients import (\n get_layer_gradients,\n get_layer_integrated_gradients,\n)\nfrom transformers import AutoModelForSequenceClassification, AutoTokenizer\nfrom datasets import load_dataset\nimport torch\nimport pickle\nfrom pprint import pprint\nfrom os import path\nfrom scipy import stats\nfrom tqdm import tqdm\nimport pandas as pd\nfrom models.distilbert_finetuned import get_distilbert_finetuned\n\n# Ipython debugger\nimport ipdb\nimport numpy as np\n\n\ndef get_attr_scores():\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n model, tokenizer, layers = get_distilbert_finetuned()\n\n def fwd(inputs, mask):\n return model(inputs, attention_mask=mask).logits\n\n def fwd_return_best(inputs, mask):\n results = model(inputs, attention_mask=mask).logits\n best = torch.argmax(results, dim=1)\n return torch.gather(results, 1, best.unsqueeze(1))\n\n n_samples = 800\n\n train_dataset = load_dataset(\"glue\", \"sst2\", split=\"train\")\n test_ds = load_dataset(\"glue\", \"sst2\", split=f\"test[:{n_samples}]\")\n\n # Define Dataloaders\n train_ds = train_dataset.map(\n encode, batched=True, fn_kwargs={\"tokenizer\": tokenizer}\n )\n train_ds.set_format(\"torch\", columns=[\"input_ids\", \"attention_mask\", \"label\"])\n train_dataloader = torch.utils.data.DataLoader(\n train_ds, collate_fn=tokenizer.pad, batch_size=20\n )\n\n test_ds = test_ds.map(\n encode,\n batched=True,\n fn_kwargs={\"tokenizer\": tokenizer},\n load_from_cache_file=False,\n )\n test_ds.set_format(\n \"torch\",\n columns=[\"input_ids\", \"attention_mask\", \"label\"],\n # output_all_columns=True,\n )\n test_dataloader = torch.utils.data.DataLoader(\n test_ds, collate_fn=tokenizer.pad, batch_size=5\n )\n\n # Get Gradients\n pickled_grads = \"./dense_gradients.pkl\"\n if not path.isfile(pickled_grads):\n print(\"Calculating gradients...\")\n grads = get_layer_gradients(train_dataloader, layers, fwd)\n print(\"Saving gradients...\")\n with open(pickled_grads, \"wb\") as f:\n pickle.dump(grads, f)\n else:\n print(\"Loading saved gradients...\")\n with open(pickled_grads, \"rb\") as f:\n grads = pickle.load(f)\n\n example_scores = torch.empty((len(test_ds), grads.shape[1]))\n counter = 0\n for i, batch in enumerate(tqdm(test_dataloader)):\n activations = get_layer_integrated_gradients(\n inputs=batch[\"input_ids\"].to(device),\n mask=batch[\"attention_mask\"].to(device),\n # target=batch[\"label\"].to(device),\n layers=layers.to(device),\n fwd=fwd_return_best,\n device=device,\n )\n simils = get_cos_similarites_batch(activations, grads, sparse=False)\n # Simils is batch_size x n_train\n batch_size = len(batch[\"label\"])\n example_scores[counter : counter + batch_size] = simils\n counter += batch_size\n # mean_scores = torch.mean(example_scores, dim=0)\n np.save(f\"./attr_scores_{n_samples}.npy\", example_scores)\n return example_scores\n\n\nif __name__ == \"__main__\":\n scores = np.load(\"./data/attr_scores_800.npy\")\n mean_scores = np.mean(scores, axis=0)\n max_scores = np.max(scores, axis=0)\n min_scores = np.min(scores, axis=0)\n rdm_test_A = scores[42]\n rdm_test_B = scores[742]\n counts, bins = np.histogram(mean_scores)\n plt.ylabel(\"Count\")\n plt.hist(bins[:-1], bins=bins, weights=counts)\n plt.xlabel(\"Cos Similarity\")\n plt.title(\"Mean score (n=800)\")\n plt.figure()\n counts2, bins2 = np.histogram(max_scores)\n plt.hist(bins2[:-1], bins=bins2, weights=counts2)\n plt.ylabel(\"Count\")\n plt.xlabel(\"Cos Similarity\")\n plt.title(\"Max score (n=800)\")\n plt.figure()\n counts3, bins3 = np.histogram(min_scores)\n plt.hist(bins3[:-1], bins=bins3, weights=counts3)\n plt.ylabel(\"Count\")\n plt.xlabel(\"Cos Similarity\")\n plt.title(\"Min score (n=800)\")\n plt.figure()\n counts4, bins4 = np.histogram(rdm_test_A)\n plt.hist(bins4[:-1], bins=bins4, weights=counts4)\n plt.ylabel(\"Count\")\n plt.xlabel(\"Cos Similarity\")\n plt.title(\"Random Test Example A\")\n plt.figure()\n counts4, bins4 = np.histogram(rdm_test_B)\n plt.hist(bins4[:-1], bins=bins4, weights=counts4)\n plt.ylabel(\"Count\")\n plt.xlabel(\"Cos Similarity\")\n plt.title(\"Random Test Example B\")\n plt.show()\n"
]
| [
[
"numpy.max",
"numpy.histogram",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"numpy.load",
"numpy.min",
"numpy.mean",
"numpy.save",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.hist",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"torch.argmax"
]
]
|
KhondokerTanvirHossain/stock-market-exchange-prediction | [
"9cd2e9c94b38692473d4113ecbad96e3408fbeb1"
]
| [
"ccbg.py"
]
| [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras.models import model_from_json\nimport math\nfrom sklearn.metrics import mean_squared_error\nimport requests\nfrom textblob import TextBlob\n#dataset_main = pd.read_csv('Google_Stock_Price_Train.csv')\n#dataset = dataset_main.iloc[0:1259, 1:2].values\nfile = open(\"Stocks/ccbg.us.txt\", \"r\") \ndataset = [[]]\ncount = 0\nfor line in file:\n tokens = line.split(',')\n array = [0]\n if count > 0 :\n array[0] = float(tokens[1])\n dataset.insert(count,array)\n count = count + 1\n#print (count)\ndataset.pop(0)\n#print (dataset) \n\nsc = MinMaxScaler(feature_range = (0, 1))\ndataset_scaled = sc.fit_transform(dataset)\n\n\ndef train(): \n #training_set = dataset.iloc[0:4001, 2:3].values\n #training_set_scaled = sc.fit_transform(training_set)\n plt.plot(dataset, color = 'blue', label = 'Price')\n plt.title('Price')\n plt.xlabel('Time')\n plt.ylabel('Price')\n plt.legend()\n plt.show()\n X_train = []\n y_train = []\n X_train = dataset_scaled[0:2899]\n y_train = dataset_scaled[1:2900]\n plt.plot(X_train, color = 'red', label = 'Scaled Price')\n plt.title('Scaled Price')\n plt.xlabel('Time')\n plt.ylabel('Price')\n plt.legend()\n plt.show()\n X_train, y_train = np.array(X_train), np.array(y_train)\n\n X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n\n regressor = Sequential()\n\n regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1)))\n \n regressor.add(Dense(units = 1))\n\n regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')\n\n regressor.fit(X_train, y_train, epochs = 200, batch_size = 32)\n \n\n model_json = regressor.to_json()\n with open(\"modelTempantm.json\", \"w\") as json_file:\n json_file.write(model_json)\n regressor.save_weights(\"modelTempantm.h5\")\n print(\"Saved model to disk\")\n\n\ndef load():\n test_set = dataset[2900:2990]\n #test_set_scaled = sc.transform(test_set)\n test_set_scaled = dataset_scaled[2900:2990]\n json_file = open('modelTempantm.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n # load weights into new model\n loaded_model.load_weights(\"modelTempantm.h5\")\n print(\"Loaded model from disk\")\n test_set_reshaped = np.reshape(test_set_scaled, (test_set_scaled.shape[0], test_set_scaled.shape[1], 1))\n predicted_temprature = loaded_model.predict(test_set_reshaped)\n predicted_temprature = sc.inverse_transform(predicted_temprature)\n fig_size = plt.rcParams[\"figure.figsize\"]\n fig_size[0] = 12\n fig_size[1] = 5\n plt.rcParams[\"figure.figsize\"] = fig_size\n plt.plot(predicted_temprature, color = 'blue', label = 'Predicted Price')\n plt.plot(test_set, color = 'red', label = 'Real Price')\n plt.title('Price Prediction')\n plt.xlabel('Time')\n plt.ylabel('Price')\n plt.legend()\n plt.show()\n rmse = math.sqrt(mean_squared_error(test_set, predicted_temprature)) / 10\n print (rmse)\n \ndef prediction():\n #test_set = dataset_main.iloc[4001:4101, 2:3].values\n #test_set_scaled = sc.transform(test_set)\n test_set_scaled = dataset_scaled[2990:3000]\n json_file = open('modelTempantm.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n # load weights into new model\n loaded_model.load_weights(\"modelTempantm.h5\")\n test_set_reshaped = np.reshape(test_set_scaled, (test_set_scaled.shape[0], test_set_scaled.shape[1], 1))\n predicted_temprature = loaded_model.predict(test_set_reshaped)\n predicted_temprature = sc.inverse_transform(predicted_temprature)\n #print(predicted_temprature)\n return predicted_temprature\ndef senti():\n url = ('https://newsapi.org/v2/everything?q=%20ccbg%20stock%20market&apiKey=6e593f373865401e803d6874594f9063')\n response = requests.get(url)\n #print (response.json())\n parsed_json = response.json()\n #print(parsed_json['status'])\n array = parsed_json['articles']\n polarity = 0.0;\n count = 0;\n for i in array:\n #print(i['description'])\n blob = TextBlob(i['description'])\n count = count + 1\n polarity = polarity + blob.sentiment.polarity\n polarity = polarity / count\n #print(polarity)\n return polarity\ndef run():\n print('Prediction of ccbg Stock Price in Next 10 Days :')\n p = prediction()\n s = senti()\n print(\"Date Price\")\n d = 10\n m = 1\n y = 2019\n for i in range(0,9):\n if (d == 31):\n d = 1;\n m += 1;\n if (m == 13):\n m = 1;\n print(str(d) + \"-\" + str(m) + \"-\"+ str(y)+\": \"+ str(p[i][0]))\n d += 1\n print('news polarity : ' + str(s))\n if s > 0.5 :\n print('User Demand Is Very High')\n elif s > 0:\n print('User Demand Is High')\n elif s < -0.5:\n print('User Demand Is Very Low')\n elif s < 0:\n print('User Demand IS Low') \n"
]
| [
[
"numpy.array",
"sklearn.metrics.mean_squared_error",
"numpy.reshape",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"sklearn.preprocessing.MinMaxScaler",
"matplotlib.pyplot.show"
]
]
|
beliveau-lab/PaintSHOP_pipeline | [
"2e7b3ebd172d8904695e4b46855d1e632c4a7dcd"
]
| [
"workflow/scripts/append_max_kmers.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 26 10:01:32 2019\n\n@author: hershe\n\nA script to append the max kmer count for a given probe to the BED row of the\nprobe. Written for use in my OligoServer/PaintSHOP Snakemake prediction \npipeline.\n\n\"\"\"\n\nimport pandas as pd\n\n# load probes with metadata\ndf = pd.read_csv(snakemake.input[0], sep='\\t', header=None)\ndf.columns = [\n 'chrom',\n 'start',\n 'stop',\n 'parent',\n 'Tm',\n 'on_target_score',\n 'off_target_score',\n 'repeat',\n 'prob'\n]\n\n# read in max kmer counts\nwith open(snakemake.input[1], 'r') as file:\n max_kmers = [line.strip() for line in file]\n\n# append counts\ndf['max_kmers'] = max_kmers\n\n# add hard-coded + strand (blockparse output)\ndf['strand'] = '+'\n\n# sort probes on chromosomal start coordinate\ndf = df.sort_values('start')\n\n# save to disk\ndf.to_csv(snakemake.output[0], sep='\\t', index=False, header=False, float_format='%.3f')\n"
]
| [
[
"pandas.read_csv"
]
]
|
murlock/hsds | [
"9f5fc3cdb64017d07e34eb422eee5398553d213c"
]
| [
"hsds/util/arrayUtil.py"
]
| [
"##############################################################################\n# Copyright by The HDF Group. #\n# All rights reserved. #\n# #\n# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #\n# Utilities. The full HSDS copyright notice, including #\n# terms governing use, modification, and redistribution, is contained in #\n# the file COPYING, which can be found at the root of the source code #\n# distribution tree. If you do not have access to this file, you may #\n# request a copy from [email protected]. #\n##############################################################################\n\nimport numpy as np\nimport hsds_logger as log\n\n\"\"\"\nConvert list that may contain bytes type elements to list of string elements \n\nTBD: Need to deal with non-string byte data (hexencode?)\n\"\"\"\ndef bytesArrayToList(data):\n if type(data) in (bytes, str):\n is_list = False\n elif isinstance(data, (np.ndarray, np.generic)):\n if len(data.shape) == 0:\n is_list = False\n data = data.tolist() # tolist will return a scalar in this case\n if type(data) in (list, tuple):\n is_list = True\n else:\n is_list = False\n else:\n is_list = True \n elif type(data) in (list, tuple):\n is_list = True\n else:\n is_list = False\n \n if is_list:\n out = []\n for item in data:\n out.append(bytesArrayToList(item)) # recursive call \n elif type(data) is bytes:\n out = data.decode(\"utf-8\")\n else:\n out = data\n \n return out\n\n\"\"\"\nConvert a list to a tuple, recursively.\nExample. [[1,2],[3,4]] -> ((1,2),(3,4))\n\"\"\"\ndef toTuple(rank, data):\n if type(data) in (list, tuple):\n if rank > 0:\n return list(toTuple(rank-1, x) for x in data)\n else:\n return tuple(toTuple(rank-1, x) for x in data)\n else:\n return data\n\n\"\"\"\nGet size in bytes of a numpy array.\n\"\"\"\ndef getArraySize(arr):\n nbytes = arr.dtype.itemsize\n for n in arr.shape:\n nbytes *= n\n return nbytes\n\n\"\"\"\nHelper - get num elements defined by a shape\nTODO: refactor some function in dsetUtil.py\n\"\"\"\ndef getNumElements(dims):\n num_elements = 0\n if isinstance(dims, int):\n num_elements = dims\n elif isinstance(dims, (list, tuple)):\n num_elements = 1\n for dim in dims:\n num_elements *= dim\n else:\n raise ValueError(\"Unexpected argument\")\n return num_elements\n\n\"\"\" \nGet dims from a given shape json. Return [1,] for Scalar datasets,\n None for null dataspaces\n\"\"\"\ndef getShapeDims(shape):\n dims = None\n if isinstance(shape, int):\n dims = [shape,]\n elif isinstance(shape, list) or isinstance(shape, tuple):\n dims = shape # can use as is\n elif isinstance(shape, str):\n # only valid string value is H5S_NULL\n if shape != 'H5S_NULL':\n raise ValueError(\"Invalid value for shape\")\n dims = None\n elif isinstance(shape, dict):\n if \"class\" not in shape:\n raise ValueError(\"'class' key not found in shape\")\n if shape[\"class\"] == 'H5S_NULL':\n dims = None\n elif shape[\"class\"] == 'H5S_SCALAR':\n dims = [1,]\n elif shape[\"class\"] == 'H5S_SIMPLE':\n if \"dims\" not in shape:\n raise ValueError(\"'dims' key expected for shape\")\n dims = shape[\"dims\"]\n else:\n raise ValueError(\"Unknown shape class: {}\".format(shape[\"class\"]))\n else:\n raise ValueError(\"Unexpected shape class: {}\".format(type(shape)))\n \n return dims\n\n\n\"\"\"\nReturn numpy array from the given json array.\n\"\"\"\ndef jsonToArray(data_shape, data_dtype, data_json):\n # utility function to initialize vlen array\n def fillVlenArray(rank, data, arr, index):\n for i in range(len(data)):\n if rank > 1: \n index = fillVlenArray(rank-1, data[i], arr, index)\n else:\n arr[index] = data[i]\n index += 1\n return index\n \n\n # need some special conversion for compound types --\n # each element must be a tuple, but the JSON decoder\n # gives us a list instead.\n if len(data_dtype) > 1 and not isinstance(data_json, (list, tuple)):\n raise TypeError(\"expected list data for compound data type\")\n npoints = getNumElements(data_shape)\n np_shape_rank = len(data_shape)\n \n if type(data_json) in (list, tuple): \n converted_data = []\n if npoints == 1 and len(data_json) == len(data_dtype):\n converted_data.append(toTuple(0, data_json))\n else: \n converted_data = toTuple(np_shape_rank, data_json)\n data_json = converted_data\n else:\n data_json = [data_json,] # listify\n\n if isVlen(data_dtype):\n arr = np.zeros((npoints,), dtype=data_dtype)\n fillVlenArray(np_shape_rank, data_json, arr, 0)\n else:\n try:\n arr = np.array(data_json, dtype=data_dtype)\n except UnicodeEncodeError as ude:\n msg = \"Unable to encode data\"\n log.warn(msg)\n raise ValueError(msg) from ude\n # raise an exception of the array shape doesn't match the selection shape\n # allow if the array is a scalar and the selection shape is one element,\n # numpy is ok with this\n if arr.size != npoints:\n msg = \"Input data doesn't match selection number of elements\"\n msg += \" Expected {}, but received: {}\".format(npoints, arr.size)\n log.warn(msg)\n raise ValueError(msg)\n if arr.shape != data_shape:\n arr = arr.reshape(data_shape) # reshape to match selection\n\n return arr\n\n\"\"\"\nReturn True if the type contains variable length elements\n\"\"\"\ndef isVlen(dt):\n is_vlen = False\n if len(dt) > 1:\n names = dt.names\n for name in names:\n if isVlen(dt[name]):\n is_vlen = True\n break\n else:\n if dt.metadata and \"vlen\" in dt.metadata:\n is_vlen = True\n return is_vlen\n\n\"\"\"\nGet number of byte needed to given element as a bytestream\n\"\"\"\ndef getElementSize(e, dt):\n #print(\"getElementSize - e: {} dt: {}\".format(e, dt))\n if len(dt) > 1:\n count = 0\n for name in dt.names:\n field_dt = dt[name]\n field_val = e[name]\n count += getElementSize(field_val, field_dt)\n elif not dt.metadata or \"vlen\" not in dt.metadata:\n count = dt.itemsize # fixed size element\n else:\n # variable length element\n vlen = dt.metadata[\"vlen\"]\n if isinstance(e, int):\n if e == 0:\n count = 4 # non-initialized element\n else:\n raise ValueError(\"Unexpected value: {}\".format(e))\n elif isinstance(e, bytes):\n count = len(e) + 4\n elif isinstance(e, str):\n count = len(e.encode('utf-8')) + 4\n elif isinstance(e, np.ndarray):\n nElements = np.prod(e.shape)\n if e.dtype.kind != 'O':\n count = e.dtype.itemsize * nElements\n else:\n arr1d = e.reshape((nElements,))\n count = 0\n for item in arr1d:\n count += getElementSize(item, dt)\n count += 4 # byte count\n elif isinstance(e, list) or isinstance(e, tuple):\n #print(\"got list for e:\", e)\n count = len(e) * vlen.itemsize + 4 # +4 for byte count\n else:\n raise TypeError(\"unexpected type: {}\".format(type(e)))\n return count\n\n\n\"\"\"\nGet number of bytes needed to store given numpy array as a bytestream\n\"\"\"\ndef getByteArraySize(arr):\n if not isVlen(arr.dtype):\n return arr.itemsize * np.prod(arr.shape)\n nElements = np.prod(arr.shape)\n # reshape to 1d for easier iteration\n arr1d = arr.reshape((nElements,))\n dt = arr1d.dtype\n count = 0\n for e in arr1d:\n count += getElementSize(e, dt)\n return count\n\n\"\"\"\nCopy to buffer at given offset\n\"\"\"\ndef copyBuffer(src, des, offset):\n for i in range(len(src)):\n des[i+offset] = src[i]\n \n return offset + len(src)\n\n\"\"\"\nCopy element to bytearray\n\"\"\"\ndef copyElement(e, dt, buffer, offset):\n if len(dt) > 1:\n for name in dt.names:\n field_dt = dt[name]\n field_val = e[name]\n offset = copyElement(field_val, field_dt, buffer, offset) \n elif not dt.metadata or \"vlen\" not in dt.metadata:\n #print(\"e novlen: {} type: {}\".format(e, type(e)))\n e_buf = e.tobytes()\n offset = copyBuffer(e_buf, buffer, offset)\n else:\n # variable length element\n vlen = dt.metadata[\"vlen\"]\n if isinstance(e, int):\n if e == 0:\n # write 4-byte integer 0 to buffer\n offset = copyBuffer(b'\\x00\\x00\\x00\\x00', buffer, offset) \n else:\n raise ValueError(\"Unexpected value: {}\".format(e))\n elif isinstance(e, bytes):\n count = np.int32(len(e))\n offset = copyBuffer(count.tobytes(), buffer, offset)\n offset = copyBuffer(e, buffer, offset)\n elif isinstance(e, str):\n text = e.encode('utf-8')\n count = np.int32(len(text))\n offset = copyBuffer(count.tobytes(), buffer, offset)\n offset = copyBuffer(text, buffer, offset)\n\n elif isinstance(e, np.ndarray):\n nElements = np.prod(e.shape)\n if e.dtype.kind != 'O':\n count = np.int32(e.dtype.itemsize * nElements)\n offset = copyBuffer(count.tobytes(), buffer, offset)\n offset = copyBuffer(e.tobytes(), buffer, offset)\n else:\n arr1d = e.reshape((nElements,))\n for item in arr1d:\n offset = copyElement(item, dt, buffer, offset) \n\n elif False and isinstance(e, list) or isinstance(e, tuple):\n count = np.int32(len(e) * vlen.itemsize)\n offset = copyBuffer(count.tobytes(), buffer, offset)\n if isinstance(e, np.ndarray):\n arr = e\n else:\n arr = np.asarray(e, dtype=vlen)\n offset = copyBuffer(arr.tobytes(), buffer, offset)\n \n else:\n raise TypeError(\"unexpected type: {}\".format(type(e)))\n #print(\"buffer: {}\".format(buffer))\n return offset\n\n\"\"\"\nGet the count value from persisted vlen array\n\"\"\"\ndef getElementCount(buffer, offset):\n count_bytes = bytes(buffer[offset:(offset+4)])\n \n try:\n count = int(np.frombuffer(count_bytes, dtype=\"<i4\"))\n except TypeError as e:\n msg = \"Unexpected error reading count value for variable length elemennt: {}\".format(e)\n log.error(msg)\n raise TypeError(msg)\n if count < 0:\n # shouldn't be negative\n raise ValueError(\"Unexpected count value for variable length element\")\n if count > 1024*1024*1024:\n # expect variable length element to be between 0 and 1mb\n raise ValueError(\"Variable length element size expected to be less than 1MB\")\n return count\n\n\n\"\"\"\nRead element from bytearrray \n\"\"\"\ndef readElement(buffer, offset, arr, index, dt):\n #print(\"readElement, offset: {}, index: {} dt: {}\".format(offset, index, dt))\n \n if len(dt) > 1:\n e = arr[index]\n for name in dt.names:\n field_dt = dt[name]\n offset = readElement(buffer, offset, e, name, field_dt)\n elif not dt.metadata or \"vlen\" not in dt.metadata:\n count = dt.itemsize\n e_buffer = buffer[offset:(offset+count)]\n offset += count\n arr[index] = np.frombuffer(bytes(e_buffer), dtype=dt)\n else:\n # variable length element\n vlen = dt.metadata[\"vlen\"]\n e = arr[index]\n \n if isinstance(e, np.ndarray):\n nelements = np.prod(dt.shape)\n e.reshape((nelements,))\n for i in range(nelements):\n offset = readElement(buffer, offset, e, i, dt)\n e.reshape(dt.shape)\n else:\n count = getElementCount(buffer, offset)\n offset += 4\n if count > 0:\n e_buffer = buffer[offset:(offset+count)]\n offset += count\n\n if vlen is bytes:\n arr[index] = bytes(e_buffer)\n elif vlen is str:\n s = e_buffer.decode(\"utf-8\")\n arr[index] = s\n else:\n e = np.frombuffer(bytes(e_buffer), dtype=vlen)\n arr[index] = e\n \n return offset\n\n \n \n\"\"\" \nReturn byte representation of numpy array\n\"\"\"\ndef arrayToBytes(arr):\n if not isVlen(arr.dtype):\n # can just return normal numpy bytestream\n return arr.tobytes() \n \n nSize = getByteArraySize(arr)\n buffer = bytearray(nSize)\n offset = 0\n nElements = np.prod(arr.shape)\n arr1d = arr.reshape((nElements,))\n for e in arr1d:\n offset = copyElement(e, arr1d.dtype, buffer, offset)\n return buffer\n\n\"\"\"\nCreate numpy array based on byte representation\n\"\"\"\ndef bytesToArray(data, dt, shape):\n nelements = getNumElements(shape)\n if not isVlen(dt):\n # regular numpy from string\n arr = np.frombuffer(data, dtype=dt) \n else:\n arr = np.zeros((nelements,), dtype=dt)\n offset = 0\n for index in range(nelements):\n offset = readElement(data, offset, arr, index, dt)\n arr = arr.reshape(shape)\n return arr\n"
]
| [
[
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.prod",
"numpy.frombuffer",
"numpy.int32"
]
]
|
diffunity/kpmg-corona-blue | [
"93c063933981009af8d661b9b91dda5e2ebf68ab"
]
| [
"model_video/src/model.py"
]
| [
"# code partially from: https://github.com/siqueira-hc/Efficient-Facial-Feature-Learning-with-Wide-Ensemble-based-Convolutional-Neural-Networks\nimport os\nimport sys\nimport json\nimport yaml\nimport logging\nimport requests\n\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nimport face_recognition\nimport torchvision.transforms as t\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.datasets.folder import default_loader\n\nfrom facial_emotion_recognition import facial_emotion_recognition_video\n\nlogger = logging.getLogger(__name__)\n\nclass model:\n def __init__(self):\n self.user_image_URL = \"https://kpmg-ybigta-image.s3.ap-northeast-2.amazonaws.com/user_image.jpg\"\n\n def inference(self, message:json):\n\n result = facial_emotion_recognition_video(message[\"video_path\"], self.user_image_URL)\n \n fname = message[\"video_path\"]+\"_result.json\"\n json.dump(result, open(fname, \"w\"))\n print(f\"Results dumped in JSON in {fname}\")\n\n return result\n \n\n def deploy(self):\n \n look_at_queue = {\"input\": np.ndarray(self.config[\"unittest_settings\"][\"input_dimension\"])}\n output = self.inference(look_at_queue)\n\n def run(self):\n print(\"Model successfully deployed\")\n while True:\n self.deploy()\n\nif __name__==\"__main__\":\n\n model = model()\n\n model.run()\n"
]
| [
[
"numpy.ndarray"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.