{"text": "import sys\nsys.path.append('../rxnft_vae')\nimport rdkit\nimport rdkit.Chem as Chem\nfrom rdkit.Chem import QED, Descriptors, rdmolops\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nimport math, random, sys\nfrom optparse import OptionParser\nfrom collections import deque\n\nfrom reaction_utils import get_mol_from_smiles, get_smiles_from_mol,read_multistep_rxns, get_template_order, get_qed_score,get_clogp_score\nfrom reaction import ReactionTree, extract_starting_reactants, StartingReactants, Templates, extract_templates,stats\nfrom fragment import FragmentVocab, FragmentTree, FragmentNode, can_be_decomposed\nfrom vae import FTRXNVAE, set_batch_nodeID\nfrom mpn import MPN,PP,Discriminator\nfrom evaluate import Evaluator\nimport random\nimport numpy as np\nimport networkx as nx\n\nfrom sparse_gp import SparseGP\nimport scipy.stats as sps\nimport sascorer\n\n\ndef decode_many_times(model, latent):\n\tprob_decode = True\n\tlatent_size = model.latent_size\n\tft_mean = latent[:, :latent_size]\n\trxn_mean = latent[:, latent_size:]\n\tproduct_list=[]\n\tfor i in range(50):\n\t\tgenerated_tree = model.fragment_decoder.decode(ft_mean, prob_decode)\n\t\tg_encoder_output, g_root_vec = model.fragment_encoder([generated_tree])\n\t\tproduct, reactions = model.rxn_decoder.decode(rxn_mean, g_encoder_output, prob_decode)\n\t\tif product != None:\n\t\t\tproduct_list.append([product, reactions])\n\tif len(product_list) == 0:\n\t\treturn None\n\telse:\n\t\treturn product_list\n\ndef run_bo(X_train, y_train, X_test, y_test, model, parameters, metric, randseed):\n\trandom_seed = int(randseed)\n\tnp.random.seed(random_seed)\n\tif metric ==\"logp\":\n\t\tlogp_m = parameters[0]\n\t\tlogp_s = parameters[1]\n\t\tsascore_m = parameters[2]\n\t\tsascore_s = parameters[3]\n\t\tcycle_m = parameters[4]\n\t\tcycle_s = parameters[5]\n\n\tfilename = \"../Results/\" + metric + str(random_seed) + \".txt\"\n\n\t#print(\"maxmimum score :\", np.min(y_train), X_train.shape)\n\t#print(y_train)\n\twith open(filename, \"w\") as writer:\n\t\titeration = 0\n\t\tlatents = []\n\t\tmin_scores = []\n\t\twhile iteration < 5:\n\t\t\t# fit the GP\n\t\t\t#print(\"maxmimum score :\", np.min(y_train), X_train.shape)\n\t\t\tprint(iteration)\n\t\t\tnp.random.seed(iteration * random_seed)\n\t\t\tM = 500\n\t\t\tsgp = SparseGP(X_train, 0 * X_train, y_train, M)\n\t\t\tsgp.train_via_ADAM(X_train, 0 * X_train, y_train, X_test, X_test * 0, y_test, minibatch_size = 10 * M, max_iterations = 100, learning_rate = 0.001)\n\n\t\t\tpred, uncert = sgp.predict(X_test, 0 * X_test)\n\t\t\terror = np.sqrt(np.mean((pred - y_test)**2))\n\t\t\ttestll = np.mean(sps.norm.logpdf(pred - y_test, scale = np.sqrt(uncert)))\n\t\t\tprint('Test RMSE: ', error, ' Test ll: ', testll)\n\n\t\t\tpred, uncert = sgp.predict(X_train, 0 * X_train)\n\t\t\terror = np.sqrt(np.mean((pred - y_train)**2))\n\t\t\ttrainll = np.mean(sps.norm.logpdf(pred - y_train, scale = np.sqrt(uncert)))\n\t\t\tprint( 'Train RMSE: ', error, 'Train ll: ', trainll)\n\t\t\t#print( 'Train ll: ', trainll)\n\n\t\t\tnext_inputs, values = sgp.batched_greedy_ei(60, np.min(X_train, 0), np.max(X_train, 0))\n\t\t\tvalid_smiles =[]\n\t\t\tnew_features =[]\n\t\t\tfull_rxn_strs=[]\n\t\t\tvalues = values.flatten()\n\t\t\tfor i in range(60):\n\t\t\t\t#print(i)\n\t\t\t\tlatent = next_inputs[i].reshape((1,-1))\n\t\t\t\t#res = model.decode_many_times(torch.from_numpy(latent).float(), 50)\n\t\t\t\tres= decode_many_times(model, torch.from_numpy(latent).float())\n\t\t\t\tif res is not None:\n\t\t\t\t\tsmiles_list = [re[0] for re in res]\n\t\t\t\t\tn_reactions = [len(re[1].split(\" \")) for re in res]\n\t\t\t\t\t#print(n_reactions)\n\t\t\t\t\tfor re in res:\n\t\t\t\t\t\tsmiles = re[0]\n\t\t\t\t\t\tif len(re[1].split(\" \")) > 0 and smiles not in valid_smiles:\n\t\t\t\t\t\t\t#print(smiles, re[1].split(\" \"))\n\t\t\t\t\t\t\tvalid_smiles.append(smiles)\n\t\t\t\t\t\t\tnew_features.append(latent)\n\t\t\t\t\t\t\tfull_rxn_strs.append(re[1])\n\t\t\t\t#print(i, res)\n\t\t\t\t\t\n\t\t\t#new_features = np.vstack(new_features)\n\t\t\tscores =[]\n\t\t\tb_valid_smiles=[]\n\t\t\tb_full_rxn_strs=[]\n\t\t\tb_scores=[]\n\t\t\tb_new_features=[]\n\t\t\tfor i in range(len(valid_smiles)):\n\t\t\t\tif metric ==\"logp\":\n\t\t\t\t\tmol = rdkit.Chem.MolFromSmiles(valid_smiles[i])\n\t\t\t\t\tif mol is None:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tcurrent_log_P_value = Descriptors.MolLogP(mol)\n\t\t\t\t\tcurrent_SA_score = -sascorer.calculateScore(mol)\n\t\t\t\t\tcycle_list = nx.cycle_basis(nx.Graph(rdmolops.GetAdjacencyMatrix(mol)))\n\t\t\t\t\tif len(cycle_list) == 0:\n\t\t\t\t\t\tcycle_length = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcycle_length = max([ len(j) for j in cycle_list ])\n\t\t\t\t\tif cycle_length <= 6:\n\t\t\t\t\t\tcycle_length = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcycle_length = cycle_length - 6\n\t\t\t\t\tcurrent_cycle_score = -cycle_length\n\t\t\t\t\tcurrent_SA_score_normalized = (current_SA_score - sascore_m) / sascore_s\n\t\t\t\t\tcurrent_log_P_value_normalized = (current_log_P_value - logp_m) / logp_s\n\t\t\t\t\tcurrent_cycle_score_normalized = (current_cycle_score - cycle_m) / cycle_s\n\t\t\t\t\tscore = current_SA_score_normalized + current_log_P_value_normalized + current_cycle_score_normalized\n\t\t\t\t\tscores.append(-score)\n\t\t\t\t\tb_valid_smiles.append(valid_smiles[i])\n\t\t\t\t\tb_full_rxn_strs.append(full_rxn_strs[i])\n\t\t\t\t\tb_new_features.append(new_features[i])\n\t\t\t\tif metric==\"qed\":\n\t\t\t\t\tmol = rdkit.Chem.MolFromSmiles(valid_smiles[i])\n\t\t\t\t\tif mol!=None:\n\t\t\t\t\t\tscore = QED.qed(mol)\n\t\t\t\t\t\tscores.append(-score)\n\t\t\t\t\t\tb_valid_smiles.append(valid_smiles[i])\n\t\t\t\t\t\tb_full_rxn_strs.append(full_rxn_strs[i])\n\t\t\t\t\t\tb_new_features.append(new_features[i])\n\t\t\tnew_features = np.vstack(b_new_features)\n\t\t\tif len(new_features) > 0:\n\t\t\t\tX_train = np.concatenate([ X_train, new_features ], 0)\n\t\t\t\ty_train = np.concatenate([ y_train, np.array(scores)[ :, None ] ], 0)\n\t\t\titeration+=1\n\n\t\t\tfor i in range(len(b_valid_smiles)):\n\t\t\t\tline = \" \".join([b_valid_smiles[i], b_full_rxn_strs[i], str(scores[i])])\n\t\t\t\twriter.write(line + \"\\n\")\n\t\t\t#print(iteration, min(scores))\n\n\n\n\nparser = OptionParser()\nparser.add_option(\"-w\", \"--hidden\", dest=\"hidden_size\", default=200)\nparser.add_option(\"-l\", \"--latent\", dest=\"latent_size\", default=50)\nparser.add_option(\"-d\", \"--depth\", dest=\"depth\", default=2)\nparser.add_option(\"-s\", \"--save_dir\", dest=\"save_path\")\nparser.add_option(\"-t\", \"--data_path\", dest=\"data_path\")\nparser.add_option(\"-v\", \"--vocab_path\", dest=\"vocab_path\")\nparser.add_option(\"-m\", \"--metric\", dest=\"metric\")\nparser.add_option(\"-r\", \"--seed\", dest=\"seed\", default=1)\nopts, _ = parser.parse_args()\n\n# get parameters\nhidden_size = int(opts.hidden_size)\nlatent_size = int(opts.latent_size)\ndepth = int(opts.depth)\nvocab_path = opts.vocab_path\ndata_filename = opts.data_path\nw_save_path = opts.save_path\nmetric = opts.metric\nseed = int(opts.seed)\n\n\n# load model\nif torch.cuda.is_available():\n\t#device = torch.device(\"cuda:1\")\n\tdevice = torch.device(\"cuda\")\n\ttorch.cuda.set_device(1)\nelse:\n\tdevice = torch.device(\"cpu\")\n\n\nprint(\"hidden size:\", hidden_size, \"latent_size:\", latent_size, \"depth:\", depth)\nprint(\"loading data.....\")\ndata_filename = opts.data_path\nroutes, scores = read_multistep_rxns(data_filename)\nrxn_trees = [ReactionTree(route) for route in routes]\nmolecules = [rxn_tree.molecule_nodes[0].smiles for rxn_tree in rxn_trees]\nreactants = extract_starting_reactants(rxn_trees)\ntemplates, n_reacts = extract_templates(rxn_trees)\nreactantDic = StartingReactants(reactants)\ntemplateDic = Templates(templates, n_reacts)\n\nprint(\"size of reactant dic:\", reactantDic.size())\nprint(\"size of template dic:\", templateDic.size())\n\n\nn_pairs = len(routes)\nind_list = [i for i in range(n_pairs)]\nfgm_trees = [FragmentTree(rxn_trees[i].molecule_nodes[0].smiles) for i in ind_list]\nrxn_trees = [rxn_trees[i] for i in ind_list]\ndata_pairs=[]\nfor fgm_tree, rxn_tree in zip(fgm_trees, rxn_trees):\n\tdata_pairs.append((fgm_tree, rxn_tree))\ncset=set()\nfor fgm_tree in fgm_trees:\n\tfor node in fgm_tree.nodes:\n\t\tcset.add(node.smiles)\ncset = list(cset)\nif vocab_path is None:\n\tfragmentDic = FragmentVocab(cset)\nelse:\n\tfragmentDic = FragmentVocab(cset, filename =vocab_path)\n\nprint(\"size of fragment dic:\", fragmentDic.size())\n\n\n\n# loading model\n\nmpn = MPN(hidden_size, depth)\nmodel = FTRXNVAE(fragmentDic, reactantDic, templateDic, hidden_size, latent_size, depth, fragment_embedding=None, reactant_embedding=None, template_embedding=None)\ncheckpoint = torch.load(w_save_path, map_location=device)\nmodel.load_state_dict(checkpoint)\nprint(\"finished loading model...\")\n\nprint(\"number of samples:\", len(data_pairs))\nlatent_list=[]\nscore_list=[]\nprint(\"num of samples:\", len(rxn_trees))\nlatent_list =[]\nscore_list=[]\nif metric ==\"qed\":\n\tfor i, data_pair in enumerate(data_pairs):\n\t\tlatent = model.encode([data_pair])\n\t\t#print(i, latent.size(), latent)\n\t\tlatent_list.append(latent[0])\n\t\trxn_tree = data_pair[1]\n\t\tsmiles = rxn_tree.molecule_nodes[0].smiles\n\t\tscore_list.append(get_qed_score(smiles))\nif metric ==\"logp\":\n\tlogP_values = np.loadtxt('logP_values.txt')\n\tSA_scores = np.loadtxt('SA_scores.txt')\n\tcycle_scores = np.loadtxt('cycle_scores.txt')\n\n\tlogp_m = np.mean(logP_values)\n\tlogp_s = np.std(logP_values)\n\n\tsascore_m = np.mean(SA_scores)\n\tsascore_s = np.std(SA_scores)\n\n\tcycle_m = np.mean(cycle_scores)\n\tcycle_s = np.std(cycle_scores)\n\tfor i, data_pair in enumerate(data_pairs):\n\t\tlatent = model.encode([data_pair])\n\t\tlatent_list.append(latent[0])\n\t\trxn_tree = data_pair[1]\n\t\tsmiles = rxn_tree.molecule_nodes[0].smiles\n\t\tscore_list.append(get_clogp_score(smiles, logp_m, logp_s, sascore_m, sascore_s, cycle_m, cycle_s))\nlatents = torch.stack(latent_list, dim=0)\nscores = np.array(score_list)\nscores = scores.reshape((-1,1))\nlatents = latents.detach().numpy()\nn = latents.shape[0]\npermutation = np.random.choice(n, n, replace = False)\nX_train = latents[ permutation, : ][ 0 : np.int(np.round(0.9 * n)), : ]\nX_test = latents[ permutation, : ][ np.int(np.round(0.9 * n)) :, : ]\ny_train = -scores[ permutation ][ 0 : np.int(np.round(0.9 * n)) ]\ny_test = -scores[ permutation ][ np.int(np.round(0.9 * n)) : ]\nprint(X_train.shape, X_test.shape)\nif metric == \"logp\":\n\tparameters = [logp_m, logp_s, sascore_m, sascore_s, cycle_m, cycle_s]\nelse: \n\tparameters =[]\n\n\nrun_bo(X_train, y_train, X_test, y_test, model, parameters, metric, seed)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1b9bf5f8e5a280fc98f029a2b09ebec9dfc3bf86", "size": 10018, "ext": "py", "lang": "Python", "max_stars_repo_path": "bo/run_bo.py", "max_stars_repo_name": "tsudalab/rxngenerator", "max_stars_repo_head_hexsha": "6f459828c03485926adb390e5bfbd4a6d91de30b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2022-01-04T09:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T22:35:53.000Z", "max_issues_repo_path": "bo/run_bo.py", "max_issues_repo_name": "tsudalab/rxngenerator", "max_issues_repo_head_hexsha": "6f459828c03485926adb390e5bfbd4a6d91de30b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bo/run_bo.py", "max_forks_repo_name": "tsudalab/rxngenerator", "max_forks_repo_head_hexsha": "6f459828c03485926adb390e5bfbd4a6d91de30b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T19:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T19:17:44.000Z", "avg_line_length": 32.4207119741, "max_line_length": 163, "alphanum_fraction": 0.7180075863, "include": true, "reason": "import numpy,import scipy,import networkx", "num_tokens": 2825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.18242551713899047, "lm_q1q2_score": 0.09903211247013974}} {"text": "import pickle\nimport os\nimport time\nimport numpy as np\nimport sys\nimport shutil\nfrom openmmlib import openmmlib\nfrom openmmlib import polymerutils\nfrom openmmlib.polymerutils import scanBlocks\nfrom openmmlib.openmmlib import Simulation\nfrom openmmlib.polymerutils import grow_rw\nimport pyximport; pyximport.install()\nfrom smcTranslocator_MovingBarrier import smcTranslocatorDirectional\nimport tools\nimport random\n\n# -------defining parameters----------\n# -- basic loop extrusion parameters--\n\nlogname=\"log.txt\"\nGPU = 0 \nLIFETIME = 100 # Processivity of cohesin, Default: 100 for WT, 1000 for Wapl KO\nSEPARATION = 200 # Separation LEFs in number of monomers, Default: 200 for WT, 100 for Wapl KO, assuming a monomer size of 1kb\nN = 10000 # System size in number of monomers\nsmcStepsPerBlock = 1 # Number of LEF steps between blocks of polymer simulations, Default: 1\nstiff = 1 # Polymer siffness in unit of bead size, default: 1\ndens = 0.2 # density in beads / volume. The density can roughly be estimated by looking at the amount of DNA in a nuclear volume, Default: 0.2\nbox = (N / dens) ** 0.33 # Define size of the bounding box for Periodic Boundary Conditions, Default: 0.33\ndata = polymerutils.grow_rw(N, int(box) - 2) # creates a compact conformation \nblock = 0 # starting block \nstg = 0.8# same as Banigan, van den Berg, Brandao eLife 2020 #0.1 #stall probability at ctcf sites \nunstallLEFRate = 0.005 # about once per two typical LEF lifetimes.\nctcf_interval = 300 # 300 kb, e.g., see Busslinger et al. Nature 2017\n\n# -- LEF and transcription dynamics -- \n\n# Note that the each rate can have a maximum value of 1. \nlef_speed=1.0\nlefperm = 0. # controls amount of LEF-LEF bypassing we have\npauseArray = np.ones(N,dtype=np.double) # The speed of LEFS at each position. Default is an array of ones, which means that LEFS go on maximum speed everywhere. To simulate the presence of CTCF Aafke reduced the speed at CTCF sites to 0.005. However, this doesn't account for directionality of CTCF!\nshrinkPauseArray=np.zeros(N,dtype=np.double)# speed at which loops shrink\nshrink_speed=0.0\nkinPol= 0.001 # PolII initiation rate, Default range: 0.00025-0.002\nkterPol=0.002 # Termination rate of PolII, Default range: 0.002-1.0. Normally transcription is initiation limited, so make sure that kinPol < kterPol\nkterPolArray=np.zeros(N,dtype=np.double) # fix this later based on gene stucture\nPolSpeed=0.1 # The speed of PolII as a fraction of the speed of cohesin. Default value: 0.1\npoldissoc=0.\n#pauseArrayPol=np.zeros(N,dtype=np.double) + PolSpeed # The speed of PolII at each lattice site #initialize later\npolloading=np.array([950,1950,2950,3950,4950,5950,6950,7950,8950]) # PolII initiation sites. The direction of the gene is set by the relative position of the polloading and poltermination sites.\n#np.array([700,903,1100,1303,1700,1903,2100,2303,2700,2903,3100,3303,3700,3903,4100,4303,4700,4903,5100,5303,5700,5903,6100,6303])\npoltermination=np.array([1850,2850,3850,4850,5850,6850,7850,8850,9850]) #PolII termination sites. At a termination site, PolII stalls with probability 1 and then unloads with rate kterPol. To simulate a broad PolII unloading area, I would set the poltermination site far beyond the gene length and then define wide region where PolII can stall, as shown on the lines below\n#np.array([800,803,1200,1203,1800,1803,2200,2203,2800,2803,3200,3203,3800,3803,4200,4203,4800,4803,5200,5203,5800,5803,6200,6203])\nstalProbPol=np.zeros(N,dtype=np.double) # The rate of PolII stalling. Once stalled, PolII unloads with a rate 'kterPol'. One can choose a single stall site, or a range of stall sites. If this array is set to zero everywhere, PolII will stall at the defined termination sites.\nstalProb=0.001 \nstall_in_gene=0.\nunstall_in_gene=1.\nunstallArray=np.zeros(N,dtype=np.double) #array for unstalling in of Pol II in gene\n\nSTALL_FROM_FILE = False # option to take stall probabilities from file for spatially varying patterns \nstallfile=\"\"\ngene_stall=[]\nctcf_left_list=[]\nctcf_right_list=[]\nstrongCTCFstall = 0\n\nTSSloadbias = 1.0\nTSSloadstart=0 #use this and TSSloadend to control offset/width of loading near TSS, note: positive TSSloadstart denotes num sites before TSS, positive TSSloadend denotes sites after TSS\nTSSloadend=0\n\nbase_genelen=200\n#genelength=[base_genelen]*len(polloading)\nvariable_genelength = 0 \nfixed_variable_genelength=0\nvariable_permeability = 0 #This varaible toggles on/off variable permeability of cohesin through RNAp depending on position in gene, 0 or 1 for constant permeability or variable perm, respectively\nvariable_type = 0 #type of variable permeability: 0- linearly decreasing, 1- step function\nvariable_offset = 0 #param for var perm function: for linear this is a constant offset from 0, for step this is offset for the bottom step\nvariable_pos = base_genelen // 2 #param: irrelevant for linear, position of step for step function.\nvariable_return = 0 #return to max permeability after passing end of gene but before reaching termination site\nvariable_TSSfactor = 1.0 # factor by which permeability at TSS is lower (or higher)\n\npermLeftArray=np.zeros(N,dtype=np.double)\npermRightArray=np.zeros(N,dtype=np.double)\n\ncollisionLifeFactor=1.0 # factor by which head-on collision with RNAP changes lifetime of cohesin\ncollisionLife=LIFETIME*collisionLifeFactor\nTTSunload=1.0 # factor by which cohesin life time is changed near TTS\nunloadZone=10 # width of zone in which cohesin life is changed by TTS\n\nPolPause=0.002 # Step rate PolII at TSS, Default: 0.002\n#later:\n#for i in polloading:\n# pauseArrayPol[i]=PolPause\n\nL=0. # Set permeability of PolII to cohesin. L=0 means PolII is impermeable. \nR=0. # Set permeability of PolII to cohesin coming from the right\n\nrun_id=1\n\n\n# -- polymer simulation settings --\n\nsteps = int(200*(smcStepsPerBlock)) # nr of 3D simulation blocks btw advancing LEFs. For deterministic stepping choose 200-250 steps per block, otherwise, rescale with stepping probability. When genes are sparse, smcStepsPerBLock is approximately the number of smc steps per smc block.\n\nsaveRNAP=True # whether or not to print RNAP positions w/ each printed block\n\nsaveEveryBlocks = int(200/(smcStepsPerBlock)) # number of blocks until polymer configuration is saved\nskipSavedBlocksBeginning = int(20/(smcStepsPerBlock)) # how many blocks (saved) to skip after you restart LEF positions\n#totalSavedBlocks = 5000 # how many blocks to save (number of blocks done is totalSavedBlocks * saveEveryBlocks)\ntotalSavedBlocks = 4000 # how many blocks to save (number of blocks done is totalSavedBlocks * saveEveryBlocks)\n#restartMilkerEveryBlocks = int(200/(smcStepsPerBlock)) \nrestartMilkerEveryBlocks = int(400/(smcStepsPerBlock)) \n#Only one Hamiltonian can be loaded at a time to the simkt, but we want to update the bonds every time a LEF steps. Loading a new Hamiltonian costs a lot of time. Instead we precalculate bonds and load all positions at once as one big Hamiltonian and just change the prefactors. \n\n# parameters for smc bonds \n\nsmcBondWiggleDist = 0.2\nsmcBondDist = 0.5\n\n\n#if len(sys.argv)!=8:\n# print(\"Warning: Number of input arguments != 8\")\n# sys.exit('Number of input arguments is not correct')\n\nFLAG=\"\" #extra label for directory name\n\n#######use custom class to parse inputs with keywords#######################\n\nparams= tools.argsList()\nfor p in params.arg_dict:\n print(p, params.arg_dict[p])\n\nif \"gpu\" in params.arg_dict:\n GPU = int(params.arg_dict[\"gpu\"])\nif \"lifetime\" in params.arg_dict:\n LIFETIME = float(params.arg_dict[\"lifetime\"])\nif \"separation\" in params.arg_dict:\n SEPARATION = float(params.arg_dict[\"separation\"])\nif \"initiation\" in params.arg_dict:\n kinPol = float(params.arg_dict[\"initiation\"])\nif \"termination\" in params.arg_dict:\n kterPol = float(params.arg_dict[\"termination\"])\nif \"dissociation\" in params.arg_dict:\n poldissoc= float(params.arg_dict[\"dissociation\"])\nif \"stall\" in params.arg_dict: #pol stall\n stalProb = float(params.arg_dict[\"stall\"])\nif \"stallgene\" in params.arg_dict:\n stall_in_gene = float(params.arg_dict[\"stallgene\"])\nif \"unstall\" in params.arg_dict: # pol unstall\n unstall_in_gene=float(params.arg_dict[\"unstall\"])\nif \"lefspeed\" in params.arg_dict:\n lef_speed=float(params.arg_dict[\"lefspeed\"])\n pauseArray= lef_speed*pauseArray\nif \"lefperm\" in params.arg_dict:\n lefperm=float(params.arg_dict[\"lefperm\"])\nif \"shrink\" in params.arg_dict:\n shrink_speed=float(params.arg_dict[\"shrink\"])\n shrinkPauseArray= shrinkPauseArray + shrink_speed\n if shrink_speed+lef_speed>1.:\n print(\"WARNING: step+shrink > 1!! extrusion probabilities will not be computed correctly.\\n\")\nif \"lefstall\" in params.arg_dict:\n stg = float(params.arg_dict[\"lefstall\"])\nif \"lefunstall\" in params.arg_dict:\n unstallLEFRate = float(params.arg_dict[\"lefunstall\"])\nif \"polspeed\" in params.arg_dict:\n PolSpeed = float(params.arg_dict[\"polspeed\"])\nif \"polpause\" in params.arg_dict:\n PolPause = float(params.arg_dict[\"polpause\"])\nif \"permL\" in params.arg_dict:\n L=float(params.arg_dict[\"permL\"])\nif \"permR\" in params.arg_dict:\n R=float(params.arg_dict[\"permR\"])\nif \"collisionlife\" in params.arg_dict:\n collisionLifeFactor=float(params.arg_dict[\"collisionlife\"])\nif \"tssload\" in params.arg_dict:\n TSSloadbias=float(params.arg_dict[\"tssload\"])\nif \"tssloadstart\" in params.arg_dict:\n TSSloadstart=int(params.arg_dict[\"tssloadstart\"])\nif \"tssloadend\" in params.arg_dict:\n TSSloadend=int(params.arg_dict[\"tssloadend\"])\nif \"ttsunload\" in params.arg_dict:\n TTSunload=float(params.arg_dict[\"ttsunload\"])\nif \"ttszone\" in params.arg_dict:\n unloadZone=int(params.arg_dict[\"ttszone\"])\nif \"genelen\" in params.arg_dict:\n base_genelen=int(params.arg_dict[\"genelen\"])\nif \"vperm\" in params.arg_dict:\n variable_permeability = int(params.arg_dict[\"vperm\"])\nif \"vpermtype\" in params.arg_dict:\n variable_type = int(params.arg_dict[\"vpermtype\"])\nif \"vpermoffset\" in params.arg_dict:\n variable_offset = float(params.arg_dict[\"vpermoffset\"])\nif \"vpermpos\" in params.arg_dict:\n variable_pos = int(params.arg_dict[\"vpermpos\"])\nif \"vreturn\" in params.arg_dict:\n variable_return = int(params.arg_dict[\"vreturn\"])\nif \"vtss\" in params.arg_dict:\n variable_TSSfactor = float(params.arg_dict[\"vtss\"])\nif \"vgene\" in params.arg_dict:\n variable_genelength = int(params.arg_dict[\"vgene\"])\nif \"fixed_vgene\" in params.arg_dict:\n fixed_variable_genelength=int(params.arg_dict[\"fixed_vgene\"])\nif \"convergent\" in params.arg_dict:\n if int(params.arg_dict[\"convergent\"]):\n #print(\"warning only correct for genelength = 110 right now.\\n\")\n polloading= np.array([840, 1160, 1640, 1960, 2440, 2760, 3240, 3560, 4040, 4360, 4840, 5160, 5640, 5960, 6440, 6760, 7240, 7560, 8040, 8360, 8840, 9160]) \n poltermination= np.array([1000, 1001, 1800, 1801, 2600, 2601, 3400, 3401, 4200, 4201, 5000, 5001, 5800, 5801, 6600, 6601, 7400, 7401, 8200, 8201, 9000, 9001])\nif \"sparse\" in params.arg_dict:\n if int(params.arg_dict[\"sparse\"]):\n #print(\"warning only correct for genelength = 110 right now.\\n\")\n polloading= np.array([1950,3950,5950,7950])\n poltermination=np.array([2850,4850,6850,8850])\nif \"ctcfint\" in params.arg_dict:\n ctcf_interval=int(params.arg_dict[\"ctcfint\"])\nif \"ctcf\" in params.arg_dict:\n if params.arg_dict[\"ctcf\"] == \"tss\":\n #puts ctcf just before each tss, alternating left/right \n ctcf_left_list = polloading[0::2] - 1\n ctcf_right_list = polloading[1::2] - 1\n elif params.arg_dict[\"ctcf\"] == \"body\":\n #puts ctcf halfway through the gene, assuming fixed gene length and genes pointing downstream\n ctcf_left_list = polloading[0::2] + base_genelen // 2\n ctcf_right_list = polloading[1::2] + base_genelen // 2\n elif params.arg_dict[\"ctcf\"] == \"distributed\":\n #put in sites every ~300 kb\n Nctcf = int(N/ctcf_interval/2)\n ctcf_left_list = np.arange(1,Nctcf+2)*2*ctcf_interval-ctcf_interval\n ctcf_right_list = np.arange(1,Nctcf+1)*2*ctcf_interval\n ctcf_left_list=np.delete(ctcf_left_list, np.where(ctcf_left_list>=N)[0])\n ctcf_right_list=np.delete(ctcf_right_list, np.where(ctcf_right_list>=N)[0])\n elif params.arg_dict[\"ctcf\"] == \"distributed2\":\n Nctcf = int(N/ctcf_interval/2)\n ctcf_left_list = np.arange(1,Nctcf+2)*2*ctcf_interval-int(3*ctcf_interval/2)\n ctcf_right_list = np.arange(1,Nctcf+1)*2*ctcf_interval-int(ctcf_interval/2)\n ctcf_left_list=np.delete(ctcf_left_list, np.where(ctcf_left_list>=N)[0])\n ctcf_right_list=np.delete(ctcf_right_list, np.where(ctcf_right_list>=N)[0])\n else:\n with open(params.arg_dict[\"ctcf\"], \"r\") as ctcffile:\n ctcfdata=ctcffile.readlines()\n #should only be 2 lines\n entries=ctcfdata[0].split()\n ctcf_left_list = np.array([int(x) for x in entries])\n entries=ctcfdata[1].split()\n ctcf_right_list = np.array([int(x) for x in entries])\nif \"strongctcf\" in params.arg_dict:\n strongCTCFstall= int(params.arg_dict[\"strongctcf\"])\n#granting command line control of these variables for flexibility:\nif \"save\" in params.arg_dict:\n saveEveryBlocks = int(int(params.arg_dict[\"save\"])/(smcStepsPerBlock))\nif \"skip\" in params.arg_dict:\n skipSavedBlocksBeginning = int(int(params.arg_dict[\"skip\"])/(smcStepsPerBlock))\nif \"total\" in params.arg_dict:\n totalSavedBlocks = int(params.arg_dict[\"total\"])\nif \"stallfile\" in params.arg_dict:\n stallfile=params.arg_dict[\"stallfile\"]\n STALL_FROM_FILE=True\nif \"restart\" in params.arg_dict:\n restartMilkerEveryBlocks = int(int(params.arg_dict[\"restart\"])/(smcStepsPerBlock))\nif \"log\" in params.arg_dict:\n logname=params.arg_dict[\"log\"]\nif \"flag\" in params.arg_dict:\n FLAG=params.arg_dict[\"flag\"]\n\n\n###### a few variables to be initialized last b/c they depend on others ###\ncollisionLife= LIFETIME*collisionLifeFactor\n\npauseArrayPol=np.zeros(N,dtype=np.double) + PolSpeed ## The speed of PolII at each lattice site\nfor i in polloading:\n pauseArrayPol[i]=PolPause\n\ngenelength=[base_genelen]*len(polloading)\nif variable_genelength:\n if fixed_variable_genelength:\n genelength=random.shuffle([80,81,82,84,86,90,95,100,110])\n else:\n for ii in range(len(genelength)):\n genelength[ii] = genelength[ii] + int(np.random.normal(0, np.sqrt(genelength[ii])))\n print(\"genelengths:\", genelength)\n\n#stalling, unstalling and termination in gene and after gene ends\nfor i,j, gl in zip(polloading,poltermination, genelength):\n if j>i: \n stalProbPol[i:i+gl]=stall_in_gene \n unstallArray[i:i+gl]=unstall_in_gene\n stalProbPol[i+gl:j]=stalProb # This line adds stall probability to all sites between end of gene (loading site + gene len) and the \"termination site\" (where pol stops with prob=1) \n # int(poltermination[0]-polloading[0])\n kterPolArray[i+gl:j]=kterPol\n kterPolArray[j]=kterPol\n else: # flipped genes\n stalProbPol[i-gl+1:i+1]=stall_in_gene\n unstallArray[i-gl:i+1]=unstall_in_gene\n stalProbPol[j+1:i-gl+1]=stalProb\n kterPolArray[j+1:i-gl+1]=kterPol\n kterPolArray[j]=kterPol\n\n\n#permeabilities\nif not variable_permeability:\n permLeftArray += L\n permRightArray += R\nelse:\n for ii in range(len(genelength)):\n direc = 2*int(poltermination[ii]>polloading[ii])-1\n gene_end=genelength[ii]*direc+polloading[ii]\n RL_factor=1.\n if not L==0.:\n RL_factor=R/L\n if variable_type == 0:\n for j in range(polloading[ii], gene_end):\n permLeftArray[j] = L*(gene_end-j)/(gene_end-polloading[ii])*direc + variable_offset\n permRightArray[j] = R*(gene_end-j)/(gene_end-polloading[ii])*direc + variable_offset*RL_factor\n permLeftArray[polloading[ii]] *= variable_TSSfactor\n permRightArray[polloading[ii]] *= variable_TSSfactor\n if gene_end 0.:\n fname=fname+\"_dissoc\"+str(poldissoc)\n if lef_speed < 1.0:\n fname=fname+\"_lefspeed\"+str(lef_speed)\n if shrink_speed > 0.0:\n fname=fname+\"_shrink\"+str(shrink_speed)\n if stall_in_gene > 0.:\n fname=fname+\"_stallgene{0}_unstall{1}\".format(stall_in_gene, unstall_in_gene)\n if lefperm > 0.:\n fname=fname+\"_lefperm{0}\".format(lefperm)\n fname=fname+FLAG\n fname=fname+\"_\"+str(run_id)\n FullFileName=os.path.join(folder, fname) \n sleeptime=np.random.uniform(0,10)\n os.system(\"sleep {0}\".format(sleeptime))\n if not os.path.exists(FullFileName):\n os.system(\"mkdir {0}\".format(FullFileName))\n print(\"directory is {0}\".format(FullFileName))\n break\n else:\n run_id = run_id+1\n\n\n# -- Assertions to make sure parameters have been chosen correctly --\n\nassert restartMilkerEveryBlocks % saveEveryBlocks == 0 \nassert (skipSavedBlocksBeginning * saveEveryBlocks) % restartMilkerEveryBlocks == 0 \nassert (totalSavedBlocks * saveEveryBlocks) % restartMilkerEveryBlocks == 0 \nassert smcStepsPerBlock<6 # max number of steps per smc block should not be too large to prevent 'jerky' polymer motion\n\nsavesPerMilker = restartMilkerEveryBlocks // saveEveryBlocks\nmilkerInitsSkip = saveEveryBlocks * skipSavedBlocksBeginning // restartMilkerEveryBlocks\nmilkerInitsTotal = (totalSavedBlocks + skipSavedBlocksBeginning) * saveEveryBlocks // restartMilkerEveryBlocks\nprint(\"Milker will be initialized {0} times, first {1} will be skipped\".format(milkerInitsTotal, milkerInitsSkip))\n\n# create filenames for Ekin, Epot and time\n\nEkin_fname = os.path.join(FullFileName,'Ekin.txt')\nEpot_fname = os.path.join(FullFileName,'Epot.txt')\ntime_fname = os.path.join(FullFileName,'time.txt')\nPar_fname = os.path.join(FullFileName,'Pars.txt')\n\n\ndef save_Es_ts_Rg():\n with open(time_fname, \"a+\") as time_file:\n time_file.write('%f\\n'%(a.state.getTime()/openmmlib.ps))\n with open(Ekin_fname, \"a+\") as Ekin_file:\n Ekin_file.write('%f\\n'%((a.state.getKineticEnergy())/a.N/a.kT))\n with open(Epot_fname, \"a+\") as Epot_file:\n Epot_file.write('%f\\n'%((a.state.getPotentialEnergy()) /a.N /a.kT))\n\nclass smcTranslocatorMilker(object):\n\n def __init__(self, smcTransObject):\n \"\"\"\n :param smcTransObject: smc translocator object to work with\n \"\"\"\n self.smcObject = smcTransObject\n self.allBonds = []\n\n def setParams(self, activeParamDict, inactiveParamDict):\n \"\"\"\n A method to set parameters for bonds.\n It is a separate method because you may want to have a Simulation object already existing\n\n :param activeParamDict: a dict (argument:value) of addBond arguments for active bonds\n :param inactiveParamDict: a dict (argument:value) of addBond arguments for inactive bonds\n\n \"\"\"\n self.activeParamDict = activeParamDict\n self.inactiveParamDict = inactiveParamDict\n\n\n def setup(self, bondForce, blocks = 100, smcStepsPerBlock = 1):\n \"\"\"\n A method that milks smcTranslocator object\n and creates a set of unique bonds, etc.\n\n :param bondForce: a bondforce object (new after simulation restart!)\n :param blocks: number of blocks to precalculate\n :param smcStepsPerBlock: number of smcTranslocator steps per block\n :return:\n \"\"\"\n\n\n if len(self.allBonds) != 0:\n raise ValueError(\"Not all bonds were used; {0} sets left\".format(len(self.allBonds)))\n\n self.bondForce = bondForce\n\n #precalculating all bonds\n allBonds = []\n for dummy in range(blocks):\n self.smcObject.steps(smcStepsPerBlock)\n left, right = self.smcObject.getSMCs()\n bonds = [(int(i), int(j)) for i,j in zip(left, right)]\n allBonds.append(bonds)\n\n self.allBonds = allBonds\n self.uniqueBonds = list(set(sum(allBonds, []))) # 'sum' preserves order and makes one long list with bonds, 'set' creates a set with left bonds from different time points ordered from small to large and eliminates two equal bonds (also if they were created by different LEFs at different times). List turns set into a list with unique bonds at different time points.\n\n # adding forces and getting bond indices\n self.bondInds = []\n self.curBonds = allBonds.pop(0) # pop(0) removes and returns first list of bonds\n\n for bond in self.uniqueBonds:\n paramset = self.activeParamDict if (bond in self.curBonds) else self.inactiveParamDict\n ind = bondForce.addBond(bond[0], bond[1], **paramset)\n self.bondInds.append(ind)\n self.bondToInd = {i:j for i,j in zip(self.uniqueBonds, self.bondInds)}\n return self.curBonds,[]\n\n\n def step(self, context, verbose=False):\n \"\"\"\n Update the bonds to the next step.\n It sets bonds for you automatically!\n :param context: context\n :return: (current bonds, previous step bonds); just for reference\n \"\"\"\n if len(self.allBonds) == 0:\n raise ValueError(\"No bonds left to run; you should restart simulation and run setup again\")\n\n pastBonds = self.curBonds\n self.curBonds = self.allBonds.pop(0) # getting current bonds\n bondsRemove = [i for i in pastBonds if i not in self.curBonds]\n bondsAdd = [i for i in self.curBonds if i not in pastBonds]\n bondsStay = [i for i in pastBonds if i in self.curBonds]\n if verbose:\n print(\"{0} bonds stay, {1} new bonds, {2} bonds removed\".format(len(bondsStay),\n len(bondsAdd), len(bondsRemove)))\n bondsToChange = bondsAdd + bondsRemove\n bondsIsAdd = [True] * len(bondsAdd) + [False] * len(bondsRemove)\n for bond, isAdd in zip(bondsToChange, bondsIsAdd):\n ind = self.bondToInd[bond]\n paramset = self.activeParamDict if isAdd else self.inactiveParamDict\n self.bondForce.setBondParameters(ind, bond[0], bond[1], **paramset) # actually updating bonds\n self.bondForce.updateParametersInContext(context) # now run this to update things in the context\n return self.curBonds, pastBonds\n\n def getRNAP(self):\n return self.smcObject.getPolOccupied()\n\ndef initModel(): \n birthArray = np.zeros(N,dtype=np.double) + 0.1\n #birthArray[polloading] *= TSSloadbias\n for nn, tt in zip(polloading,poltermination):\n #the following accounts for different gene directions:\n if tt > nn:\n loadbegin=min(max(nn-TSSloadstart,0), N) #max/min construction here ensures range will not exceed ends of polymer, noting that TSSloadstart can be + or -\n loadend=max(min(nn+TSSloadend+1,N),0)\n else:\n loadbegin= min(max(nn-TSSloadend,0),N)\n loadend= max(min(nn+TSSloadstart+1,N),0)\n for jj in range(loadbegin,loadend):\n birthArray[jj] *= TSSloadbias\n deathArray = np.zeros(N, dtype=np.double) + 1. / (LIFETIME)\n collisionDeathArray= np.zeros(N,dtype=np.double) + 1./collisionLife\n if not (TTSunload==1.):\n for nn,tt,gg in zip(polloading, poltermination, genelength):\n if tt>nn:\n zonebegin=nn+gg\n zoneend=min(nn+gg+unloadZone,N)\n else:\n zonebegin= max(nn-gg+1-unloadZone,0)\n zoneend= nn-gg+1\n for jj in range(zonebegin, zoneend):\n deathArray[jj] = 1./(TTSunload*LIFETIME)\n collisionDeathArray[jj] = 1./(TTSunload*LIFETIME)\n\n stallLeftArray = np.zeros(N, dtype=np.double) #stall prob for left LEF legs, i.e. CTCF sites that point rightward\n stallRightArray = np.zeros(N, dtype=np.double)\n if STALL_FROM_FILE: #read in stall rates from file; file should provide list of LEF stalling rates starting from the TSS, extending as long as the configuration of repeats permits\n with open(\"stallfiles/\"+stallfile,\"r\") as infile:\n stall_list = infile.readlines()\n for entry in stall_list:\n gene_stall.append(float(entry.split()[0]))\n for nn,tt in zip(polloading,poltermination):\n ii=0\n if nn0, since there won't be stalls there anyway\n stallDeathArray = np.zeros(N, dtype=np.double) + 1. / (LIFETIME) # unbinding rate during stall can be different, but we usually leave it the same \n smcNum = int(N / SEPARATION)\n curPos = 0\n \n SMCTran = smcTranslocatorDirectional(birthArray, deathArray, stallLeftArray, stallRightArray, unstallLEFArray, pauseArray, stallDeathArray, smcNum, \n kinPol,kterPolArray,pauseArrayPol,shrinkPauseArray, polloading,poltermination, stalProbPol, unstallArray, \n PolPermL=permLeftArray, PolPermR=permRightArray, collisionFalloffProb=collisionDeathArray, \n poldissoc= poldissoc, \n LefPerm=lefperm,\n strongCTCF=strongCTCFstall\n ) \n return SMCTran\n\n\nSMCTran = initModel() # defining actual smc translocator object \n\n\n\n# now polymer simulation code starts\n\n# ------------feed smcTran to the milker---\nSMCTran.steps(1000000) # first steps to \"equilibrate\" SMC dynamics. If desired of course. \nmilker = smcTranslocatorMilker(SMCTran) # now feed this thing to milker (do it once!)\n#--------- end new code ------------\n\nfor milkerCount in range(milkerInitsTotal):\n doSave = milkerCount >= milkerInitsSkip\n \n # simulation parameters are defined below \n a = Simulation(timestep=80, thermostat=0.001)#Collision rate in inverse picoseconds, low collistion rate means ballistic like motion, default in openmmpolymer is 0.001. Motion polymer is not diffusive, this is ok for statistical average,\n #but not for dynamics of the polymer\n a.setup(platform=\"CUDA\", PBC=True, PBCbox=[box, box, box], GPU=GPU, precision=\"mixed\") # set up GPU here, PBC=Periodic Boundary Conditions. Default integrator is langevin with 300 K, friction coefficient of 1/ps, step size 0.002ps\n a.saveFolder(FullFileName)\n a.load(data)\n a.addHarmonicPolymerBonds(wiggleDist=0.1) # WiggleDist controls distance at which energy of bond equals kT\n if stiff > 0:\n a.addGrosbergStiffness(stiff) # Chain stiffness is introduced by an angular potential U(theta)=stiff(1-cos(theta-Pi))\n a.addPolynomialRepulsiveForce(trunc=1.5, radiusMult=1.05) #Polynomial repulsive potential between particles. Has value trunc=3.0 at zero, stays flat until 0.6-0.7 and then drops to zero. For attraction between a selective set of particles, use LeonardJones or addSelectiveSSWForce (see blocks.py or ask Johannes)\n a.step = block\n\n # ------------ initializing milker; adding bonds ---------\n # copied from addBond\n kbond = a.kbondScalingFactor / (smcBondWiggleDist ** 2)\n bondDist = smcBondDist * a.length_scale\n\n activeParams = {\"length\":bondDist,\"k\":kbond}\n inactiveParams = {\"length\":bondDist, \"k\":0} \n milker.setParams(activeParams, inactiveParams)\n \n # this step actually puts all bonds in and sets first bonds to be what they should be\n milker.setup(bondForce=a.forceDict[\"HarmonicBondForce\"],\n blocks=restartMilkerEveryBlocks, # default value; milk for 100 blocks\n smcStepsPerBlock=smcStepsPerBlock) # \n print(\"Restarting milker\")\n\n a.doBlock(steps=steps, increment=False) # do block for the first time with first set of bonds in\n #print('done 1')\n for i in range(restartMilkerEveryBlocks - 1):\n #print(i)\n curBonds, pastBonds = milker.step(a.context) # this updates bonds. You can do something with bonds here\n if i % saveEveryBlocks == (saveEveryBlocks - 2): \n a.doBlock(steps=steps, increment = doSave)\n if doSave: \n a.save()\n pickle.dump(curBonds, open(os.path.join(a.folder, \"SMC{0}.dat\".format(a.step)),'wb'))\n save_Es_ts_Rg() # save energies and time\n if saveRNAP:\n pickle.dump(milker.getRNAP(), open(os.path.join(a.folder, \"RNAP{0}.dat\".format(a.step)), 'wb'))\n else:\n a.integrator.step(steps) # do steps without getting the positions from the GPU (faster)\n\n data = a.getData() # save data and step, and delete the simulation\n block = a.step\n del a\n \n time.sleep(0.2) # wait 200ms for sanity (to let garbage collector do its magic)\n\nwith open(Par_fname,\"a+\") as Parfile:\n Parfile.write(\" tau=\"+str(LIFETIME)+\"\\n Separation=\"+str(SEPARATION)+\"\\n N=\"+str(N)+\"\\n smcStepsPerBlock=\"+str(smcStepsPerBlock)+\"\\n stiff=\"+str(stiff)+\"\\n dens=\"+str(dens)+\"\\n block=\"+str(block)+\"\\n SaveEveryBlocks=\"+str(saveEveryBlocks)+\"\\n skipSavedBlocksBeginning=\"+str(skipSavedBlocksBeginning)+\"\\n totalSavedBlocks=\"+str(totalSavedBlocks)+\"\\n restartMilkerEveryBlocks=\"+str(restartMilkerEveryBlocks)+\"\\n smcBondWiggleDist=\"+str(smcBondWiggleDist)+\"\\n smcBondDist=\"+str(smcBondDist)+\"\\n SmcTimestep=1\\n NumMonos\"+str(N))\n\n\nos.system(\"mv {0} {1}\".format(logname, FullFileName))\n\n\n", "meta": {"hexsha": "ec373cdf3e896491732cd7aa93a7f421bd8ace21", "size": 33192, "ext": "py", "lang": "Python", "max_stars_repo_path": "simulations/SimulateMovingBarrier.py", "max_stars_repo_name": "mirnylab/moving-barriers-paper", "max_stars_repo_head_hexsha": "9084e0ce0725dfabaebcde89508b764e44b7662f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulations/SimulateMovingBarrier.py", "max_issues_repo_name": "mirnylab/moving-barriers-paper", "max_issues_repo_head_hexsha": "9084e0ce0725dfabaebcde89508b764e44b7662f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/SimulateMovingBarrier.py", "max_forks_repo_name": "mirnylab/moving-barriers-paper", "max_forks_repo_head_hexsha": "9084e0ce0725dfabaebcde89508b764e44b7662f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.9879518072, "max_line_length": 530, "alphanum_fraction": 0.6848638226, "include": true, "reason": "import numpy", "num_tokens": 9084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.1919327841361473, "lm_q1q2_score": 0.09746574492847508}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py,md\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.13.3\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\n# +\n# Uncomment to run the notebook in Colab\n# # ! pip install -q \"wax-ml[complete]@git+https://github.com/eserie/wax-ml.git\"\n# # ! pip install -q --upgrade jax jaxlib==0.1.70+cuda111 -f https://storage.googleapis.com/jax-releases/jax_releases.html\n# -\n\n# %matplotlib inline\n\n\nimport io\nimport warnings\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Any, Callable, NamedTuple, Optional, TypeVar\n\nimport haiku as hk\nimport jax\nimport jax.numpy as jnp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy as onp\nimport optax\nimport pandas as pd\nimport plotnine as gg\nimport requests\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tqdm.auto import tqdm\n\nfrom wax.accessors import register_wax_accessors\nfrom wax.compile import jit_init_apply\nfrom wax.encode import Encoder\nfrom wax.modules import Buffer, FillNanInf, Lag, RollingMean\nfrom wax.unroll import unroll\n\nprint(\"jax backend {}\".format(jax.lib.xla_bridge.get_backend().platform))\njax.devices()\n\n# # 🔭 Reconstructing the light curve of stars with LSTM 🔭\n#\n# [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eserie/wax-ml/blob/main/docs/notebooks/05_reconstructing_the_light_curve_of_stars.ipynb)\n\n# Let's take a walk through the stars...\n#\n# This notebook is based on the study done in\n# [this post by Christophe Pere](https://towardsdatascience.com/how-to-use-deep-learning-for-time-series-forecasting-3f8a399cf205)\n# and the notebook available on\n# [the authors's github](https://github.com/Christophe-pere/Time_series_RNN).\n#\n# We will repeat this study on starlight using the LSTM architecture to predict the observed light flux through time.\n#\n# Our LSTM implementation is based on this [notebook from Haiku's github repository](https://github.com/deepmind/dm-haiku/blob/master/examples/haiku_lstms.ipynb).\n#\n# We'll see how to use WAX-ML to ease the preparation of time series data stored in dataframes and having Nans\n# before calling a \"standard\" deep-learning workflow.\n#\n# ## Disclaimer\n#\n# Despite the fact that this code works with real data, the results presented here should not be considered as scientific knowledge insights, to the knowledge of the authors of WAX-ML, neither the results nor the data source have been reviewed by an astrophysics pair.\n#\n# The purpose of this notebook is only to demonstrate how WAX-ML can be used when applying a \"standard\" machine learning workflow, here LSTM, to analyze time series.\n\n# ## Download the data\n\nregister_wax_accessors()\n\n# + tags=[\"parameters\"]\n# Parameters\nSTAR = \"007609553\"\nSEQ_LEN = 64\nBATCH_SIZE = 8\nTRAIN_SIZE = 2 ** 16\nNUM_EPOCHS = 10\nNUM_STARS = None\nRECORD_FREQ = 100\nTOTAL_LEN = None\nTRAIN_DATE = \"2016\"\nCACHE_DIR = Path(\"./cached_data/\")\n# -\n\n# %%time\nfilename = CACHE_DIR / \"kep_lightcurves.parquet\"\ntry:\n raw_dataframe = pd.read_parquet(open(filename, \"rb\"))\n print(f\"data read from {filename}\")\nexcept FileNotFoundError:\n # Downloading the csv file from Chrustioge Pere GitHub account\n download = requests.get(\n \"https://raw.github.com/Christophe-pere/Time_series_RNN/master/kep_lightcurves.csv\"\n ).content\n raw_dataframe = pd.read_csv(io.StringIO(download.decode(\"utf-8\")))\n # set date index\n raw_dataframe.index = pd.Index(\n pd.date_range(\"2009-03-07\", periods=len(raw_dataframe.index), freq=\"h\"),\n name=\"time\",\n )\n # save dataframe locally in CACHE_DIR\n CACHE_DIR.mkdir(exist_ok=True)\n raw_dataframe.to_parquet(filename)\n print(f\"data saved in {filename}\")\n\n\n# shortening of data to speed up the execution of the notebook in the CI\nif TOTAL_LEN:\n raw_dataframe = raw_dataframe.iloc[:TOTAL_LEN]\n\n\n# Let's visualize the description of this dataset:\n\nraw_dataframe.describe().T.to_xarray()\n\n\nstars = raw_dataframe.columns\nstars = sorted(list(set([i.split(\"_\")[0] for i in stars])))\nprint(f\"The number of stars available is: {len(stars)}\")\nprint(f\"star identifiers: {stars}\")\n\ndataframe = raw_dataframe[[i + \"_rscl\" for i in stars]].rename(\n columns=lambda c: c.replace(\"_rscl\", \"\")\n)\ndataframe.columns.names = [\"star\"]\ndataframe.shape\n\nif NUM_STARS:\n columns = dataframe.columns.tolist()\n columns.remove(STAR)\n dataframe = dataframe[[STAR] + columns[: NUM_STARS - 1]]\n\n# ## Rolling mean\n\n# We will smooth the data by applying a rolling mean with a window of 100 periods.\n\n# ### Count nan values\n#\n# But before since the dataset has some nan values, we will extract few statistics\n# about the density of nan values in windows of size 100.\n#\n# It will be the occasion to show a usage of the `wax.modules.Buffer` module with the `format_outputs=False`\n# option for the dataframe accessor `.wax.stream`.\n\n\n# Let's apply the `Buffer` module to the data:\n\nbuffer, _ = dataframe.wax.stream(format_outputs=False).apply(lambda x: Buffer(100)(x))\n\nassert isinstance(buffer, jnp.ndarray)\n\n# Equivalently, we can use wax `unroll` function.\n\n\nbuffer = unroll(lambda x: Buffer(100)(x))(jax.device_put(dataframe.values))\n\n# Let's describe the statistic of nans with pandas:\n\ncount_nan = jnp.isnan(buffer).sum(axis=1)\npd.DataFrame(onp.array(count_nan)).stack().describe().astype(int)\n\n# ### Computing the rolling mean\n\n# We will choose a `min_periods` of 5 in order to keep at leas 75% of the points.\n\n# %%time\ndataframe_mean, _ = dataframe.wax.stream().apply(\n lambda x: RollingMean(100, min_periods=5)(x)\n)\n\ndataframe.iloc[:, :2].plot()\n\n# ## Forecasting with Machine Learning\n#\n# We need two forecast in this data, if you look with attention you'll see micro holes and big holes.\n\n\nT = TypeVar(\"T\")\n\n\nclass Pair(NamedTuple):\n x: T\n y: T\n\n\nclass TrainSplit(NamedTuple):\n train: T\n validation: T\n\n\ngg.theme_set(gg.theme_bw())\nwarnings.filterwarnings(\"ignore\")\n\n\nplt.rcParams[\"figure.figsize\"] = 18, 8\nfig, (ax, lax) = plt.subplots(ncols=2, gridspec_kw={\"width_ratios\": [4, 1]})\ndataframe.plot(ax=ax, title=\"raw data\")\nax.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=lax.transAxes)\nlax.axis(\"off\")\n\n\nplt.rcParams[\"figure.figsize\"] = 18, 8\nfig, (ax, lax) = plt.subplots(ncols=2, gridspec_kw={\"width_ratios\": [4, 1]})\ndataframe_mean.plot(ax=ax, title=\"Smoothed data\")\nax.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=lax.transAxes)\nlax.axis(\"off\")\n# -\n\n# ### Normalize data\n\ndataframe_mean.stack().hist(bins=100, log=True)\n\n\ndef min_max_scaler(values: pd.DataFrame, output_format: str = \"dataframe\") -> Encoder:\n scaler = MinMaxScaler(feature_range=(0, 1))\n scaler.fit(values)\n index = values.index\n columns = values.columns\n\n def encode(dataframe: pd.DataFrame):\n nonlocal index\n nonlocal columns\n\n index = dataframe.index\n columns = dataframe.columns\n array_normed = scaler.transform(dataframe)\n\n if output_format == \"dataframe\":\n return pd.DataFrame(array_normed, index, columns)\n elif output_format == \"jax\":\n return jnp.array(array_normed)\n else:\n return array_normed\n\n def decode(array_scaled):\n\n value = scaler.inverse_transform(array_scaled)\n\n if output_format == \"dataframe\":\n return pd.DataFrame(value, index, columns)\n else:\n return value\n\n return Encoder(encode, decode)\n\n\n# -\n\nscaler = min_max_scaler(dataframe_mean)\ndataframe_normed = scaler.encode(dataframe_mean)\nassert (scaler.decode(dataframe_normed) - dataframe_mean).stack().abs().max() < 1.0e-4\n\ndataframe_normed.stack().hist(bins=100)\n\n# ### Prepare train / validation datasets\n\n\ndef split_feature_target(\n dataframe,\n look_back=SEQ_LEN,\n shuffle=True,\n stack=True,\n min_periods_ratio: float = 0.8,\n rng=None,\n) -> Pair:\n def prepare_xy(data):\n buffer = Buffer(look_back + 1)(data)\n x = buffer[:-1]\n y = buffer[-1]\n return x, y\n\n def prepare_xy(data):\n y = Buffer(look_back)(data)\n x = Lag(1)(y)\n return x, y\n\n x, y = unroll(prepare_xy)(jax.device_put(dataframe.values))\n\n if shuffle:\n if rng is None:\n rng = jax.random.PRNGKey(42)\n\n B = x.shape[0]\n idx = jnp.arange(B)\n idx = jax.random.shuffle(rng, idx)\n\n x = x[idx]\n y = y[idx]\n\n if stack:\n B, T, F = x.shape\n x = x.transpose(1, 0, 2).reshape(T, B * F, 1).transpose(1, 0, 2)\n y = y.transpose(1, 0, 2).reshape(T, B * F, 1).transpose(1, 0, 2)\n\n if min_periods_ratio:\n T = x.shape[1]\n count_nan = jnp.isnan(x).sum(axis=1)\n mask = count_nan < min_periods_ratio * T\n idx = jnp.where(mask)\n x = x[idx[0]]\n y = y[idx[0]]\n\n # round Batch size to a power of to\n B = x.shape[0]\n B_round = int(2 ** jnp.floor(jnp.log2(B)))\n print(f\"{B} batches rounded to {B_round} batches.\")\n x = x[:B_round]\n y = y[:B_round]\n\n # fillnan by zeros\n x, y = hk.testing.transform_and_run(lambda x: FillNanInf()(x))((x, y))\n\n return Pair(x, y)\n\n\n# +\n# split_feature_target(dataframe)\n# -\n\n\ndef split_train_validation(\n dataframe, train_size, look_back, scaler: Optional[Callable] = None\n) -> TrainSplit:\n\n # prepare scaler\n train_df = dataframe.iloc[:train_size]\n\n if scaler:\n scaler = scaler(train_df)\n\n # prepare train data\n if scaler:\n train_df = scaler.encode(train_df)\n\n train_xy = split_feature_target(train_df, look_back)\n\n # prepare validation data\n valid_size = len(dataframe) - train_size\n valid_size = int(2 ** jnp.floor(jnp.log2(valid_size)))\n\n valid_end = int(train_size + valid_size)\n valid_df = dataframe.iloc[train_size:valid_end]\n\n if scaler:\n valid_df = scaler.encode(valid_df)\n\n valid_xy = split_feature_target(valid_df, look_back)\n\n return TrainSplit(train_xy, valid_xy)\n\n\nTRAIN_SIZE\n\nprint(f\"Look at star: {STAR}\")\ntrain, valid = split_train_validation(dataframe_normed[[STAR]], TRAIN_SIZE, SEQ_LEN)\n\ntrain[0].shape, train[1].shape, valid[0].shape, valid[1].shape\n\n# TRAIN_SIZE, VALID_SIZE = len(train.x), len(valid.x)\nprint(\n f\"effective train_size = {len(train.x)}, \" f\"effective valid size= {len(valid.x)}\"\n)\n\n\n# Plot an observation/target pair.\nrng = jax.random.PRNGKey(42)\nbatch_plot = jax.random.choice(rng, len(train[0]))\ndf = pd.DataFrame(\n {\"x\": train.x[batch_plot, :, 0], \"y\": train.y[batch_plot, :, 0]}\n).reset_index()\ndf = pd.melt(df, id_vars=[\"index\"], value_vars=[\"x\", \"y\"])\nplot = (\n gg.ggplot(df)\n + gg.aes(x=\"index\", y=\"value\", color=\"variable\")\n + gg.geom_line()\n + gg.scales.scale_y_log10()\n)\n_ = plot.draw()\n\n\n# ### Dataset iterator\n\n\nclass Dataset:\n \"\"\"An iterator over a numpy array, revealing batch_size elements at a time.\"\"\"\n\n def __init__(self, xy: Pair, batch_size: int):\n self._x, self._y = xy\n self._batch_size = batch_size\n self._length = self._x.shape[0]\n self._idx = 0\n if self._length % batch_size != 0:\n msg = \"dataset size {} must be divisible by batch_size {}.\"\n raise ValueError(msg.format(self._length, batch_size))\n\n def __next__(self) -> Pair:\n start = self._idx\n end = start + self._batch_size\n x, y = self._x[start:end], self._y[start:end]\n if end >= self._length:\n print(f\"End of the data set (size={end}). Return to the beginning.\")\n end = end % self._length\n assert end == 0 # Guaranteed by ctor assertion.\n self._idx = end\n return Pair(x, y)\n\n\n# + [markdown] colab_type=\"text\" id=\"LZGw5Jdvjmqh\"\n# ### Training an LSTM\n#\n# To train the LSTM, we define a Haiku function which unrolls the LSTM over the input sequence, generating predictions for all output values. The LSTM always starts with its initial state at the start of the sequence.\n#\n# The Haiku function is then transformed into a pure function through `hk.transform`, and is trained with Adam on an L2 prediction loss.\n\n\n# + colab={} colab_type=\"code\" id=\"nacnTj5ejIK5\"\ndef unroll_net(seqs: jnp.ndarray):\n \"\"\"Unrolls an LSTM over seqs, mapping each output to a scalar.\"\"\"\n # seqs is [T, B, F].\n core = hk.LSTM(32)\n batch_size = seqs.shape[0]\n outs, state = hk.dynamic_unroll(\n core, seqs, core.initial_state(batch_size), time_major=False\n )\n # We could include this Linear as part of the recurrent core!\n # However, it's more efficient on modern accelerators to run the linear once\n # over the entire sequence than once per sequence element.\n return hk.BatchApply(hk.Linear(1))(outs), state\n\n\n# + colab={} colab_type=\"code\" id=\"nacnTj5ejIK5\"\nmodel = jit_init_apply(hk.transform(unroll_net))\n\n\n# +\n@jax.jit\ndef loss(pred, y):\n return jnp.mean(jnp.square(pred - y))\n\n\ndef model_with_loss(x, y):\n pred, _ = unroll_net(x)\n return loss(pred, y)\n\n\n# + colab={} colab_type=\"code\" id=\"nacnTj5ejIK5\"\nclass TrainState(NamedTuple):\n step: int\n params: Any\n opt_state: Any\n rng: jnp.ndarray\n loss: float\n\n\ndef train_model(\n model_with_loss: Callable,\n train_ds: Dataset,\n valid_ds: Dataset,\n max_iterations: int = -1,\n rng=None,\n record_freq=100,\n) -> hk.Params:\n \"\"\"Initializes and trains a model on train_ds, returning the final params.\"\"\"\n opt = optax.adam(1e-3)\n model_with_loss = jit_init_apply(hk.transform(model_with_loss))\n\n @jax.jit\n def update(train_state, x, y):\n step, params, opt_state, rng, _ = train_state\n if rng is not None:\n (rng,) = jax.random.split(rng, 1)\n l, grads = jax.value_and_grad(model_with_loss.apply)(params, rng, x, y)\n grads, opt_state = opt.update(grads, opt_state)\n params = optax.apply_updates(params, grads)\n return TrainState(step + 1, params, opt_state, rng, l)\n\n # Initialize state.\n def init():\n x, y = next(train_ds)\n params = model_with_loss.init(rng, x, y)\n opt_state = opt.init(params)\n return TrainState(0, params, opt_state, rng, jnp.inf)\n\n def _format_results(records):\n records = {key: jnp.stack(l) for key, l in records.items()}\n return records\n\n records = defaultdict(list)\n train_state = init()\n with tqdm(total=max_iterations if max_iterations > 0 else None) as pbar:\n while True:\n try:\n x, y = next(train_ds)\n except StopIteration:\n return train_state, _format_results(records)\n\n train_state = update(train_state, x, y)\n if train_state.step % record_freq == 0:\n x, y = next(valid_ds)\n if rng is not None:\n (rng,) = jax.random.split(rng, 1)\n valid_loss = model_with_loss.apply(train_state.params, rng, x, y)\n records[\"step\"].append(train_state.step)\n records[\"valid_loss\"].append(valid_loss)\n records[\"train_loss\"].append(train_state.loss)\n\n pbar.update()\n if max_iterations > 0 and train_state.step >= max_iterations:\n return train_state, _format_results(records)\n\n\n# + colab={} colab_type=\"code\" id=\"AssgDctokbl5\"\n# %%time\ntrain, valid = split_train_validation(dataframe_normed[[STAR]], TRAIN_SIZE, SEQ_LEN)\ntrain_ds = Dataset(train, BATCH_SIZE)\nvalid_ds = Dataset(valid, BATCH_SIZE)\n\n\ntrain_state, records = train_model(\n model_with_loss,\n train_ds,\n valid_ds,\n len(train.x) // BATCH_SIZE * NUM_EPOCHS,\n rng=jax.random.PRNGKey(42),\n record_freq=RECORD_FREQ,\n)\n\n# +\n# train_state.params\n# -\n\n# Plot losses\nlosses = pd.DataFrame(records)\ndf = pd.melt(losses, id_vars=[\"step\"], value_vars=[\"train_loss\", \"valid_loss\"])\nplot = (\n gg.ggplot(df)\n + gg.aes(x=\"step\", y=\"value\", color=\"variable\")\n + gg.geom_line()\n + gg.scales.scale_y_log10()\n)\n_ = plot.draw()\n\n\n# + [markdown] colab_type=\"text\" id=\"yr7jrOL3ki-b\"\n# ### Sampling\n#\n# The point of training models is so that they can make predictions! How can we generate predictions with the trained model?\n#\n# If we're allowed to feed in the ground truth, we can just run the original model's `apply` function.\n\n# + colab={} colab_type=\"code\" id=\"f2qETEqXLT1N\"\ndef plot_samples(truth: np.ndarray, prediction: np.ndarray) -> gg.ggplot:\n assert truth.shape == prediction.shape\n df = pd.DataFrame(\n {\"truth\": truth.squeeze(), \"predicted\": prediction.squeeze()}\n ).reset_index()\n df = pd.melt(df, id_vars=[\"index\"], value_vars=[\"truth\", \"predicted\"])\n plot = (\n gg.ggplot(df) + gg.aes(x=\"index\", y=\"value\", color=\"variable\") + gg.geom_line()\n )\n return plot\n\n\n# + colab={} colab_type=\"code\" id=\"KOuK1egilGD0\"\n# Grab a sample from the validation set.\nsample_x, sample_y = next(valid_ds)\nsample_x = sample_x[:1] # Shrink to batch-size 1.\nsample_y = sample_y[:1]\n\n# Generate a prediction, feeding in ground truth at each point as input.\npredicted, _ = model.apply(train_state.params, None, sample_x)\n\nplot = plot_samples(sample_y, predicted)\nplot.draw()\ndel sample_x, predicted\n\n\n# -\n\n# ### Run autoregressively\n\n# + [markdown] colab_type=\"text\" id=\"tDyGshz_lwrM\"\n# If we can't feed in the ground truth (because we don't have it), we can also run the model autoregressively.\n\n# + colab={} colab_type=\"code\" id=\"Cg8oQ75Ulvld\"\ndef autoregressive_predict(\n trained_params: hk.Params,\n context: jnp.ndarray,\n seq_len: int,\n pbar=False,\n):\n \"\"\"Given a context, autoregressively generate the rest of a sine wave.\"\"\"\n\n ar_outs = []\n context = jax.device_put(context)\n times = onp.arange(seq_len - context.shape[1] + 1)\n if pbar:\n times = tqdm(times)\n for _ in times:\n full_context = jnp.concatenate([context] + ar_outs, axis=1)\n\n outs, _ = model.apply(trained_params, None, full_context)\n # Append the newest prediction to ar_outs.\n ar_outs.append(outs[:, -1:, :])\n # Return the final full prediction.\n return outs\n\n\n# + colab={} colab_type=\"code\" id=\"Cg8oQ75Ulvld\"\nsample_x, sample_y = next(valid_ds)\nsample_x = sample_x[:1] # Shrink to batch-size 1.\nsample_y = sample_y[:1] # Shrink to batch-size 1.\n\n\ncontext_length = SEQ_LEN // 8\nprint(f\"context_length = {context_length}\")\n# Cut the batch-size 1 context from the start of the sequence.\ncontext = sample_x[:, :context_length]\n\n# + colab={} colab_type=\"code\" id=\"Cg8oQ75Ulvld\"\n# %%time\n# We can reuse params we got from training for inference - as long as the\n# declaration order is the same.\npredicted = autoregressive_predict(train_state.params, context, SEQ_LEN, pbar=True)\n# -\n\nsample_y.shape, predicted.shape\n\n# + colab={} colab_type=\"code\" id=\"Cg8oQ75Ulvld\"\nplot = plot_samples(sample_y, predicted)\nplot += gg.geom_vline(xintercept=context.shape[1], linetype=\"dashed\")\n_ = plot.draw()\n\n\n# + [markdown] colab_type=\"text\" id=\"qGkr2gf2oALo\"\n# #### Sharing parameters with a different function.\n#\n# Unfortunately, this is a bit slow - we're doing O(N^2) computation for a sequence of length N.\n#\n# It'd be better if we could do the autoregressive sampling all at once - but we need to write a new Haiku function for that.\n#\n# We're in luck - if the Haiku module names match, the same parameters can be used for multiple Haiku functions.\n#\n# This can be achieved through a combination of two techniques:\n#\n# 1. If we manually give a unique name to a module, we can ensure that the parameters are directed to the right places.\n# 2. If modules are instantiated in the same order, they'll have the same names in different functions.\n#\n# Here, we rely on method #2 to create a fast autoregressive prediction.\n\n# + colab_type=\"text\" id=\"qGkr2gf2oALo\"\n@hk.transform\ndef fast_autoregressive_predict_fn(context, seq_len):\n \"\"\"Given a context, autoregressively generate the rest of a sine wave.\"\"\"\n core = hk.LSTM(32)\n dense = hk.Linear(1)\n state = core.initial_state(context.shape[0])\n # Unroll over the context using `hk.dynamic_unroll`.\n # As before, we `hk.BatchApply` the Linear for efficiency.\n context_outs, state = hk.dynamic_unroll(\n core,\n context,\n state,\n time_major=False,\n )\n context_outs = hk.BatchApply(dense)(context_outs)\n\n # Now, unroll one step at a time using the running recurrent state.\n ar_outs = []\n x = context_outs[:, -1, :]\n times = range(seq_len - context.shape[1])\n for _ in times:\n x, state = core(x, state)\n x = dense(x)\n ar_outs.append(x)\n ar_outs = jnp.stack(ar_outs)\n ar_outs = ar_outs.transpose(1, 0, 2)\n return jnp.concatenate([context_outs, ar_outs], axis=1)\n\n\nfast_autoregressive_predict = jax.jit(\n fast_autoregressive_predict_fn.apply, static_argnums=(3,)\n)\n\n# + colab={} colab_type=\"code\" id=\"WdKcHr6_n_ba\"\n# %%time\n# Reuse the same context from the previous cell.\npredicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN)\n\n\n# + colab={} colab_type=\"code\" id=\"WdKcHr6_n_ba\"\n# The plots should be equivalent!\nplot = plot_samples(sample_y, predicted)\nplot += gg.geom_vline(xintercept=context.shape[1], linetype=\"dashed\")\n_ = plot.draw()\n# -\n\n\n# # Sample trajectories\n\n# + colab={} colab_type=\"code\" id=\"WdKcHr6_n_ba\"\nsample_x, sample_y = next(valid_ds)\nsample_x = sample_x[:1] # Shrink to batch-size 1.\nsample_y = sample_y[:1] # Shrink to batch-size 1.\n\n\ncontext_length = SEQ_LEN // 8\nprint(f\"context_length = {context_length}\")\n# Cut the batch-size 1 context from the start of the sequence.\ncontext = sample_x[:, :context_length]\n\n# Reuse the same context from the previous cell.\npredicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN)\n\n# The plots should be equivalent!\nplot = plot_samples(sample_y, predicted)\nplot += gg.geom_vline(xintercept=context.shape[1], linetype=\"dashed\")\n_ = plot.draw()\n# -\n\n\n# ## timeit\n\n# + colab={} colab_type=\"code\" id=\"9S0tkPXGrU3a\"\n# %timeit autoregressive_predict(train_state.params, context, SEQ_LEN)\n# %timeit fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN)\n# -\n# ## Train all stars\n\n\n# ### Training\n\n\ndef split_train_validation_date(dataframe, date, look_back) -> TrainSplit:\n train_size = len(dataframe.loc[:date])\n return split_train_validation(dataframe, train_size, look_back)\n\n\n# %%time\ntrain, valid = split_train_validation_date(dataframe_normed, TRAIN_DATE, SEQ_LEN)\nprint(f\"effective train size = {train[0].shape[1]}\")\n\ntrain[0].shape, train[1].shape, valid[0].shape, valid[1].shape\n\ntrain_ds = Dataset(train, BATCH_SIZE)\nvalid_ds = Dataset(valid, BATCH_SIZE)\n# del train, valid # Don't leak temporaries.\n\n# %%time\ntrain_state, records = train_model(\n model_with_loss,\n train_ds,\n valid_ds,\n len(train.x) // BATCH_SIZE * 1,\n jax.random.PRNGKey(42),\n record_freq=RECORD_FREQ,\n)\n\n# Plot losses\nlosses = pd.DataFrame(records)\ndf = pd.melt(losses, id_vars=[\"step\"], value_vars=[\"train_loss\", \"valid_loss\"])\nplot = (\n gg.ggplot(df)\n + gg.aes(x=\"step\", y=\"value\", color=\"variable\")\n + gg.geom_line()\n + gg.scales.scale_y_log10()\n)\n_ = plot.draw()\n\n# ### Sampling\n\n# +\n# Grab a sample from the validation set.\nsample_x, sample_y = next(valid_ds)\nsample_x = sample_x[:1] # Shrink to batch-size 1.\nsample_y = sample_y[:1] # Shrink to batch-size 1.\n\n\n# Generate a prediction, feeding in ground truth at each point as input.\npredicted, _ = model.apply(train_state.params, None, sample_x)\n\nplot = plot_samples(sample_y, predicted)\n_ = plot.draw()\n# -\n\n# ### Run autoregressively\n\n# +\n# %%time\nsample_x, sample_y = next(valid_ds)\nsample_x = sample_x[:1] # Shrink to batch-size 1.\nsample_y = sample_y[:1] # Shrink to batch-size 1.\n\n\ncontext_length = SEQ_LEN // 8\n# Cut the batch-size 1 context from the start of the sequence.\ncontext = sample_x[:, :context_length]\n\n# Reuse the same context from the previous cell.\npredicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN)\n\n# The plots should be equivalent!\nplot = plot_samples(sample_y, predicted)\nplot += gg.geom_vline(xintercept=len(context), linetype=\"dashed\")\n_ = plot.draw()\n", "meta": {"hexsha": "fef2dbdf7939029991a9ebb80a5192eda981285e", "size": 24234, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/notebooks/05_reconstructing_the_light_curve_of_stars.py", "max_stars_repo_name": "eserie/wax-ml", "max_stars_repo_head_hexsha": "9cf92ff5c41ea681fd3eaaf4560b3380f986ee1e", "max_stars_repo_licenses": ["MIT", "ECL-2.0", "Apache-2.0", "BSD-3-Clause"], "max_stars_count": 42, "max_stars_repo_stars_event_min_datetime": "2021-06-14T16:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:51:42.000Z", "max_issues_repo_path": "docs/notebooks/05_reconstructing_the_light_curve_of_stars.py", "max_issues_repo_name": "eserie/wax-ml", "max_issues_repo_head_hexsha": "9cf92ff5c41ea681fd3eaaf4560b3380f986ee1e", "max_issues_repo_licenses": ["MIT", "ECL-2.0", "Apache-2.0", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-10-01T12:45:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T18:06:39.000Z", "max_forks_repo_path": "docs/notebooks/05_reconstructing_the_light_curve_of_stars.py", "max_forks_repo_name": "eserie/wax-ml", "max_forks_repo_head_hexsha": "9cf92ff5c41ea681fd3eaaf4560b3380f986ee1e", "max_forks_repo_licenses": ["MIT", "ECL-2.0", "Apache-2.0", "BSD-3-Clause"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-06-11T12:32:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T16:13:15.000Z", "avg_line_length": 29.6621787026, "max_line_length": 268, "alphanum_fraction": 0.6829660807, "include": true, "reason": "import numpy,import jax", "num_tokens": 6517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.19930799790404563, "lm_q1q2_score": 0.09731878592620251}} {"text": "import os\nfrom sympy import *\nimport pandas as pd\nimport numpy as np\nimport scipy.fftpack\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn-paper\")\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n\ndef find_nearest_value(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return array[idx]\n\n\n# ## Canvas palette\n\n# In[2]:\n\n\n#Canvas for single plot\nx = np.linspace(0,10,100)\ny = np.sin(x)\nplt.figure(figsize=[14,6])\nplt.grid(True)\nplt.title(\"Change-me!\",fontsize=20)\nplt.plot(x,y,label=\"testvalue\")\nplt.legend(fontsize=16)\nplt.xlabel(\"XLABEL (unit)\",fontsize=18)\nplt.ylabel(\"YLABEL (unit)\",fontsize=18)\nplt.show()\n\n\n# In[3]:\n\n\n#Canvas for side by side\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,6))\nfig.suptitle(\"test\",y=1.05,fontsize=20)\n\naxes[0].grid(True)\naxes[0].plot(x,y,label=\"testvalue\")\naxes[0].legend(fontsize=16)\naxes[0].set_title(\"TESTTITLE\",fontsize=18)\naxes[0].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0].legend(fontsize=16)\naxes[0].tick_params(axis='both', which='major', labelsize=15)\n\n\naxes[1].grid(True)\naxes[1].plot(x,y,label=\"testvalue\")\naxes[1].legend(fontsize=16)\naxes[1].set_title(\"TESTTITLE\",fontsize=18)\naxes[1].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[1].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[1].legend(fontsize=16)\naxes[1].tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.show()\n\n\n# In[4]:\n\n\n#Canvas for side by side\nfig, axes = plt.subplots(nrows=2, ncols=4, figsize=(14,6))\nfig.suptitle(\"test\",y=1.05,fontsize=20)\n\naxes[0,0].grid(True)\naxes[0,0].plot(x,y,label=\"testvalue\")\naxes[0,0].legend(fontsize=16)\naxes[0,0].set_title(\"TESTTITLE\",fontsize=18)\naxes[0,0].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0,0].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0,0].legend(fontsize=16)\naxes[0,0].tick_params(axis='both', which='major', labelsize=15)\n\n\naxes[0,1].grid(True)\naxes[0,1].plot(x,y,label=\"testvalue\")\naxes[0,1].legend(fontsize=16)\naxes[0,1].set_title(\"TESTTITLE\",fontsize=18)\naxes[0,1].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0,1].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0,1].legend(fontsize=16)\naxes[0,1].tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.show()\n\n\n# ## Read data\n\n# In[2]:\n\n\n#Folder and paths definitions\nmain_path = os.getcwd()\ndatafolder_path = main_path+\"/results\"\nresults_dir = \"/output_py\" \noutput_dir = main_path+results_dir\ntry:\n os.mkdir(output_dir)\nexcept OSError:\n print (\"Creation of the directory %s failed\" % results_dir)\nelse:\n print (\"Successfully created the directory %s \" % results_dir)\n\n\n# In[27]:\n\n\nKvalues = np.linspace(0,6,30)\nKvalues = np.around(Kvalues, decimals=3)\n\n\n# In[28]:\n\n\npvalues = [0, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, .95, 1]\n\n\n# In[9]:\n\n\n#Create dataframe dictionary. For each entry, first value is the K of the dataframe (second value)\ndata = []\nfor i in range(0,len(Kvalues)):\n for j in pvalues:\n filename = datafolder_path + \"/WS_gfreq_uphase_N2000_NOMF_T20000_dt0.0100_nruns10_K%.3f_p=%.3f.tsv\"%(Kvalues[i],j)\n #cols refers to timestep, avgmod, stdmod, avgphase,stdphase (of order parameter)\n df = pd.read_csv(filename,sep=\"\\t\",header=None)\n data.append([Kvalues[i],j,df])\n \n\n\n# In[10]:\n\n\n#data[0][x]#, x=0=> K, x=1=>p, x=2=> df \n\n\n# In[11]:\n\n\ndef rinf_avg(df):\n lasts = df[1][int(T*.9):-1]\n return np.mean(lasts)\n\ndef rinf_std(df):\n lasts = df[1][int(T*.9):-1]\n return np.std(lasts)\n\n\n# In[12]:\n\n\nK_plot = []\np_plot = []\nr_inf_avg = []\nr_inf_std = []\nfor i in range(0,len(data)):\n t_plot = data[i][2][0]\n K_plot.append(data[i][0])\n p_plot.append(data[i][1])\n r_inf_avg.append(rinf_avg(data[i][2]))\n r_inf_std.append(rinf_std(data[i][2]))\n\n\n# In[29]:\n\n\nr_inf_mat = np.zeros(shape=[len(pvalues),len(Kvalues)])\nfor i in range(0,len(data)):\n r_inf_mat[find_nearest(pvalues, data[i][1])][find_nearest(Kvalues, data[i][0])] = rinf_avg(data[i][2])\n\nplt.figure(figsize=[10,10])\nax = plt.gca()\n#name = \"Kuramoto oscillators on Watts-Strogatz network \\n N = %d, r = %d, dt = %.3f, %s, n_runs = %d\\n$r_{\\\\infty}$\"%(N,2,dt,freq_plot, n_runs)\n\nim = plt.imshow(r_inf_mat)\nplt.title(\"Kuramoto oscillators on Watts-Strogatz network\\n N=%d, $r_{WS}$=%d, T=%d, dt=%.3f, %s, n_runs=%d\\n $r_{\\\\infty}$\"%(N,3,T,dt,freq_plot,n_runs),fontsize=20)\n\nplt.yticks(np.linspace(0,len(pvalues)-1,len(pvalues)),pvalues)\nplt.ylabel(\"p\",fontsize=18,rotation=0)\nplt.xticks(np.linspace(0,len(Kvalues)-1,len(Kvalues)),Kvalues,rotation=45)\nplt.xlabel(\"K\",fontsize=18)\n\ndivider = make_axes_locatable(ax)\ncax = divider.append_axes(\"right\", size=\"5%\", pad=0.15)\ncbar = plt.colorbar(im, cax=cax)\n\nplt.tight_layout()\nplt.savefig(output_dir+config_name+\"WS_rinf_heatmap.png\")\n\nplt.show()\n\n\n# In[14]:\n\n\nKcs_df = pd.DataFrame([p_plot,K_plot,r_inf_avg,r_inf_std]).T\n\n\n# In[15]:\n\n\nKcs_df = Kcs_df.sort_values(by=[0,1])\n\n\n# In[31]:\n\n\nKc_plot = []\n\nfor i in range(0,len(pvalues)):\n\n idx_kc = find_nearest(Kcs_df[0+i*len(Kvalues)+1:len(Kvalues)*(i+1)][2],.5)\n rinf_value = find_nearest_value(Kcs_df[0+i*len(Kvalues)+1:len(Kvalues)*(i+1)][2],.5)\n df = Kcs_df[0+i*len(Kvalues)+1:len(Kvalues)*(i+1)]\n df = df.reset_index(inplace = False) \n Kc_plot.append([pvalues[i],df[1].iloc[idx_kc]])\n print(\"prob\",pvalues[i],\", rinf %.3f\"%(rinf_value),\", K\",df[1].iloc[idx_kc])\nKc_plot = pd.DataFrame(Kc_plot, columns=[\"p\",\"Kc\"])\n\n\n# In[54]:\n\n\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\n\n# In[55]:\n\n\ndef func(x, a, b):\n return a+ b/x\n\n\n# In[66]:\n\n\npopt, pcov = curve_fit(func, Kc_plot[\"p\"][2:],Kc_plot[\"Kc\"][2:], p0=[1.6,2])\npopt\n\n\n# In[70]:\n\n\nx_fit = np.linspace(Kc_plot[\"p\"][2],1,100)\ny_fit = func(x_fit,popt[0],popt[1])\n\n\n# In[94]:\n\n\nplt.figure(figsize=[14,6])\nplt.grid(True,alpha=.3)\nplt.title(\"Kuramoto oscillators on Watts-Strogatz network\\n N=%d, $r_{WS}$=%d, T=%d, dt=%.3f, %s, n_runs=%d\\n $K_{c}(p)$\"%(N,3,T,dt,freq_plot,n_runs),fontsize=20)\nplt.plot(x_fit,y_fit,label=\"y(p) = a + $\\\\frac{b}{p}$ fit\")\nplt.plot(Kc_plot[\"p\"],Kc_plot[\"Kc\"],c='b',marker='o',markersize=12,ls='',label=\"Raw Data\")\nplt.plot(Kc_plot[\"p\"][2:],Kc_plot[\"Kc\"][2:],c='r',marker='o',markersize=9,ls='--',linewidth=.7,label=\"Fitted Data\")\nplt.xticks(pvalues,pvalues)\nplt.xlabel(\"p\",fontsize=18,rotation=0)\nplt.yticks(Kvalues,Kvalues)\nplt.ylim(min(Kc_plot[\"Kc\"])*.85,max(Kc_plot[\"Kc\"])*1.1)\nplt.legend(fontsize=18)\n\nplt.text(.5,4,\"a = %.4f$\\pm$%.4f, b = %.4f$\\pm$%.4f\"%(popt[0],pcov[0,0],popt[1],pcov[1,1]),fontsize=20)\n\nplt.tight_layout()\nplt.savefig(output_dir+config_name+\"WS_Kc(p).png\")\n\n\n\n", "meta": {"hexsha": "9291ed9a698a559b269652879dc8307a8cf2d385", "size": 6775, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/Python/Bonus_part/WS_analysis.py", "max_stars_repo_name": "spicella/Intro_to_ComplexSystems-Kuramoto", "max_stars_repo_head_hexsha": "64c027f1f0d16b2358d6889de453c1474d3dea6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-01-04T22:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-04T22:36:10.000Z", "max_issues_repo_path": "Code/Python/Bonus_part/WS_analysis.py", "max_issues_repo_name": "spicella/Intro_to_ComplexSystems-Kuramoto", "max_issues_repo_head_hexsha": "64c027f1f0d16b2358d6889de453c1474d3dea6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-01-01T16:13:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-01T16:13:24.000Z", "max_forks_repo_path": "Code/Python/Bonus_part/WS_analysis.py", "max_forks_repo_name": "spicella/IntroCS-Kuramoto", "max_forks_repo_head_hexsha": "64c027f1f0d16b2358d6889de453c1474d3dea6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.606271777, "max_line_length": 165, "alphanum_fraction": 0.6701107011, "include": true, "reason": "import numpy,import scipy,from scipy,from sympy", "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.19682620128743877, "lm_q1q2_score": 0.09610696584781199}} {"text": "# coding:utf-8\n# usr/bin/python3\n# python src/chapter32/chapter32note.py\n# python3 src/chapter32/chapter32note.py\n\"\"\"\n\nClass Chapter32_1\n\nClass Chapter32_2\n\nClass Chapter32_3\n\nClass Chapter32_4\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport math\nimport re\nimport numpy as np\n\nif __name__ == '__main__':\n import stringmatch as sm\nelse:\n from . import stringmatch as sm\n\nclass Chapter32_1:\n \"\"\"\n chapter32.1 note and function\n \"\"\"\n def __init__(self):\n pass\n\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter32.1 note\n\n Example\n ====\n ```python\n Chapter32_1().note()\n ```\n \"\"\"\n print('chapter32.1 note as follow')\n print('第32章 字符串匹配')\n print('在文本编辑程序中,经常出现要在一段文本中找出某个模式的全部出现位置这一问题。典型情况是,一段文本是正在编辑的文件,',\n '所搜寻的模式是用户提供的一个特定单词。解决这个问题的有效算法能极大地提高文本编辑程序的响应性能',\n '字符串匹配算法也常常用于其他方面,例如在DNA序列中搜寻特定的模式')\n print('字符串匹配问题的形式定义是这样的:假设文本是一个长度为n的数组T[1..n],模式是一个长度为m<=n的数组P[1..m].',\n '进一步假设P和T的元素都是属于有限字母表∑表中的字符.例如可以有∑={0,1}或∑={a,b,...,z},字符数组P和T常称为字符串')\n print('如果0<=s<=n-m,并且T[S+1,...,s+m]=P[1..m](即对1<=j<=m,有T[s+j]=P[j]),则说模式P在文本T中出现且位移为s.',\n '(或者等价地,模式P在文本T中从位置s+1开始出现)。如果P在T中出现且位移为s,则称s为一个有效位移,否则称s为无效位移',\n '这样一来,字符串匹配问题就变成一个在一段指定的文本T中,找出某指定模式P出现所有有效位移的问题')\n print('本章的每个字符串匹配算法都对模式进行了一些预处理,然后找寻所有有效位移;我们称第二步为“匹配”.',\n '每个算法的总运行时间为预处理和匹配时间的总和.')\n print('32.2节介绍由Rabin和Karp发现的一种有趣的字符串匹配算法,该算法在最坏情况下的运行时间为Θ((n-m+1)m),虽然这一时间并不比朴素的算法好',\n '但是在平均情况和实际情况中,该算法的效果要好的多.这种算法也可以很好地推广到解决其他的模式匹配问题')\n print('32.3节中描述另一种字符串匹配算法,该算法构造一个特别设计的有限自动机,用来搜寻某给定模式P在文本中的出现的位置',\n '此算法用O(m|∑|)的预处理时间,但只用Θ(n)的匹配时间')\n print('32.4节介绍与其类似但更巧妙的Knuth-Morris-Pratt(或KMP)算法。该算法的匹配时间同样为Θ(n),但是将预处理时间降至Θ(m)')\n print('算法 预处理时间 匹配时间')\n print('朴素算法 0 O((n-m+1)m)')\n print('Rabin-Karp Θ(m) O((n-m+1)m)')\n print('有限自动机算法 O(m|∑|) Θ(n)')\n print('KMP算法 Θ(m) Θ(n)')\n print('记号与术语')\n print(' 用∑*表示用字母表∑中的字符形成的所有有限长度的字符串的集合.在本章中仅考虑长度有限的字符串',\n '长度为0的空字符串用e表示,它也属于∑*.字符串x的长度用|x|表示.两个字符串x和y的连接表示为xy,其长度为|x|+|y|,由x的字符接y的字符组成')\n print(' 如果对某个字符串与y∈∑*,有x=wy,就说字符串w是字符串x的前缀,表示为w∝x,得知|w|<=|x|.空字符串e既是每个字符串的前缀,也是每个字符串的后缀',\n '例如,有ab>abcca,ccay当且仅当xa>ya.注意>和<都是传递关系')\n print('引理32.1(重叠后缀定理)假设x,y和z是满足x>z和yy;如果|x|>=|y|,则y>x;如果|x|=|y|,则x=y')\n print(' 本章中允许把比较两个等长的字符串是否相等的操作当做原语操作.如果对字符串的比较是从左往右进行,并且发现一个不匹配字符时比较就终止,',\n '则假设这样一个测试过程所需的时间是关于所发现的匹配字符数目的线性函数')\n print('32.1 朴素的字符串匹配算法')\n print('朴素的字符串匹配算法:它用一个循环来找出所有有效位移,该循环对n-m+1可能的每一个s值检查条件P[1..m]=T[s+1..s+m]')\n print('这种朴素的字符串匹配过程可以形象地看成用一个包含模式的“模板”沿文本滑动,同时对每个位移注意模板上的字符是否与文本的相应字符相等')\n print('NATIVE-STRING-MATCHER的运行时间为Θ((m-m+1)m)')\n print('在本章中还要介绍一种算法,它的最坏情况预处理时间为Θ(m),最坏情况匹配时间为Θ(n)')\n print('练习31.1-1 解答过程如下:')\n P = '0001'\n T = '000010001010001'\n sm.native_string_matcher(T, P)\n print('练习31.1-2 假设模式P中的所有字符都是不同的。试说明如何对一段n个字符的文本T加速过程NATIVE-STRING-MATCHER的执行速度,',\n '使其运行时间达到O(n)')\n print('练习31.1-3 假设模式P和文本T是长度分别为m和n的随机选取的字符串,其字符串属于d个元素的字母表∑={0,1,...,d-1},其中d>=2',\n '证明朴素算法第4行中隐含的循环所执行的字符比较的预计次数为')\n print(' (n-m+1)(1-d**-m)/(1-d**-1)<=2(n-m+1)')\n print('练习31.1-4 假设允许模式P中包含一个间隔字符◇,该字符可以与任意的字符串匹配(甚至可以与长度为0的字符串匹配)',\n '例如,模式ab◇ba◇c')\n # python src/chapter32/chapter32note.py\n # python3 src/chapter32/chapter32note.py\n\nclass Chapter32_2:\n \"\"\"\n chapter32.2 note and function\n \"\"\"\n def __init__(self):\n pass\n\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter32.2 note\n\n Example\n ====\n ```python\n Chapter32_2().note()\n ```\n \"\"\"\n print('chapter32.2 note as follow')\n print('Rabin-Karp算法')\n print('在实际应用中,Rabin和Karp所建议的字符串匹配算法能够较好的运行,我们还可以从中归纳出有关问题的其他算法,如二维模式匹配')\n print('Rabin-Karp算法预处理时间为')\n print('Θ(m),在最坏情况下的运行时间为O((n-m+1)m),但是它的平均情况运行时间还是比较好的')\n print('假定∑={0,1,2,...,9},这样每个字符都是一个十进制数字(一般情况下,可以假定每个字符都是基数为d的表示法中一个数字,d=|∑|).',\n '可以用一个长度为k的十进制数来表示由k个连续字符组成的字符串.因此,字符串31415就对应于十进制数31415',\n '如果输入字符既可以看做图形符号,也可以看做数字')\n print('已知一个模式P[1..m],设p表示其相应的十进制数的值。对于给定的文本T[1..n],用ts来表示其长度为m的子字符串T[s+1..s+m](s=0,1,...,n - m)相应的十进制数的值')\n print('当然,用ts来表示其长度为m的子字符串T[s+1..s+m](s=0,1,..,n-m)相应十进制数的值.当然,ts=p当且仅当T[s+1..s+m]=P[1..m],因此s是有效位移当且仅当ts=p',\n '如果能够在Θ(m)的时间内计算出p的值,并在总共Θ(n-m+1)的时间内计算出所有ts的值,那么通过把p值与每个ts值进行比较,能够在Θ(n)的时间内,求出有效位移s')\n print('可以运用霍纳法则,在Θ(m)的时间内计算出p的值:')\n print(' p=P[m]+10(P[m-1]+10(P[m-2]+...+10(P[2]+10P[1])...))')\n print('类似地,也可以在Θ(m)的时间内,根据T[1..m]计算出t0的值')\n print('为了在Θ(n-m)的时间内计算出剩余的值t1,t2,...,tn-m,可以在常数时间内根据ts计算出ts+1,这是因为霍纳法则')\n print('RABIN-KARP-MATCHER的预处理时间Θ(m),其匹配时间在最坏情况下为Θ((n-m+1)m),因为Rabin-Karp算法与朴素的字符串匹配算法一样,对每个有效位移进行显示验证',\n '如果P=a^m并且T=a^n,则验证所需的时间为Θ((n-m+1)m),因为n-m+1可能的位移中每一个都是有效位移')\n print('在许多实际作用中,有效位移数很少(如只有常数c个),因此,算法的期望匹配时间为O((n-m+1)+cm)=O(n+m),',\n '再加上处理伪命中点所需的时间.假设减少模q的值就像是从∑*到Zq上的一个随机映射,基于这种假设,进行启发性分析',\n '要正式证明这个假设是比较困难的,但是有一种可行的方法,就是假定q是从适当大的整数中随机得出的.可以预计伪命中的次数为O(n/q)',\n '因为可以估计出任意的ts对模q等价于p的概率为1/q.')\n print('Rabin-Karp算法的期望运行时间为:O(n)+O(m(v+n/q))')\n print('练习32.2-1 如果取模q=11,那么当Rabin-Karp匹配算法在文本T=3141592653589793中与搜寻模式P=26,会遇到多少个伪命中点')\n sm.native_string_matcher('3141592653589793', '26')\n sm.rabin_karp_matcher('3141592653589793', '26', 10, 11)\n print('练习32.2-2 如何扩展Rabin-Karp方法,使其能解决这样的问题:如何在文本字符串中搜寻出给定的k个模式中任何一个出现',\n '起初假定所有k个模式都是等长的.然后扩展算法允许不同长度的模式')\n print('练习32.2-3 试说明如何扩展Rabin-Karp方法以处理下列问题,在一个n*n二维字符串中搜寻出给定的m*m模式',\n '(可以使该模式在水平方向和垂直方向移动,但不可以把模式旋转)')\n print('练习32.2-4 Alice有一份很长的n位文件的复印件A=,Bob也有一份类似的文件B=',\n 'Alice和Bob都希望知道他们的文件是否一样,为了避免传送整个文件A或B.',\n '运用下列快速概率检查手段,一起选择一个素数q>1000n,并从{0,1,...,q-1}中随机选取一个整数x,然后Alice求出:',\n 'A(x)=(∑aixi) mod q)的值,Bob也用类似的方法计算出B(x).',\n '证明:如果A≠B,则A(x)=B(x)的概率至多为1/1000;如果两个文件相同,则A(x)的值必定等于B(x)的值') \n # python src/chapter32/chapter32note.py\n # python3 src/chapter32/chapter32note.py\n\nclass Chapter32_3:\n \"\"\"\n chapter32.3 note and function\n \"\"\"\n def __init__(self):\n pass\n\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter32.3 note\n\n Example\n ====\n ```python\n Chapter32_3().note()\n ```\n \"\"\"\n print('chapter32.3 note as follow')\n print('32.3 利用有限自动机进行字符串匹配')\n print('很多字符串匹配算法都要建立一个有限自动机,它通过对文本字符串T进行扫描的方法,',\n '找出模式P的所有出现位置.建立这样自动机的方法,用于字符串匹配:它们只对每个文本字符检查一次,并且检查每个文本字符的时间为常数',\n '因此,在建立好自动机后所需要的时间为Θ(n),但是如果∑很大,建立自动机所花的时间也可能是很多的')\n print('在本节的开头先定义有限自动机概念.考察一种一种特殊的字符串匹配自动机,并说明如何利用它找出一个模式在文本中的出现位置',\n '包括对一段给定的文本,如何模拟出字符串匹配自动机的执行步骤的一些细节.',\n '将说明对一个给定的输入模式,如何构造相应的字符串匹配自动机')\n print('有限自动机')\n print(' 一个有限自动机M是一个5元组(Q,q0,A,∑,d)')\n print(' Q是一个状态的有限集合')\n print(' q0∈Q是初始状态')\n print(' A∈Q是一个接受状态集合')\n print(' ∑是有限的输入字母表')\n print(' d是一个从Q×∑到Q的函数,称为M的转移函数')\n print(' 有限自动机开始于状态q0,每次读入输入字符串的一个字符.如果有限自动机在状态q时读入了输入字符a,则它从状态q变为状态d(q,a)(进行了一次转移).',\n '每当其状态q属于A时,就说自动机M接受了所有读入的字符串。没有被接收的输入称为被拒绝的输入')\n print(' 有限自动机M可以推导出一个函数∮,称为终止函数,它是从∑*到Q的函数,并满足:∮(w)是M在扫描字符串w终止时的状态.',\n '因此,M接受字符串w当且仅当∮(w)∈A,函数∮由下列递归关系定义∮(e)∈q0',\n '∮(wa)=d(∮(w), a) 对于w∈∑*, a∈∑')\n print('字符串匹配自动机')\n print(' 对每个模式P都存在一个字符串匹配自动机,必须在预处理阶段,根据模式构造出相应的自动机后,才能利用它来搜寻文本字符串',\n '关于模式P=ababaca的有限自动机的构造过程。从现在开始,假定P是一个已知的固定模式.为了使说明上的简洁,在下面的概念中将不特别指出对P的依赖关系')\n print(' 为了详细说明与给定模式P[1..m]相应的字符串匹配自动机,首先定义一个辅助函数a,称为相应P的后缀函数。',\n '函数a是一个从∑*到{0,1,...,m}上定义的映射,a(x)是x的后缀P的最长前缀的长度:a(x)=max{k:Pk>x}')\n print(' 为了清楚地说明字符串匹配自动机的操作过程,给出一个简单而有效的程序,用来模拟这样一个自动机(用它的变迁函数d来表示),在输入文本T[1..n]中,',\n '寻找长度为m的模式P的出现位置的过程,对于长度为m的模式的任意字符串匹配自动机来说,状态Q为{0,1,...,m},初始状态为0,唯一的接收态是状态m')\n print(' 由FINITE-AUTOMATON-MATCHER的简单循环结构可以看出,对于一个长度为n的文本字符串,它的匹配时间为Θ(n)',\n '但是,这一匹配时间没有包括计算变迁函数d所需要的预处理时间.将在证明FINITE-AUTOMATON-MATCHER的正确性以后,再来讨论这一问题')\n print(' 考察自动机在输入文本T[1..n]上进行的操作.将证明自动机扫过字符T[i]后,其状态为d(Ti).因为d(Ti)=m当且仅当P>Ti,',\n '所以自动机处于接收状态m,当且仅当模式P已经被扫描过,为了证明这个结论,要用到下面两条关于后缀函数o的引理')\n print('引理32.2 (后缀函数不等式) 对任意字符串x和字符a,有o(xa)>=o(x)+1')\n print('引理32.3 (后缀函数递归引理) 对任意x和字符a,如果q=o(x),则o(xa)=o(Pqa)')\n print('定理32.4 如果∮是字符串匹配自动机关于给定模式P的终态函数,T[1..n]是自动机的输入文本,对i=0,1,...,n,有∮(Ti)=o(Ti)')\n print('计算变迁函数')\n print('练习32.3-1 对模式P=aabab构造出相应的字符串匹配自动机,并说明它在文本字符串T=aaababaabaababaab上的操作过程')\n print(sm.finite_automaton_matcher('aaababaabaababaab', 10, 8))\n print('练习32.3-2 对字母表∑={a, b},画出与模式ababbabbababbababbabb相应的字符串匹配自动机状态转换图')\n print('练习32.3-3 如果由Pk>Pq蕴含着k=0或k=q,则称模式P是不可重叠的.试描述与不可重叠模式相应的字符串匹配自动机的状态转换图')\n print('练习32.3-4 已知两个模式P和P`,试描述如何构造一个有限自动机,使之能确定其中任意一个模式的所有出现位置.要求尽量使自动机的状态数最小')\n print('练习32.3-5 已知一个包括间隔字符的某模式P,说明如何构造一个有限自动机,使其在O(n)的时间内,找出P在文本T中的一次出现位置,其中n=|T|')\n # python src/chapter32/chapter32note.py\n # python3 src/chapter32/chapter32note.py\n\nclass Chapter32_4:\n \"\"\"\n chapter32.4 note and function\n \"\"\"\n def __init__(self):\n pass\n\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter32.4 note\n\n Example\n ====\n ```python\n Chapter32_4().note()\n ```\n \"\"\"\n print('chapter32.4 note as follow')\n print('32.4 Knuth-Morris-Pratt算法')\n print('Knuth、Morris和Pratt三人设计的线性时间字符串匹配算法。这个算法不用计算变迁函数d,匹配时间为Θ(n),只要用到辅助函数pi[1,m]',\n '它是在Θ(m)时间内,根据模式预先计算出来的.数组pi使得我们可以按需要,“现场”有效地计算(在平摊意义上来说)变迁函数d.',\n '粗略地说,对任意状态q=0,1,...,m和任意字符a∈∑,pi[q]的值包含了与a无关但在计算d(q,a)时需要的信息',\n '由于数组pi只有m个元素,而d有Θ(m|∑|个值,所以通过预先计算pi而不是d,使得时间减少了一个|∑|因子)')\n print('关于模式的前缀函数')\n print(' 模式的前缀函数pi包含有模式与其自身的位移进行匹配的信息.这些信息可用于避免在朴素的字符串匹配算法中,对无位移进行测试,',\n '也可以避免在字符串匹配自动机中,对d的预先计算过程')\n print('KMP-MATCHER的大部分过程都是在模仿FINITE-AUTOMATON-MATCHER.KMP-MATCHER调用了一个辅助过程COMPUTE-PREFIX-FUNCTION来计算pi')\n print('运行时间分析')\n print(' 运用平摊分析方法进行分析后可知,过程COMPUTE-PREFIX-FUNCTION的运行时间为Θ(m)')\n print(' 在类似的平摊分析中,如果用q的值作为势函数,则KMP-MATCHER的匹配时间为Θ(n)',\n '与FINITE-AUTOMATON-MATCHER相比,通过运用pi而不是d,可使对模式进行预处理所需的时间由O(m|∑|)下降为Θ(m),同时保持实际的匹配时间为Θ(n)')\n print('前缀函数计算的正确性')\n print(' 通过对前缀函数pi进行迭代,就能够列举出是某给定前缀Pq的后缀的所有前缀Pk,设',\n 'pi*[q]={pi[q],pi(2)[q],pi(3)[q],...,pi(t)[q]}')\n print('引理32.5 (前缀函数迭代定理) 设P是长度为m的模式,其前缀函数为pi,对q=1,2,...,m,有pi*[q]={k:kPq}')\n print('引理32.6 设P是长度为m的模式,pi是P的前缀函数.对q=1,2,...,m,如果pi[q]>0,则pi[q]-1∈pi*[q-1]')\n print('推论32.7 设P是长度为m的模式,pi是P的前缀函数,对q=2,3,...,m')\n print('KMP算法的正确性')\n print(' 过程KMP-MATCHER可以看做是过程FINITE-AUTOMATON-MATCHER的一次重新实现')\n print('练习32.4-1 当字母表为∑={a,b},计算相应于模式ababbabbabbababbabb的前缀函数pi')\n print('练习32.4-2 给出关于q的函数pi*[q]的规模的上界.举例说明所给出的上界是严格的')\n print('练习32.4-3 试说明如何通过检查字符串PT的pi函数,来确定模式P在文本T中的出现位置(由P和T并置形成的长度为m+n的字符串)')\n print('练习32.4-4 试说明如何通过以下方式对过程KMP-MATCHER进行改进:把第7行(不是第12行中)出现的pi替换为pi‘.对q=1,2,...,m的递归定义如下:')\n print('练习32.4-5 写出一个线性时间的算法,','以确定文本T是否是另一个字符串T‘的循环旋转,例如arc和car是彼此的循环旋转')\n print('练习32.4-6 给出一个有效的算法,计算出相应于某给定模式P的字符串匹配自动机的变迁函数d',\n '所给出的算法的运行时间应该是O(m|∑|).(提示:证明:如果q=m或P[q+1]!=a,则d(q,a)=d(pi[q],a))')\n print('思考题32-1 基于重复因子的字符串匹配')\n print(' 设yi表示字符串y与其自身并置i次所得的结果.例如(ab)^3=ababab.如果对某个字符串y∈∑*和某个r>0有x=y^r,则称字符串x∈∑*具有重复因子r.',\n '设p(x)表示满足x具有重复因子r的最大值')\n print(' (a) 写出一个有效算法以计算出p(Pi)(i=1,2,...,m),算法的输入为模式P[1..m].算法的运行时间是多少?')\n print(' (b) 对任何模式p[1..m],设p(P)定义为max(1<=i<=m)p(Pi).证明:如果从长度为m的所有二进制字符串所组成的集中随机地选择模式P,则p*(P)的期望值是O(1)')\n print(' (c) 论证下列字符串匹配算法可以在O(p*(P)n+m)的运行时间内,正确地找出模式P在文本T[1..n]中的所有出现位置')\n # python src/chapter32/chapter32note.py\n # python3 src/chapter32/chapter32note.py\n\nchapter32_1 = Chapter32_1()\nchapter32_2 = Chapter32_2()\nchapter32_3 = Chapter32_3()\nchapter32_4 = Chapter32_4()\n\ndef printchapter32note():\n \"\"\"\n print chapter32 note.\n \"\"\"\n print('Run main : single chapter thirty-two!')\n chapter32_1.note()\n chapter32_2.note()\n chapter32_3.note()\n chapter32_4.note()\n\n# python src/chapter32/chapter32note.py\n# python3 src/chapter32/chapter32note.py\n\nif __name__ == '__main__': \n printchapter32note()\nelse:\n pass\n", "meta": {"hexsha": "6372d0e278c4c77ae1b98018bbd8c91e21a8acb5", "size": 12740, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chapter32/chapter32note.py", "max_stars_repo_name": "Peefy/CLRS_dugu_code-master", "max_stars_repo_head_hexsha": "98f00e75e1b0ebc13a7affb2604bec8501692a19", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-01-31T03:08:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T12:57:01.000Z", "max_issues_repo_path": "src/chapter32/chapter32note.py", "max_issues_repo_name": "HideLakitu/IntroductionToAlgorithm.Python", "max_issues_repo_head_hexsha": "33662f46dc346203b220d7481d1a4439feda05d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter32/chapter32note.py", "max_forks_repo_name": "HideLakitu/IntroductionToAlgorithm.Python", "max_forks_repo_head_hexsha": "33662f46dc346203b220d7481d1a4439feda05d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-03T04:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T10:18:58.000Z", "avg_line_length": 43.4812286689, "max_line_length": 117, "alphanum_fraction": 0.6326530612, "include": true, "reason": "import numpy", "num_tokens": 7493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.20946968626535545, "lm_q1q2_score": 0.09494461709983816}} {"text": "from IPython.display import HTML\n\nHTML('''\nThe raw code for this IPython notebook is by default hidden for easier reading.\nTo toggle on/off the raw code, click here.''')\n\n\n# From Ptolemy to Kepler\n\nPtolemy, Copernicus, Brahe, Kepler\n\n\n\n\n\n# Cosmic Calculations 2.1: Kepler’s Third Law\n\nFirst, let's review the three laws discovered by Kepler from the careful measurements of [Tycho Brache](https://physicsworld.com/a/kepler-and-tycho-brahe-the-odd-couple/). This is one of the most ineteresting stories of scientific collaboration that transformed years of observations into laws about the universe. I recommend to read/watch [***The Character of Physical Law***](https://www.youtube.com/watch?v=j3mhkYbznBk) by Richard Feynman if you want to indulge in the details.\n\n

\"Tycho-Kepler-Statue-Prague.jpg\"
By Both Előd at Hungarian Wikipedia, CC BY-SA 2.5, Link

\n\n## Kepler's laws:\n\n***1. The orbit of every planet is an ellipse with the Sun at one of the two foci.***\n\nIn the figure below, you can imagine the yellow dot as the sun, and a planet would be moving on the blue curve a certain distance away from it. The elliptical orbit can be described by the semi-major and semi-minor axes, which define the eccentricity of the orbit. \n\n\nLook for the *perihelion* and *aphelion* of Earth's orbit. From those values, what's the flattening of Earth's orbit and its eccentricity?\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets\n\n# Set default font size for plots:\nfont = {'size' : 18}\nplt.rc('font',**font)\n\ndef elliptic_orbit(a,b,t):\n '''Plot an elliptical orbit and see the radial distance from one focal point\n a= semi-major axis\n b=semi-minor axis\n t=location at an angle between 0 and 360'''\n p=np.linspace(0,2*np.pi,360)\n x = a*np.cos(p)\n y = b*np.sin(p) \n plt.figure('Ellipse2',figsize=(10,5))\n plt.plot(x,y,'-')\n plt.axis('equal')\n plt.grid(True)\n #t is the angle varying from 0 to 360 degrees\n X = a*np.cos(t*np.pi/180)\n Y = b*np.sin(t*np.pi/180)\n #Conditionals in case of changing length of largest semi-major axis\n if a>=b:\n c=np.sqrt(a**2-b**2)\n plt.scatter(c,0,s=200,c='y')\n plt.scatter(-c, 0, s=200, facecolors='none', edgecolors='y')\n plt.arrow(c, 0, X-c, Y, head_width=0.1, head_length=0.1, fc='red', ec='red')\n plt.scatter(X,Y,s=50,c='b')\n f=(a-b)/a\n e=c/a\n #print('Orbital flattening : ',f)\n print('Orbital eccentricity : ',e)\n #plt.show()\n else:\n c=np.sqrt(b**2-a**2)\n plt.scatter(0,c,s=200,c='y')\n plt.scatter(0, -c, s=200, facecolors='none', edgecolors='y')\n plt.arrow(0, c, X, Y-c, head_width=0.1, head_length=0.1, fc='red', ec='red')\n plt.scatter(X,Y,s=50,c='b')\n f=(b-a)/b\n e=c/b\n #print('Orbital flattening : ',f)\n print('Orbital eccentricity : ',e)\n plt.show()\n return\n\ninteractive(elliptic_orbit, a = (0,20,1),b=(0,20,1),t=(0,360,20),continuous_update=False)\n \n\nThe reason the orbits are ellipses, and not circles, would not be understood until the arrival of Newton's equations on Gravitation. \n\n***2. A line joining a planet and the Sun sweeps out equal areas during equal intervals of time.***\n\n

\"Kepler-second-law.gif\"
By Gonfer (talk) - Gonfer, CC BY-SA 3.0, Link

\n\n\nWhen Kepler discovered his third law ($p^2 = a^3$), he knew only that it applied to the orbits of planets about the Sun. In fact, it applies to any orbiting object as long as the following two conditions are met: \n\n1. The object orbits the Sun or another star of precisely the same mass. \n2. We use units of years for the orbital period and AU for the orbital distance. (Newton extended the law to all orbiting objects; see [Cosmic Calculations 7.1](#CC-7.1).) \n\nIn other words, these two conditions make the relationship a perfect equality.\n\n**Example 1:** The largest asteroid, Ceres, orbits the Sun at an average distance (semimajor axis) of 2.77 AU. What is its orbital period? \n\n***Solution:*** Both conditions are met, so we solve Kepler’s third law for the orbital period $p$ and substitute the given orbital distance, $a = 2.77~AU$.\n\n\n$$p^2 = a^3$$\n\n$$ p = \\sqrt{a^3} = \\sqrt{2.77^3} \\approx 4.6~y$$\n\nCeres has an orbital period of 4.6 years. \n\n**Example 2:** A planet is discovered orbiting every three months around a star of the same mass as our Sun. What is the planet’s average orbital distance? \n\n***Solution:*** The first condition is met, and we can satisfy the second by converting the orbital period from months to years: $p = 3$ months = 0.25 year. We now solve Kepler’s third law for the average distance a: \n\n$a = \\sqrt[3]{p^2}$\n\n$a = \\sqrt[3]{0.25^2} \\approx 0.40~AU$\n\nThe planet orbits its star at an average distance of $0.40~AU$, which is nearly the same as Mercury’s average distance from the Sun.\n\nThese observations offered clear proof that Earth is not the center of everything.* Although we now recognize that Galileo won the day, the story was more complex in his own time, when Catholic Church doctrine still held Earth to be the center of the universe. On June 22, 1633, Galileo was brought before a Church inquisition in Rome and ordered to recant his claim that Earth orbits the Sun. Nearly 70 years old and fearing for his life, Galileo did as ordered and his life was spared. However, legend has it that as he rose from his knees, he whispered under his breath, Eppur si muove— Italian for “And yet it moves.” (Given the likely consequences if Church officials had heard him say this, most historians doubt the legend.) The Church did not formally vindicate Galileo until 1992, but the Church had given up the argument long before that. Today, Catholic scientists are at the forefront of much astronomical research, and official Church teachings are compatible not only with Earth’s planetary status but also with the theories of the Big Bang and the subsequent evolution of the cosmos and of life.\n\n\n

flash animation

\n\n\n[Go back to the top of the page](#top-title)\n\n", "meta": {"hexsha": "fa0fe4246614c87cb8512347036f4efd90b216af", "size": 7989, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/content/01/3/from_ptolemy_to_kepler.py", "max_stars_repo_name": "edur409/ASTROBIOLOGY200", "max_stars_repo_head_hexsha": "868d02a10b4be5f71935325c43e89b02567e4e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/content/01/3/from_ptolemy_to_kepler.py", "max_issues_repo_name": "edur409/ASTROBIOLOGY200", "max_issues_repo_head_hexsha": "868d02a10b4be5f71935325c43e89b02567e4e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/content/01/3/from_ptolemy_to_kepler.py", "max_forks_repo_name": "edur409/ASTROBIOLOGY200", "max_forks_repo_head_hexsha": "868d02a10b4be5f71935325c43e89b02567e4e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.3138686131, "max_line_length": 1108, "alphanum_fraction": 0.7080986356, "include": true, "reason": "import numpy", "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.09433619798565421}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # ETHZ: 227-0966-00L\n# # Quantitative Big Imaging\n# # March 28, 2019\n#\n# ## Shape Analysis\n\n# In[1]:\n\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = (8, 8)\nplt.rcParams[\"figure.dpi\"] = 150\nplt.rcParams[\"font.size\"] = 14\nplt.rcParams[\"font.family\"] = [\"sans-serif\"]\nplt.rcParams[\"font.sans-serif\"] = [\"DejaVu Sans\"]\nplt.style.use(\"ggplot\")\nsns.set_style(\"whitegrid\", {\"axes.grid\": False})\n\n\n# # Literature / Useful References\n#\n# - Jean Claude, Morphometry with R\n# - [Online](http://link.springer.com/book/10.1007%2F978-0-387-77789-4) through ETHZ\n# - [Buy it](http://www.amazon.com/Morphometrics-R-Use-Julien-Claude/dp/038777789X)\n# - John C. Russ, “The Image Processing Handbook”,(Boca Raton, CRC Press)\n# - Available [online](http://dx.doi.org/10.1201/9780203881095) within domain ethz.ch (or proxy.ethz.ch / public VPN)\n# - Principal Component Analysis\n# - Venables, W. N. and B. D. Ripley (2002). Modern Applied Statistics with S, Springer-Verlag\n# - Shape Tensors\n# - http://www.cs.utah.edu/~gk/papers/vissym04/\n# - Doube, M.,et al. (2010). BoneJ: Free and extensible bone image analysis in ImageJ. Bone, 47, 1076–9. doi:10.1016/j.bone.2010.08.023\n# - Mader, K. , et al. (2013). A quantitative framework for the 3D characterization of the osteocyte lacunar system. Bone, 57(1), 142–154. doi:10.1016/j.bone.2013.06.026\n#\n# - Wilhelm Burger, Mark Burge. Principles of Digital Image Processing:\n# Core Algorithms. Springer-Verlag, London, 2009.\n# - B. Jähne. Digital Image Processing. Springer-Verlag,\n# Berlin-Heidelberg, 6. edition, 2005.\n# - T. H. Reiss. Recognizing Planar Objects Using Invariant Image\n# Features, from Lecture notes in computer science, p. 676. Springer,\n# Berlin, 1993.\n# - http://en.wikipedia.org/wiki/Image_moment\n#\n#\n\n# # Previously on QBI ...\n#\n# - Image Enhancment\n# - Highlighting the contrast of interest in images\n# - Minimizing Noise\n# - Segmentation\n# - Understanding value histograms\n# - Dealing with multi-valued data\n# - Automatic Methods\n# - Hysteresis Method, K-Means Analysis\n# - Regions of Interest\n# - Contouring\n# - Machine Learning\n\n# # Learning Objectives\n#\n# ## Motivation (Why and How?)\n# - How do we quantify where and how big our objects are?\n# - How can we say something about the shape?\n# - How can we compare objects of different sizes?\n# - How can we compare two images on the basis of the shape as calculated from the images?\n# - How can we put objects into an finite element simulation? or make pretty renderings?\n\n# # Outline\n#\n# - Motivation (Why and How?)\n# - Object Characterization\n# - Volume\n# - Center and Extents\n# - Anisotropy\n#\n# ***\n#\n# - Shape Tensor\n# - Principal Component Analysis\n# - Ellipsoid Representation\n# - Scale-free metrics\n# - Anisotropy, Oblateness\n# - Meshing\n# - Marching Cubes\n# - Isosurfaces\n# - Surface Area\n\n# # Motivation\n#\n#\n# We have dramatically simplified our data, but there is still too much.\n#\n# - We perform an experiment bone to see how big the cells are inside the tissue\n# $$\\downarrow$$ ![Bone Measurement](ext-figures/tomoimage.png)\n#\n# ### 2560 x 2560 x 2160 x 32 bit\n# _56GB / sample_\n# - Filtering and Enhancement!\n# $$\\downarrow$$\n# - 56GB of less noisy data\n#\n# ***\n#\n# - __Segmentation__\n#\n# $$\\downarrow$$\n#\n# ### 2560 x 2560 x 2160 x 1 bit\n# (1.75GB / sample)\n#\n# - Still an aweful lot of data\n\n# # What did we want in the first place\n#\n# ### _Single number_:\n# * volume fraction,\n# * cell count,\n# * average cell stretch,\n# * cell volume variability\n\n# # Component Labeling\n#\n# Once we have a clearly segmented image, it is often helpful to identify the sub-components of this image. The easist method for identifying these subcomponents is called component labeling which again uses the neighborhood $\\mathcal{N}$ as a criterion for connectivity, resulting in pixels which are touching being part of the same object.\n#\n#\n# In general, the approach works well since usually when different regions are touching, they are related. It runs into issues when you have multiple regions which agglomerate together, for example a continuous pore network (1 object) or a cluster of touching cells.\n#\n# Here we show some examples from Cityscape Data taken in Aachen (https://www.cityscapes-dataset.com/)\n\n# In[2]:\n\n\nfrom skimage.io import imread\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ncar_img = imread(\"ext-figures/aachen_img.png\")\nseg_img = imread(\"ext-figures/aachen_label.png\")[::4, ::4] == 26\nprint(\"image dimensions\", car_img.shape, seg_img.shape)\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))\nax1.imshow(car_img)\nax1.set_title(\"Input Image\")\n\nax2.imshow(seg_img, cmap=\"bone\")\nax2.set_title(\"Segmented Image\")\n\n\n# The more general formulation of the problem is for networks (roads, computers, social). Are the points start and finish connected?\n\n# In[3]:\n\n\nfrom skimage.morphology import label\n\nhelp(label)\n\n\n# In[4]:\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))\nax1.imshow(seg_img, cmap=\"bone\")\nax1.set_title(\"Segmented Image\")\nlab_img = label(seg_img)\nax2.imshow(lab_img, cmap=plt.cm.gist_earth)\nax2.set_title(\"Labeled Image\")\n\n\n# In[5]:\n\n\nfig, (ax3) = plt.subplots(1, 1)\nax3.hist(lab_img.ravel())\nax3.set_title(\"Label Counts\")\nax3.set_yscale(\"log\")\n\n\n# # Component Labeling: Algorithm\n#\n# We start off with all of the pixels in either foreground (1) or background (0)\n\n# In[6]:\n\n\nfrom skimage.morphology import label\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nseg_img = np.eye(9, dtype=int)\nseg_img[4, 4] = 0\nseg_img += seg_img[::-1]\nsns.heatmap(seg_img, annot=True, fmt=\"d\")\n\n\n# Give each point in the image a unique label\n# - For each point $(x,y)\\in\\text{Foreground}$\n# - Set value to $I_{x,y} = x+y*width+1$\n\n# In[7]:\n\n\nidx_img = np.zeros_like(seg_img)\nfor x in range(seg_img.shape[0]):\n for y in range(seg_img.shape[1]):\n if seg_img[x, y] > 0:\n idx_img[x, y] = x + y * seg_img.shape[0] + 1\nsns.heatmap(idx_img, annot=True, fmt=\"d\", cmap=\"nipy_spectral\")\n\n\n# In a [brushfire](http://www.sciencedirect.com/science/article/pii/S0921889007000966)-style algorithm\n# - For each point $(x,y)\\in\\text{Foreground}$\n# - For each point $(x^{\\prime},y^{\\prime})\\in\\mathcal{N}(x,y)$\n# - if $(x^{\\prime},y^{\\prime})\\in\\text{Foreground}$\n# - Set the label to $\\min(I_{x,y}, I_{x^{\\prime},y^{\\prime}})$\n# - Repeat until no more labels have been changed\n\n# In[8]:\n\n\nfig, m_axs = plt.subplots(2, 2, figsize=(20, 20))\nlast_img = idx_img.copy()\nimg_list = [last_img]\nfor iteration, c_ax in enumerate(m_axs.flatten(), 1):\n cur_img = last_img.copy()\n\n for x in range(last_img.shape[0]):\n for y in range(last_img.shape[1]):\n if last_img[x, y] > 0:\n i_xy = last_img[x, y]\n for xp in [-1, 0, 1]:\n if (x + xp < last_img.shape[0]) and (x + xp >= 0):\n for yp in [-1, 0, 1]:\n if (y + yp < last_img.shape[1]) and (y + yp >= 0):\n i_xpyp = last_img[x + xp, y + yp]\n if i_xpyp > 0:\n\n new_val = min(i_xy, i_xpyp, cur_img[x, y])\n if cur_img[x, y] != new_val:\n print(\n (x, y),\n i_xy,\n \"vs\",\n (x + xp, y + yp),\n i_xpyp,\n \"->\",\n new_val,\n )\n cur_img[x, y] = new_val\n\n img_list += [cur_img]\n sns.heatmap(cur_img, annot=True, fmt=\"d\", cmap=\"nipy_spectral\", ax=c_ax)\n c_ax.set_title(\"Iteration #{}\".format(iteration))\n if (cur_img == last_img).all():\n print(\"Done\")\n break\n else:\n print(\n \"Iteration\",\n iteration,\n \"Groups\",\n len(np.unique(cur_img[cur_img > 0].ravel())),\n \"Changes\",\n np.sum(cur_img != last_img),\n )\n last_img = cur_img\n\n\n# The image very quickly converges and after 4 iterations the task is complete. For larger more complicated images with thousands of components this task can take longer, but there exist much more efficient [algorithms](https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf) for labeling components which alleviate this issue.\n\n# In[9]:\n\n\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\n\nfig, c_ax = plt.subplots(1, 1, figsize=(5, 5), dpi=150)\n\n\ndef update_frame(i):\n plt.cla()\n sns.heatmap(\n img_list[i],\n annot=True,\n fmt=\"d\",\n cmap=\"nipy_spectral\",\n ax=c_ax,\n cbar=False,\n vmin=img_list[0].min(),\n vmax=img_list[0].max(),\n )\n c_ax.set_title(\n \"Iteration #{}, Groups {}\".format(\n i + 1, len(np.unique(img_list[i][img_list[i] > 0].ravel()))\n )\n )\n\n\n# write animation frames\nanim_code = FuncAnimation(\n fig, update_frame, frames=len(img_list) - 1, interval=1000, repeat_delay=2000\n).to_html5_video()\nplt.close(\"all\")\nHTML(anim_code)\n\n\n# # Bigger Images\n# How does the same algorithm apply to bigger images\n\n# In[10]:\n\n\nfrom skimage.io import imread\nfrom skimage.morphology import label\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nseg_img = (imread(\"ext-figures/aachen_label.png\")[::4, ::4] == 26)[110:130:2, 370:420:3]\nseg_img[9, 1] = 1\n_, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 7), dpi=150)\nsns.heatmap(seg_img, annot=True, fmt=\"d\", ax=ax1, cmap=\"nipy_spectral\", cbar=False)\nidx_img = seg_img * np.arange(len(seg_img.ravel())).reshape(seg_img.shape)\nsns.heatmap(idx_img, annot=True, fmt=\"d\", ax=ax2, cmap=\"nipy_spectral\", cbar=False)\n\n\n# In[11]:\n\n\nlast_img = idx_img.copy()\nimg_list = [last_img]\nfor iteration in range(99):\n cur_img = last_img.copy()\n for x in range(last_img.shape[0]):\n for y in range(last_img.shape[1]):\n if last_img[x, y] > 0:\n i_xy = last_img[x, y]\n for xp in [-1, 0, 1]:\n if (x + xp < last_img.shape[0]) and (x + xp >= 0):\n for yp in [-1, 0, 1]:\n if (y + yp < last_img.shape[1]) and (y + yp >= 0):\n i_xpyp = last_img[x + xp, y + yp]\n if i_xpyp > 0:\n new_val = min(i_xy, i_xpyp, cur_img[x, y])\n if cur_img[x, y] != new_val:\n cur_img[x, y] = new_val\n\n img_list += [cur_img]\n if (cur_img == last_img).all():\n print(\"Done\")\n break\n else:\n print(\n \"Iteration\",\n iteration,\n \"Groups\",\n len(np.unique(cur_img[cur_img > 0].ravel())),\n \"Changes\",\n np.sum(cur_img != last_img),\n )\n last_img = cur_img\n\n\n# In[12]:\n\n\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\n\nfig, c_ax = plt.subplots(1, 1, figsize=(5, 5), dpi=150)\n\n\ndef update_frame(i):\n plt.cla()\n sns.heatmap(\n img_list[i],\n annot=True,\n fmt=\"d\",\n cmap=\"nipy_spectral\",\n ax=c_ax,\n cbar=False,\n vmin=img_list[0].min(),\n vmax=img_list[0].max(),\n )\n c_ax.set_title(\n \"Iteration #{}, Groups {}\".format(\n i + 1, len(np.unique(img_list[i][img_list[i] > 0].ravel()))\n )\n )\n\n\n# write animation frames\nanim_code = FuncAnimation(\n fig, update_frame, frames=len(img_list) - 1, interval=500, repeat_delay=1000\n).to_html5_video()\nplt.close(\"all\")\nHTML(anim_code)\n\n\n# # Different Neighborhoods\n# We can expand beyond the 3x3 neighborhood to a 5x5 for example\n\n# In[13]:\n\n\nlast_img = idx_img.copy()\nimg_list = [last_img]\nfor iteration in range(99):\n cur_img = last_img.copy()\n for x in range(last_img.shape[0]):\n for y in range(last_img.shape[1]):\n if last_img[x, y] > 0:\n i_xy = last_img[x, y]\n for xp in [-2, -1, 0, 1, 2]:\n if (x + xp < last_img.shape[0]) and (x + xp >= 0):\n for yp in [-2, -1, 0, 1, 2]:\n if (y + yp < last_img.shape[1]) and (y + yp >= 0):\n i_xpyp = last_img[x + xp, y + yp]\n if i_xpyp > 0:\n new_val = min(i_xy, i_xpyp, cur_img[x, y])\n if cur_img[x, y] != new_val:\n cur_img[x, y] = new_val\n\n img_list += [cur_img]\n if (cur_img == last_img).all():\n print(\"Done\")\n break\n else:\n print(\n \"Iteration\",\n iteration,\n \"Groups\",\n len(np.unique(cur_img[cur_img > 0].ravel())),\n \"Changes\",\n np.sum(cur_img != last_img),\n )\n last_img = cur_img\n\nfig, c_ax = plt.subplots(1, 1, figsize=(5, 5), dpi=150)\n\n\ndef update_frame(i):\n plt.cla()\n sns.heatmap(\n img_list[i],\n annot=True,\n fmt=\"d\",\n cmap=\"nipy_spectral\",\n ax=c_ax,\n cbar=False,\n vmin=img_list[0].min(),\n vmax=img_list[0].max(),\n )\n c_ax.set_title(\n \"Iteration #{}, Groups {}\".format(\n i + 1, len(np.unique(img_list[i][img_list[i] > 0].ravel()))\n )\n )\n\n\n# write animation frames\nanim_code = FuncAnimation(\n fig, update_frame, frames=len(img_list) - 1, interval=500, repeat_delay=1000\n).to_html5_video()\nplt.close(\"all\")\nHTML(anim_code)\n\n\n# # Or a smaller kernel\n# By using a smaller kernel (in this case where $\\sqrt{x^2+y^2}<=1$, we cause the number of iterations to fill to increase and prevent the last pixel from being grouped since it is only connected diagonally\n#\n# | | | |\n# |--:|--:|--:|\n# | 0| 1| 0|\n# | 1| 1| 1|\n# | 0| 1| 0|\n#\n\n# In[14]:\n\n\nlast_img = idx_img.copy()\nimg_list = [last_img]\nfor iteration in range(99):\n cur_img = last_img.copy()\n for x in range(last_img.shape[0]):\n for y in range(last_img.shape[1]):\n if last_img[x, y] > 0:\n i_xy = last_img[x, y]\n for xp in [-1, 0, 1]:\n if (x + xp < last_img.shape[0]) and (x + xp >= 0):\n for yp in [-1, 0, 1]:\n if np.abs(xp) + np.abs(yp) <= 1:\n if (y + yp < last_img.shape[1]) and (y + yp >= 0):\n i_xpyp = last_img[x + xp, y + yp]\n if i_xpyp > 0:\n new_val = min(i_xy, i_xpyp, cur_img[x, y])\n if cur_img[x, y] != new_val:\n cur_img[x, y] = new_val\n\n img_list += [cur_img]\n if (cur_img == last_img).all():\n print(\"Done\")\n break\n else:\n print(\n \"Iteration\",\n iteration,\n \"Groups\",\n len(np.unique(cur_img[cur_img > 0].ravel())),\n \"Changes\",\n np.sum(cur_img != last_img),\n )\n last_img = cur_img\n\nfig, c_ax = plt.subplots(1, 1, figsize=(6, 6), dpi=100)\n\n\ndef update_frame(i):\n plt.cla()\n sns.heatmap(\n img_list[i],\n annot=True,\n fmt=\"d\",\n cmap=\"nipy_spectral\",\n ax=c_ax,\n cbar=False,\n vmin=img_list[0].min(),\n vmax=img_list[0].max(),\n )\n c_ax.set_title(\n \"Iteration #{}, Groups {}\".format(\n i + 1, len(np.unique(img_list[i][img_list[i] > 0].ravel()))\n )\n )\n\n\n# write animation frames\nanim_code = FuncAnimation(\n fig, update_frame, frames=len(img_list) - 1, interval=500, repeat_delay=1000\n).to_html5_video()\nplt.close(\"all\")\nHTML(anim_code)\n\n\n# # Component Labeling: Beyond\n#\n#\n# Now all the voxels which are connected have the same label. We can then perform simple metrics like\n#\n# - counting the number of voxels in each label to estimate volume.\n# - looking at the change in volume during erosion or dilation to estimate surface area\n\n# ### What we would like to to do\n#\n# - Count the cells\n# - Say something about the cells\n# - Compare the cells in this image to another image\n# - But where do we start?\n#\n# # COV: With a single object\n#\n# $$ I_{id}(x,y) =\n# \\begin{cases}\n# 1, & L(x,y) = id \\\\\n# 0, & \\text{otherwise}\n# \\end{cases}$$\n\n# In[15]:\n\n\nfrom IPython.display import Markdown\nfrom skimage.io import imread\nfrom skimage.morphology import label\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nseg_img = imread(\"ext-figures/aachen_label.png\") == 26\nseg_img = seg_img[::4, ::4]\nseg_img = seg_img[110:130:2, 370:420:3]\nseg_img[9, 1] = 1\nlab_img = label(seg_img)\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\nsns.heatmap(lab_img, annot=True, fmt=\"d\", ax=ax1, cmap=\"nipy_spectral\", cbar=False)\n\n\n# ### Define a center\n# $$ \\bar{x} = \\frac{1}{N} \\sum_{\\vec{v}\\in I_{id}} \\vec{v}\\cdot\\vec{i} $$\n# $$ \\bar{y} = \\frac{1}{N} \\sum_{\\vec{v}\\in I_{id}} \\vec{v}\\cdot\\vec{j} $$\n# $$ \\bar{z} = \\frac{1}{N} \\sum_{\\vec{v}\\in I_{id}} \\vec{v}\\cdot\\vec{k} $$\n#\n\n# In[16]:\n\n\nx_coord, y_coord = [], []\nfor x in range(seg_img.shape[0]):\n for y in range(seg_img.shape[1]):\n if seg_img[x, y] == 1:\n x_coord += [x]\n y_coord += [y]\nprint(\"x,y coordinates\", list(zip(x_coord, y_coord)))\nMarkdown(\"$\\\\bar{x} = %2.2f, \\\\bar{y} = %2.2f $\" % (np.mean(x_coord), np.mean(y_coord)))\n\n\n# # COM: With a single object\n#\n# If the gray values are kept (or other meaningful ones are used), this can be seen as a weighted center of volume or center of mass (using $I_{gy}$ to distinguish it from the labels)\n#\n# ### Define a center\n# $$ \\Sigma I_{gy} = \\frac{1}{N} \\sum_{\\vec{v}\\in I_{id}} I_{gy}(\\vec{v}) $$\n# $$ \\bar{x} = \\frac{1}{\\Sigma I_{gy}} \\sum_{\\vec{v}\\in I_{id}} (\\vec{v}\\cdot\\vec{i}) I_{gy}(\\vec{v}) $$\n# $$ \\bar{y} = \\frac{1}{\\Sigma I_{gy}} \\sum_{\\vec{v}\\in I_{id}} (\\vec{v}\\cdot\\vec{j}) I_{gy}(\\vec{v}) $$\n# $$ \\bar{z} = \\frac{1}{\\Sigma I_{gy}} \\sum_{\\vec{v}\\in I_{id}} (\\vec{v}\\cdot\\vec{k}) I_{gy}(\\vec{v}) $$\n#\n\n# In[17]:\n\n\nfrom IPython.display import Markdown, display\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nxx, yy = np.meshgrid(np.linspace(0, 10, 50), np.linspace(0, 10, 50))\ngray_img = 100 * (np.abs(xx * yy - 7) + np.square(yy - 4)) + 0.25\ngray_img *= np.abs(xx - 5) < 3\ngray_img *= np.abs(yy - 5) < 3\ngray_img[gray_img > 0] += 5\nseg_img = (gray_img > 0).astype(int)\n_, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7), dpi=150)\n\nsns.heatmap(gray_img, ax=ax1, cmap=\"bone_r\", cbar=True)\nax1.set_title(\"Intensity Image\")\n\nsns.heatmap(seg_img, ax=ax2, cmap=\"bone\", cbar=False)\nax2.set_title(\"Segmented Image\")\n\n\n# In[18]:\n\n\nx_coord, y_coord, i_val = [], [], []\nfor x in range(seg_img.shape[0]):\n for y in range(seg_img.shape[1]):\n if seg_img[x, y] == 1:\n x_coord += [x]\n y_coord += [y]\n i_val += [gray_img[x, y]]\n\nx_coord = np.array(x_coord)\ny_coord = np.array(y_coord)\ni_val = np.array(i_val)\ncov_x = np.mean(x_coord)\ncov_y = np.mean(y_coord)\n\ndisplay(\n Markdown(\n \"\"\"## Center of Volume: \n- $\\\\bar{x} = %2.2f$\n- $\\\\bar{y} = %2.2f $\"\"\"\n % (cov_x, cov_y)\n )\n)\n\ncom_x = np.sum(x_coord * i_val) / np.sum(i_val)\ncom_y = np.sum(y_coord * i_val) / np.sum(i_val)\n\ndisplay(\n Markdown(\n \"\"\"## Center of Mass: \n- $\\\\bar{x}_m = %2.2f$\n- $\\\\bar{y}_m = %2.2f $\"\"\"\n % (com_x, com_y)\n )\n)\n\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\n\nax1.matshow(gray_img, cmap=\"bone_r\")\nax1.set_title(\"Intensity Image\")\nax1.plot([cov_y], [cov_x], \"ro\", label=\"COV\", markersize=20)\nax1.plot([com_y], [com_x], \"bo\", label=\"COM\", markersize=20)\nax1.legend()\n\n\n# In[19]:\n\n\nfrom skimage.measure import regionprops\n\nhelp(regionprops)\n\n\n# In[20]:\n\n\nfrom skimage.measure import regionprops\n\nall_regs = regionprops(seg_img, intensity_image=gray_img)\nfor c_reg in all_regs:\n display(Markdown(\"# Region: {}\".format(c_reg.label)))\n for k in dir(c_reg):\n if not k.startswith(\"_\") and (\"image\" not in k):\n display(Markdown(\"- {} {}\".format(k, getattr(c_reg, k))))\n\n\n# # Extents: With a single object\n#\n# Exents or caliper lenghts are the size of the object in a given direction. Since the coordinates of our image our $x$ and $y$ the extents are calculated in these directions\n#\n# Define extents as the minimum and maximum values along the projection of the shape in each direction\n# $$ \\text{Ext}_x = \\left\\{ \\forall \\vec{v}\\in I_{id}: max(\\vec{v}\\cdot\\vec{i})-min(\\vec{v}\\cdot\\vec{i}) \\right\\} $$\n# $$ \\text{Ext}_y = \\left\\{ \\forall \\vec{v}\\in I_{id}: max(\\vec{v}\\cdot\\vec{j})-min(\\vec{v}\\cdot\\vec{j}) \\right\\} $$\n# $$ \\text{Ext}_z = \\left\\{ \\forall \\vec{}\\in I_{id}: max(\\vec{v}\\cdot\\vec{k})-min(\\vec{v}\\cdot\\vec{k}) \\right\\} $$\n#\n# - Lots of information about each object now\n# - But, I don't think a biologist has ever asked \"How long is a cell in the $x$ direction? how about $y$?\"\n\n# In[21]:\n\n\nfrom IPython.display import Markdown\nfrom skimage.io import imread\nfrom skimage.morphology import label\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nseg_img = imread(\"ext-figures/aachen_label.png\") == 26\nseg_img = seg_img[::4, ::4]\nseg_img = seg_img[110:130:2, 378:420:3] > 0\nseg_img = np.pad(seg_img, 3, mode=\"constant\")\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\nax1.matshow(seg_img, cmap=\"bone_r\")\n\n\n# In[22]:\n\n\nx_coord, y_coord = [], []\nfor x in range(seg_img.shape[0]):\n for y in range(seg_img.shape[1]):\n if seg_img[x, y] == 1:\n x_coord += [x]\n y_coord += [y]\nxmin = np.min(x_coord)\nxmax = np.max(x_coord)\nymin = np.min(y_coord)\nymax = np.max(y_coord)\nprint(\"X -> \", \"Min:\", xmin, \"Max:\", xmax)\nprint(\"Y -> \", \"Min:\", ymin, \"Max:\", ymax)\n\n\n# In[23]:\n\n\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Rectangle\n\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\n\nax1.matshow(seg_img, cmap=\"bone_r\")\n\nxw = xmax - xmin\nyw = ymax - ymin\n\nc_bbox = [Rectangle(xy=(ymin, xmin), width=yw, height=xw)]\nc_bb_patch = PatchCollection(\n c_bbox, facecolor=\"none\", edgecolor=\"red\", linewidth=4, alpha=0.5\n)\nax1.add_collection(c_bb_patch)\n\n\n# # Concrete Example\n# So how can we begin to apply the tools we have developed. We take the original car scene from before.\n\n# In[24]:\n\n\nfrom skimage.measure import regionprops, label\nfrom skimage.io import imread\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ncar_img = np.clip(imread(\"ext-figures/aachen_img.png\")[75:150] * 2.0, 0, 255).astype(\n np.uint8\n)\nlab_img = label(imread(\"ext-figures/aachen_label.png\")[::4, ::4] == 26)[75:150]\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 8))\nax1.imshow(car_img)\nax1.set_title(\"Input Image\")\n\nplt.colorbar(ax2.imshow(lab_img, cmap=\"nipy_spectral\"))\nax2.set_title(\"Labeled Image\")\n\n\n# # Shape Analysis\n# We can perform shape analysis on the image and calculate basic shape parameters for each object\n\n# In[25]:\n\n\nfrom skimage.measure import regionprops\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.collections import PatchCollection\n\n# shape analysis\nall_regions = regionprops(lab_img)\n\nfig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100)\nax1.imshow(car_img)\nprint(\"Found \", len(all_regions), \"regions\")\nbbox_list = []\nfor c_reg in all_regions:\n ax1.plot(c_reg.centroid[1], c_reg.centroid[0], \"o\", markersize=5)\n bbox_list += [\n Rectangle(\n xy=(c_reg.bbox[1], c_reg.bbox[0]),\n width=c_reg.bbox[3] - c_reg.bbox[1],\n height=c_reg.bbox[2] - c_reg.bbox[0],\n )\n ]\nc_bb_patch = PatchCollection(\n bbox_list, facecolor=\"none\", edgecolor=\"red\", linewidth=4, alpha=0.5\n)\nax1.add_collection(c_bb_patch)\n\n\n# # Statistics\n# We can then generate a table full of these basic parameters for each object. In this case, we add color as an additional description\n\n# In[26]:\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nimport webcolors\nimport pandas as pd\nfrom skimage.morphology import erosion, disk\n\n\ndef ed_img(in_img):\n # shrink an image to a few pixels\n cur_img = in_img.copy()\n while cur_img.max() > 0:\n last_img = cur_img\n cur_img = erosion(cur_img, disk(1))\n return last_img\n\n\n# guess color name based on rgb value\ncolor_name_class = KNeighborsClassifier(1)\nc_names = sorted(webcolors.css3_names_to_hex.keys())\ncolor_name_class.fit([tuple(webcolors.name_to_rgb(k)) for k in c_names], c_names)\n\n\nreg_df = pd.DataFrame(\n [\n dict(\n label=c_reg.label,\n bbox=c_reg.bbox,\n area=c_reg.area,\n centroid=c_reg.centroid,\n color=color_name_class.predict(\n np.mean(car_img[ed_img(lab_img == c_reg.label)], 0)[:3].reshape((1, -1))\n )[0],\n )\n for c_reg in all_regions\n ]\n)\nfig, m_axs = plt.subplots(len(all_regions), 1, figsize=(3, 14))\nfor c_ax, c_reg in zip(m_axs, all_regions):\n c_ax.imshow(car_img[c_reg.bbox[0] : c_reg.bbox[2], c_reg.bbox[1] : c_reg.bbox[3]])\n c_ax.axis(\"off\")\n c_ax.set_title(\"Label {}\".format(c_reg.label))\nreg_df\n\n\n# Anisotropy: What is it?\n# ===\n# By definition (New Oxford American): ```varying in magnitude according to the direction of measurement.```\n#\n# - It allows us to define metrics in respect to one another and thereby characterize shape.\n# - Is it tall and skinny, short and fat, or perfectly round\n#\n# ***\n#\n# Due to its very vague definition, it can be mathematically characterized in many different very much unequal ways (in all cases 0 represents a sphere)\n#\n# $$ Aiso1 = \\frac{\\text{Longest Side}}{\\text{Shortest Side}} - 1 $$\n#\n# $$ Aiso2 = \\frac{\\text{Longest Side}-\\text{Shortest Side}}{\\text{Longest Side}} $$\n#\n# $$ Aiso3 = \\frac{\\text{Longest Side}}{\\text{Average Side Length}} - 1 $$\n#\n# $$ Aiso4 = \\frac{\\text{Longest Side}-\\text{Shortest Side}}{\\text{Average Side Length}} $$\n#\n# $$ \\cdots \\rightarrow \\text{ ad nauseum} $$\n\n# In[27]:\n\n\nfrom collections import defaultdict\nfrom skimage.measure import regionprops\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nxx, yy = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100))\n\n\ndef side_len(c_reg):\n return sorted([c_reg.bbox[3] - c_reg.bbox[1], c_reg.bbox[2] - c_reg.bbox[0]])\n\n\naiso_funcs = [\n lambda x: side_len(x)[-1] / side_len(x)[0] - 1,\n lambda x: (side_len(x)[-1] - side_len(x)[0]) / side_len(x)[-1],\n lambda x: side_len(x)[-1] / np.mean(side_len(x)) - 1,\n lambda x: (side_len(x)[-1] - side_len(x)[0]) / np.mean(side_len(x)),\n]\n\n\ndef ell_func(a, b):\n return np.sqrt(np.square(xx / a) + np.square(yy / b)) <= 1\n\n\n# In[28]:\n\n\nfrom matplotlib.animation import FuncAnimation\nfrom IPython.display import HTML\n\nfig, m_axs = plt.subplots(2, 3, figsize=(12, 10), dpi=120)\nab_list = [\n (2, 2),\n (2, 3),\n (2, 4),\n (2, 5),\n (1.5, 5),\n (1, 5),\n (0.5, 5),\n (0.1, 5),\n (0.05, 5),\n]\nfunc_pts = defaultdict(list)\n\n\ndef update_frame(i):\n plt.cla()\n a, b = ab_list[i]\n c_img = ell_func(a, b)\n m_axs[0, 0].imshow(c_img, cmap=\"gist_earth\")\n reg_info = regionprops(c_img.astype(int))[0]\n m_axs[0, 0].set_title(\"Shape #{}\".format(i + 1))\n for j, (c_func, c_ax) in enumerate(zip(aiso_funcs, m_axs.flatten()[1:]), 1):\n func_pts[j] += [c_func(reg_info)]\n c_ax.plot(func_pts[j], \"r-\")\n c_ax.set_title(\"Anisotropy #{}\".format(j))\n c_ax.set_ylim(-0.1, 3)\n m_axs.flatten()[-1].axis(\"off\")\n\n\n# write animation frames\nanim_code = FuncAnimation(\n fig, update_frame, frames=len(ab_list) - 1, interval=500, repeat_delay=1000\n).to_html5_video()\nplt.close(\"all\")\nHTML(anim_code)\n\n\n# # Useful Statistical Tools: Principal Component Analysis\n#\n# While many of the topics covered in Linear Algebra and Statistics courses might not seem very applicable to real problems at first glance, at least a few of them come in handy for dealing distributions of pixels _(they will only be briefly covered, for more detailed review look at some of the suggested material)_\n#\n# ### Principal Component Analysis\n# Similar to K-Means insofar as we start with a series of points in a vector space and want to condense the information. With PCA instead of searching for distinct groups, we try to find a linear combination of components which best explain the variance in the system.\n#\n# ***\n#\n# As an example we will use a very simple example from spectroscopy\n\n# In[29]:\n\n\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ncm_dm = np.linspace(1000, 4000, 300)\n\n\ndef peak(cent, wid, h):\n return h / (wid * np.sqrt(2 * np.pi)) * np.exp(-np.square((cm_dm - cent) / wid))\n\n\ndef peaks(plist):\n return np.sum(\n np.stack([peak(cent, wid, h) for cent, wid, h in plist], 0), 0\n ) + np.random.uniform(0, 1, size=cm_dm.shape)\n\n\nfat_curve = [(2900, 100, 500), (1680, 200, 400)]\nprotein_curve = [(2900, 50, 200), (3400, 100, 600), (1680, 200, 300)]\nnoise_curve = [(3000, 50, 1)]\n\nfig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(12, 6))\n\nax1.plot(cm_dm, peaks(fat_curve))\nax1.set_title(\"Fat IR Spectra\")\n\nax2.plot(cm_dm, peaks(protein_curve))\nax2.set_title(\"Protein IR Spectra\")\n\nax0.plot(cm_dm, peaks(noise_curve))\nax0.set_title(\"Noise IR Spectra\")\n\nax0.set_ylim(ax2.get_ylim())\nax2.set_ylim(ax2.get_ylim())\n\npd.DataFrame({\"cm^(-1)\": cm_dm, \"intensity\": peaks(protein_curve)}).head(10)\n\n\n# # Test Dataset of a number of curves\n# We want to sort cells or samples into groups of being more fat like or more protein like.\n#\n# ## How can we analyze this data without specifically looking for peaks or building models?\n\n# In[30]:\n\n\ntest_data = np.stack(\n [\n peaks(c_curve)\n for _ in range(20)\n for c_curve in [protein_curve, fat_curve, noise_curve]\n ],\n 0,\n)\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))\n\nax1.plot(test_data[:4].T, \".-\")\nax1.legend([\"Curve 1\", \"Curve 2\", \"Curve 3\", \"Curve 4\"])\nax2.scatter(\n test_data[:, 0],\n test_data[:, 1],\n c=range(test_data.shape[0]),\n s=20,\n cmap=\"nipy_spectral\",\n)\n\n\n# In[31]:\n\n\nfrom sklearn.decomposition import PCA\n\npca_tool = PCA(5)\npca_tool.fit(test_data)\n\n\n# # Useful Statistical Tools: Principal Component Analysis\n#\n# The first principal component provides\n#\n# The second principal component is then related to the unique information seperating chicken from corn prices but neither indices directly themselves (maybe the cost of antibiotics)\n\n# In[32]:\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))\nscore_matrix = pca_tool.transform(test_data)\nax1.plot(cm_dm, pca_tool.components_[0, :], label=\"Component #1\")\nax1.plot(\n cm_dm,\n pca_tool.components_[1, :],\n label=\"Component #2\",\n alpha=pca_tool.explained_variance_ratio_[0],\n)\nax1.plot(\n cm_dm,\n pca_tool.components_[2, :],\n label=\"Component #3\",\n alpha=pca_tool.explained_variance_ratio_[1],\n)\nax1.legend()\nax2.scatter(score_matrix[:, 0], score_matrix[:, 1])\nax2.set_xlabel(\"Component 1\")\nax2.set_ylabel(\"Component 2\")\n\n\n# In[33]:\n\n\nfig, ax1 = plt.subplots(1, 1, figsize=(8, 4), dpi=120)\nax1.bar(\n x=range(pca_tool.explained_variance_ratio_.shape[0]),\n height=100 * pca_tool.explained_variance_ratio_,\n)\nax1.set_xlabel(\"Components\")\nax1.set_ylabel(\"Explained Variance (%)\")\n\n\n# # Principal Component Analysis\n# ## scikit-learn [Face Analyis](http://scikit-learn.org/stable/auto_examples/decomposition/plot_faces_decomposition.html)\n#\n# Here we show a more imaging related example from the scikit-learn documentation where we do basic face analysis with scikit-learn.\n#\n\n# In[34]:\n\n\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn import decomposition\n\n# Load faces data\ntry:\n dataset = fetch_olivetti_faces(shuffle=True, random_state=2018, data_home=\".\")\n faces = dataset.data\nexcept Exception as e:\n print(\"Face data not available\", e)\n faces = np.random.uniform(0, 1, (400, 4096))\n\nn_samples, n_features = faces.shape\nn_row, n_col = 2, 3\nn_components = n_row * n_col\nimage_shape = (64, 64)\n\n# global centering\nfaces_centered = faces - faces.mean(axis=0)\n\n# local centering\nfaces_centered -= faces_centered.mean(axis=1).reshape(n_samples, -1)\n\nprint(\"Dataset consists of %d faces\" % n_samples)\n\n\n# In[35]:\n\n\ndef plot_gallery(title, images, n_col=n_col, n_row=n_row):\n plt.figure(figsize=(2.0 * n_col, 2.26 * n_row))\n plt.suptitle(title, size=16)\n for i, comp in enumerate(images):\n plt.subplot(n_row, n_col, i + 1)\n vmax = max(comp.max(), -comp.min())\n plt.imshow(\n comp.reshape(image_shape),\n cmap=plt.cm.gray,\n interpolation=\"nearest\",\n vmin=-vmax,\n vmax=vmax,\n )\n plt.xticks(())\n plt.yticks(())\n plt.subplots_adjust(0.01, 0.05, 0.99, 0.93, 0.04, 0.0)\n\n\n# #############################################################################\n# List of the different estimators, whether to center and transpose the\n# problem, and whether the transformer uses the clustering API.\nestimators = [\n (\n \"Eigenfaces - PCA using randomized SVD\",\n decomposition.PCA(\n n_components=n_components, svd_solver=\"randomized\", whiten=True\n ),\n True,\n )\n]\n# #############################################################################\n# Plot a sample of the input data\n\nplot_gallery(\"First centered Olivetti faces\", faces_centered[:n_components])\n\n# #############################################################################\n# Do the estimation and plot it\n\nfor name, estimator, center in estimators:\n print(\"Extracting the top %d %s...\" % (n_components, name))\n data = faces\n if center:\n data = faces_centered\n estimator.fit(data)\n\n if hasattr(estimator, \"cluster_centers_\"):\n components_ = estimator.cluster_centers_\n else:\n components_ = estimator.components_\n plot_gallery(name, components_[:n_components])\n\nplt.show()\n\n\n# # Applied PCA: Shape Tensor\n#\n# ## How do these statistical analyses help us?\n# Going back to a single cell, we have the a distribution of $x$ and $y$ values.\n# - are not however completely independent\n# - greatest variance does not normally lie in either x nor y alone.\n#\n# A principal component analysis of the voxel positions, will calculate two new principal components (the components themselves are the relationships between the input variables and the scores are the final values.)\n# - An optimal rotation of the coordinate system\n\n# We start off by calculating the covariance matrix from the list of $x$, $y$, and $z$ points that make up our object of interest.\n#\n# $$ COV(I_{id}) = \\frac{1}{N} \\sum_{\\forall\\vec{v}\\in I_{id}} \\begin{bmatrix}\n# \\vec{v}_x\\vec{v}_x & \\vec{v}_x\\vec{v}_y & \\vec{v}_x\\vec{v}_z\\\\\n# \\vec{v}_y\\vec{v}_x & \\vec{v}_y\\vec{v}_y & \\vec{v}_y\\vec{v}_z\\\\\n# \\vec{v}_z\\vec{v}_x & \\vec{v}_z\\vec{v}_y & \\vec{v}_z\\vec{v}_z\n# \\end{bmatrix} $$\n#\n# We then take the eigentransform of this array to obtain the eigenvectors (principal components, $\\vec{\\Lambda}_{1\\cdots 3}$) and eigenvalues (scores, $\\lambda_{1\\cdots 3}$)\n#\n# $$ COV(I_{id}) \\longrightarrow \\underbrace{\\begin{bmatrix}\n# \\vec{\\Lambda}_{1x} & \\vec{\\Lambda}_{1y} & \\vec{\\Lambda}_{1z} \\\\\n# \\vec{\\Lambda}_{2x} & \\vec{\\Lambda}_{2y} & \\vec{\\Lambda}_{2z} \\\\\n# \\vec{\\Lambda}_{3x} & \\vec{\\Lambda}_{3y} & \\vec{\\Lambda}_{3z}\n# \\end{bmatrix}}_{\\textrm{Eigenvectors}} * \\underbrace{\\begin{bmatrix}\n# \\lambda_1 & 0 & 0 \\\\\n# 0 & \\lambda_2 & 0 \\\\\n# 0 & 0 & \\lambda_3\n# \\end{bmatrix}}_{\\textrm{Eigenvalues}} * \\underbrace{\\begin{bmatrix}\n# \\vec{\\Lambda}_{1x} & \\vec{\\Lambda}_{1y} & \\vec{\\Lambda}_{1z} \\\\\n# \\vec{\\Lambda}_{2x} & \\vec{\\Lambda}_{2y} & \\vec{\\Lambda}_{2z} \\\\\n# \\vec{\\Lambda}_{3x} & \\vec{\\Lambda}_{3y} & \\vec{\\Lambda}_{3z}\n# \\end{bmatrix}^{T}}_{\\textrm{Eigenvectors}} $$\n# The principal components tell us about the orientation of the object and the scores tell us about the corresponding magnitude (or length) in that direction.\n\n# In[36]:\n\n\nfrom IPython.display import Markdown\nfrom skimage.io import imread\nfrom skimage.morphology import label\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nseg_img = imread(\"ext-figures/aachen_label.png\") == 26\nseg_img = seg_img[::4, ::4]\nseg_img = seg_img[110:130:2, 378:420:3] > 0\nseg_img = np.pad(seg_img, 3, mode=\"constant\")\nseg_img[0, 0] = 0\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\nax1.matshow(seg_img, cmap=\"bone_r\")\n\n\n# In[37]:\n\n\nfrom sklearn.decomposition import PCA\n\nx_coord, y_coord = np.where(seg_img > 0)\nxy_pts = np.stack([x_coord, y_coord], 1)\nshape_pca = PCA()\nshape_pca.fit(xy_pts)\npca_xy_vals = shape_pca.transform(xy_pts)\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\nax1.plot(pca_xy_vals[:, 0], pca_xy_vals[:, 1], \"rs\", markersize=10)\n\n\n# In[38]:\n\n\n_, (ax1) = plt.subplots(1, 1, figsize=(7, 7), dpi=150)\n\n\nax1.plot(\n xy_pts[:, 0] - np.mean(xy_pts[:, 0]),\n xy_pts[:, 1] - np.mean(xy_pts[:, 1]),\n \"rs\",\n label=\"Points\",\n)\nax1.plot(\n [0, shape_pca.explained_variance_[0] / 2 * shape_pca.components_[0, 0]],\n [0, shape_pca.explained_variance_[0] / 2 * shape_pca.components_[0, 1]],\n \"b-\",\n label=\"PCA1\",\n)\nax1.plot(\n [0, shape_pca.explained_variance_[1] / 2 * shape_pca.components_[1, 0]],\n [0, shape_pca.explained_variance_[1] / 2 * shape_pca.components_[1, 1]],\n \"g-\",\n label=\"PCA2\",\n)\nax1.legend()\n\n\n# # Principal Component Analysis: Take home message\n#\n# - We calculate the statistical distribution individually for $x$, $y$, and $z$ and the 'correlations' between them.\n# - From these values we can estimate the orientation in the direction of largest variance\n# - We can also estimate magnitude\n# - These functions are implemented as ```princomp``` or ```pca``` in various languages and scale well to very large datasets.\n\n# # Principal Component Analysis: Elliptical Model\n#\n#\n# While the eigenvalues and eigenvectors are in their own right useful\n# - Not obvious how to visually represent these tensor objects\n# - Ellipsoidal (Ellipse in 2D) representation alleviates this issue\n#\n# ### Ellipsoidal Representation\n# 1. Center of Volume is calculated normally\n# 1. Eigenvectors represent the unit vectors for the semiaxes of the ellipsoid\n# 1. $\\sqrt{\\text{Eigenvalues}}$ is proportional to the length of the semiaxis ($\\mathcal{l}=\\sqrt{5\\lambda_i}$), derivation similar to moment of inertia tensor for ellipsoids.\n#\n# ***\n\n# # Meshing\n#\n#\n# Constructing a mesh for an image provides very different information than the image data itself. Most crucially this comes when looking at physical processes like deformation.\n#\n# While the images are helpful for visualizing we rarely have models for quantifying how difficult it is to turn a pixel __off__\n#\n# If the image is turned into a mesh we now have a list of vertices and edges. For these vertices and edges we can define forces. For example when looking at stress-strain relationships in mechanics using Hooke's Model\n# $$ \\vec{F}=k (\\vec{x}_0-\\vec{x}) $$\n# the force needed to stretch one of these edges is proportional to how far it is stretched.\n\n# # Meshing\n#\n#\n# Since we uses voxels to image and identify the volume we can use the voxels themselves as an approimation for the surface of the structure.\n# - Each 'exposed' face of a voxel belongs to the surface\n#\n# From this we can create a mesh by\n#\n# - adding each exposed voxel face to a list of surface squares.\n# - adding connectivity information for the different squares (shared edges and vertices)\n#\n# A wide variety of methods of which we will only graze the surface (http://en.wikipedia.org/wiki/Image-based_meshing)\n\n# # Marching Cubes\n#\n# ### Why\n# Voxels are very poor approximations for the surface and are very rough (they are either normal to the x, y, or z axis and nothing between). Because of their inherently orthogonal surface normals, any analysis which utilizes the surface normal to calculate another value (growth, curvature, etc) is going to be very inaccurate at best and very wrong at worst.\n#\n# ### [How](https://en.wikipedia.org/wiki/Marching_cubes)\n# The image is processed one voxel at a time and the neighborhood (not quite the same is the morphological definition) is checked at every voxel. From this configuration of values, faces are added to the mesh to incorporate the most simple surface which would explain the values.\n#\n# [Marching tetrahedra](http://en.wikipedia.org/wiki/Marching_tetrahedra) is for some applications a better suited approach\n\n# # Next Time on QBI\n#\n#\n# So while bounding box and ellipse-based models are useful for many object and cells, they do a very poor job with other samples\n#\n#\n# ***\n#\n# ### Why\n# - We assume an entity consists of connected pixels (wrong)\n# - We assume the objects are well modeled by an ellipse (also wrong)\n#\n# ### What to do?\n#\n# - Is it 3 connected objects which should all be analzed seperately?\n# - If we could __divide it__, we could then analyze each spart as an ellipse\n# - Is it one network of objects and we want to know about the constrictions?\n# - Is it a cell or organelle with docking sites for cell?\n# - Neither extents nor anisotropy are very meaningful, we need a __more specific metric__ which can characterize\n\n# In[ ]:\n", "meta": {"hexsha": "0a921cab92da29375a894482feadbd3c8f34fcfd", "size": 41585, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/06-ShapeAnalysis.py", "max_stars_repo_name": "kmader/qbi-2019-py", "max_stars_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-06T16:20:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T03:38:02.000Z", "max_issues_repo_path": "Lectures/06-ShapeAnalysis.py", "max_issues_repo_name": "kmader/qbi-2019-py", "max_issues_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-06T16:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-07T13:02:17.000Z", "max_forks_repo_path": "Lectures/06-ShapeAnalysis.py", "max_forks_repo_name": "kmader/qbi-2019-py", "max_forks_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-09T10:43:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T10:43:55.000Z", "avg_line_length": 30.0686912509, "max_line_length": 360, "alphanum_fraction": 0.6305879524, "include": true, "reason": "import numpy", "num_tokens": 11983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.21206880435710534, "lm_q1q2_score": 0.09366506622810616}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.4\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# + {\"colab_type\": \"text\", \"id\": \"6Tmmlr92MZVj\", \"slideshow\": {\"slide_type\": \"slide\"}, \"cell_type\": \"markdown\"}\n# # Probabilistic Programming and Bayesian Methods for Hackers Chapter 1\n#\n# \n# \n# \n#
\n# Run in Google Colab\n# \n# View source on GitHub\n#
\n#
\n#
\n#
\n#\n# Original content ([this Jupyter notebook](https://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb)) created by Cam Davidson-Pilon ([`@Cmrn_DP`](https://twitter.com/Cmrn_DP))\n#\n# Ported to [Tensorflow Probability](https://www.tensorflow.org/probability/) by Matthew McAteer ([`@MatthewMcAteer0`](https://twitter.com/MatthewMcAteer0)) and Bryan Seybold, with help from the TFP team at Google ([`tfprobability@tensorflow.org`](mailto:tfprobability@tensorflow.org)).\n#\n# Welcome to Bayesian Methods for Hackers. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!\n#\n# ---\n# ### Table of Contents\n# - Dependencies & Prerequisites\n# - The Philosophy of Bayesian Inference\n# - The Bayesian state of mind\n# - Bayesian Inference in Practice\n# - Are frequentist methods incorrect then?\n# - Our Bayesian framework\n# - Example: Mandatory coin-flip example\n# - Example: Bug, or just sweet, unintended feature?\n# - Probability Distributions\n# - Discrete Case\n# - Continuous Case\n# - But what is $\\lambda \\;$?\n# - Example: Inferring behaviour from text-message data\n# - Introducing our first hammer: Tensorflow Probability\n# - specify the joint log-density\n# - Specify the posterior sampler\n# - Execute the TF graph to sample from the posterior\n# - Plot the Results\n# - Interpretation\n# - Exercises\n# - References\n\n# + {\"colab_type\": \"text\", \"id\": \"YcJ8nEDVH30J\", \"cell_type\": \"markdown\"}\n# ### Dependencies & Prerequisites\n#\n#
\n# Tensorflow Probability is part of the colab default runtime, so you don't need to install Tensorflow or Tensorflow Probability if you're running this in the colab. \n#
\n# If you're running this notebook in Jupyter on your own machine (and you have already installed Tensorflow), you can use the following\n#
\n#
    \n#
  • For the most recent nightly installation: pip3 install -q tfp-nightly
  • \n#
  • For the most recent stable TFP release: pip3 install -q --upgrade tensorflow-probability
  • \n#
  • For the most recent stable GPU-connected version of TFP: pip3 install -q --upgrade tensorflow-probability-gpu
  • \n#
  • For the most recent nightly GPU-connected version of TFP: pip3 install -q tfp-nightly-gpu
  • \n#
\n# Again, if you are running this in a Colab, Tensorflow and TFP are already installed\n#
\n# -\n\n# ## 2020-02-07\n#\n# The following code cell contains bizarre comment formatting, like `#@title` ... `{ display-mode: \"form\" }` and `#@markdown`. Is that Colab-specific Markdown?\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\n#@title Imports and Global Variables (make sure to run this cell) { display-mode: \"form\" }\n# 2020-02-07: wait, why am I importing from __future__ if I'm running python 3.6? I'll do it anyway and figure out why later.\nfrom __future__ import absolute_import, division, print_function\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\n#@markdown This sets the warning status (default is `ignore`, since this notebook runs correctly)\n# 2020-02-07: you know what? Let's always see warnings.\nwarning_status = \"always\" #@param [\"ignore\", \"always\", \"module\", \"once\", \"default\", \"error\"]\nimport warnings\nwarnings.filterwarnings(warning_status)\nwith warnings.catch_warnings():\n warnings.filterwarnings(warning_status, category=DeprecationWarning)\n warnings.filterwarnings(warning_status, category=UserWarning)\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\nimport numpy as np\nimport os\n#@markdown This sets the styles of the plotting (default is styled like plots from [FiveThirtyeight.com](https://fivethirtyeight.com/))\nmatplotlib_style = 'fivethirtyeight' #@param ['fivethirtyeight', 'bmh', 'ggplot', 'seaborn', 'default', 'Solarize_Light2', 'classic', 'dark_background', 'seaborn-colorblind', 'seaborn-notebook']\nimport matplotlib.pyplot as plt; plt.style.use(matplotlib_style)\nimport matplotlib.axes as axes\nfrom matplotlib.patches import Ellipse\n# %matplotlib inline\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\nimport seaborn as sns; sns.set_context('notebook')\nfrom IPython.core.pylabtools import figsize\n#@markdown This sets the resolution of the plot outputs (`retina` is the highest resolution)\nnotebook_screen_res = 'retina' #@param ['retina', 'png', 'jpeg', 'svg', 'pdf']\n# %config InlineBackend.figure_format = notebook_screen_res\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\nimport tensorflow as tf\n## 2020-02-07: According to https://www.tensorflow.org/guide/eager\n## In Tensorflow 2.0, eager execution is enabled by default.\n##\n# tfe = tf.contrib.eager\ntf.__version__\n# -\ntf.executing_eagerly()\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\n## 2020-02-07: this cell is made obsolete by TF 2.0. (Maybe I could open some pull requests to modernize this tutorial,\n## but then I'd have to clone it again and not make these ad-hoc comments to myself)\n##\n## Eager Execution\n##@markdown Check the box below if you want to use [Eager Execution](https://www.tensorflow.org/guide/eager)\n##@markdown Eager execution provides An intuitive interface, Easier debugging, and a control flow comparable to Numpy. You can read more about it on the [Google AI Blog](https://ai.googleblog.com/2017/10/eager-execution-imperative-define-by.html)\n# use_tf_eager = False #@param {type:\"boolean\"}\n# # Use try/except so we can easily re-execute the whole notebook.\n# if use_tf_eager:\n# try:\n# tf.enable_eager_execution()\n# except:\n# pass\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\nimport tensorflow_probability as tfp\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\n\n# -\n\n# **2020-02-07:** someday, this Tensorflow boilerplate will make sense to me, but today is not that day.\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\ndef evaluate(tensors):\n \"\"\"Evaluates Tensor or EagerTensor to Numpy `ndarray`s.\n Args:\n tensors: Object of `Tensor` or EagerTensor`s; can be `list`, `tuple`,\n `namedtuple` or combinations thereof.\n \n Returns:\n ndarrays: Object with same structure as `tensors` except with `Tensor` or\n `EagerTensor`s replaced by Numpy `ndarray`s.\n \"\"\"\n if tf.executing_eagerly():\n return tf.contrib.framework.nest.pack_sequence_as(\n tensors,\n [t.numpy() if tf.contrib.framework.is_tensor(t) else t\n for t in tf.contrib.framework.nest.flatten(tensors)])\n return sess.run(tensors)\n\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\n# 2020-02-07: this is strikingly out of place. Why are we manually defining a colormap?\nclass _TFColor(object):\n \"\"\"Enum of colors used in TF docs.\"\"\"\n red = '#F15854'\n blue = '#5DA5DA'\n orange = '#FAA43A'\n green = '#60BD68'\n pink = '#F17CB0'\n brown = '#B2912F'\n purple = '#B276B2'\n yellow = '#DECF3F'\n gray = '#4D4D4D'\n def __getitem__(self, i):\n return [\n self.red,\n self.orange,\n self.green,\n self.blue,\n self.pink,\n self.brown,\n self.purple,\n self.yellow,\n self.gray,\n ][i % 9]\nTFColor = _TFColor()\n\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\ndef session_options(enable_gpu_ram_resizing=True, enable_xla=False):\n \"\"\"\n Allowing the notebook to make use of GPUs if they're available.\n \n XLA (Accelerated Linear Algebra) is a domain-specific compiler for linear \n algebra that optimizes TensorFlow computations.\n \"\"\"\n config = tf.compat.v1.ConfigProto()\n config.log_device_placement = True\n if enable_gpu_ram_resizing:\n # `allow_growth=True` makes it possible to connect multiple colabs to your\n # GPU. Otherwise the colab malloc's all GPU ram.\n config.gpu_options.allow_growth = True\n if enable_xla:\n # Enable on XLA. https://www.tensorflow.org/performance/xla/.\n config.graph_options.optimizer_options.global_jit_level = (\n tf.OptimizerOptions.ON_1)\n return config\n\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"RUEQ5hdvKZLB\"}\n# 2020-02-07: in this cell and the one above it, I had to manually change the namespaces \n# from tf. to tf.compat.v1. This does not strike me as elegant. What's the recommended TF 2 way of doing this?\ndef reset_sess(config=None):\n \"\"\"\n Convenience function to create the TF graph & session or reset them.\n \"\"\"\n if config is None:\n config = session_options(enable_gpu_ram_resizing=True, enable_xla=False)\n global sess\n tf.compat.v1.reset_default_graph()\n try:\n sess.close()\n except:\n pass\n sess = tf.compat.v1.InteractiveSession(config=config)\n\nreset_sess()\n\n# + {\"colab_type\": \"text\", \"id\": \"dXqjzSnXRRr3\", \"cell_type\": \"markdown\"}\n# ## The Philosophy of Bayesian Inference\n#\n# >You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, even more difficult, test too! You are starting to believe that there may be no bugs in this code...\n#\n# If you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more confident about our code, but still not certain. Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives.\n#\n#\n\n# + {\"colab_type\": \"text\", \"id\": \"YO2eSwZQRRqv\", \"cell_type\": \"markdown\"}\n# ## The Bayesian state of mind\n# Bayesian inference differs from more traditional statistical inference by preserving uncertainty. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving certainty from randomness? To reconcile this, we need to start thinking like Bayesians.\n#\n# The Bayesian world-view interprets probability as measure of believability in an event, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability.\n#\n# For this to be clearer, we consider an alternative interpretation of probability: Frequentist, known as the more classical version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the probability of plane accidents under a frequentist philosophy is interpreted as the long-term frequency of plane accidents. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability.\n#\n# Bayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of belief, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate A will win?\n#\n# Notice in the paragraph above, I assigned the belief (probability) measure to an individual, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different information about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:\n#\n# * I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is your belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result.\n#\n# * Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug.\n#\n# * A medical patient is exhibiting symptoms *x*, *y* and *z*. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs.\n#\n# This philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be trained to think like a frequentist.\n#\n# To align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the prior probability.\n#\n# John Maynard Keynes, a great economist and thinker, said \"When the facts change, I change my mind. What do you do, sir?\" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A|X)$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the posterior probability so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:\n#\n#\n# 1. $P(A)$: the coin has a 50 percent chance of being Heads. $P(A|X)$: You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.\n#\n# 2. $P(A)$: This big, complex code likely has a bug in it. $P(A|X)$: The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.\n#\n# 3. $P(A)$: The patient could have any number of diseases. $P(A|X)$: Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.\n#\n# It's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we re-weighted the prior to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others).\n#\n# By introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes less wrong. This is the alternative side of the prediction coin, where typically we try to be more right.\n#\n#\n#\n#\n#\n\n# + {\"colab_type\": \"text\", \"id\": \"FXUBMaYsRWvl\", \"cell_type\": \"markdown\"}\n# ## Bayesian Inference in Practice\n# If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return probabilities.\n#\n# For example, in our debugging problem above, calling the frequentist function with the argument \"My code passed all $X$ tests; is my code bug-free?\" would return a YES. On the other hand, asking our Bayesian function \"Often my code has bugs. My code passed all $X$ tests; is my code bug-free?\" would return something very different: probabilities of YES and NO. The function might return:\n#\n# >YES, with probability 0.8; NO, with probability 0.2\n#\n# This is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument: \"Often my code has bugs\". This parameter is the prior. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences.\n#\n# ### Incorporating evidence\n# As we acquire more and more instances of evidence, our prior belief is washed out by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like \"I expect the sun to explode today\", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.\n#\n# Denote $N$ as the number of instances of evidence we possess. As we gather an infinite amount of evidence, say as $N→∞,$ our Bayesian results (often) align with frequentist results. Hence for large N, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more unstable: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we preserve the uncertainty that reflects the instability of statistical inference of a small N dataset.\n#\n# One may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[[1]](#scrollTo=nDdph0r1ABCn), before making such a decision:\n#\n# Sample sizes are never large. If $N$, is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$, is \"large enough,\" you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$, is never enough because if it were \"enough\" you'd already be on to the next problem for which you need more data.\n#\n#\n\n# + {\"colab_type\": \"text\", \"id\": \"rACyvZBVdqB9\", \"cell_type\": \"markdown\"}\n# ## Are frequentist methods incorrect then?\n# No.\n#\n# Frequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.\n#\n# ### A note on *Big Data*\n# Paradoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [[2]](#scrollTo=nDdph0r1ABCn)[[3]](#scrollTo=nDdph0r1ABCn). Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask \"Do I really have big data?\")\n#\n# The much more difficult analytic problems involve medium data and, especially troublesome, really small data. Using a similar argument as Gelman's above, if big data problems are big enough to be readily solved, then we should be more interested in the not-quite-big enough datasets.\n\n# + {\"colab_type\": \"text\", \"id\": \"TTUDkI8peKw6\", \"cell_type\": \"markdown\"}\n# ## Our Bayesian framework\n# We are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a prior belief in event A, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.\n#\n# Secondly, we observe our evidence. To continue our buggy-code example: if our code passes X tests, we want to update our belief to incorporate this. We call this new belief the posterior probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:\n#\n# $$ P(A|X) = \\frac{P(X | A) P(A) }{P(X) } $$\n#\n# $$ P(A|X) \\propto{P(X | A) P(A) } $$\n#\n# NOTE: ($\\propto$ is \"proportional to\")\n#\n#\n# The above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A|X)$.\n\n# + {\"colab_type\": \"text\", \"id\": \"DkB3Ou8UjW-F\", \"cell_type\": \"markdown\"}\n#\n# ## Example: Mandatory coin-flip example\n# Every statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it p, but have no prior opinion on what p might be.\n#\n# We begin to flip a coin, and record the observations: either H or T. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data.\n#\n# Below we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips), while also demonstrating some of the best practices when it comes to evaluating tensors and plotting the data. First, the easy part: We define the values in our Tensorflow graph\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"yFd9GboD7hVV\"}\n# Build Graph\nrv_coin_flip_prior = tfp.distributions.Bernoulli(probs=0.5, dtype=tf.int32)\n\nnum_trials = tf.constant([0,1, 2, 3, 4, 5, 8, 15, 50, 500, 1000, 2000])\n\ncoin_flip_data = rv_coin_flip_prior.sample(num_trials[-1])\n\n# prepend a 0 onto tally of heads and tails, for zeroth flip\ncoin_flip_data = tf.pad(coin_flip_data,tf.constant([[1, 0,]]),\"CONSTANT\")\n\n# compute cumulative headcounts from 0 to 2000 flips, and then grab them at each of num_trials intervals\ncumulative_headcounts = tf.gather(tf.cumsum(coin_flip_data), num_trials)\n\nrv_observed_heads = tfp.distributions.Beta(\n concentration1=tf.cast(1 + cumulative_headcounts, tf.float32),\n concentration0=tf.cast(1 + num_trials - cumulative_headcounts, tf.float32))\n\nprobs_of_heads = tf.linspace(start=0., stop=1., num=100, name=\"linspace\")\nobserved_probs_heads = tf.transpose(rv_observed_heads.prob(probs_of_heads[:, tf.newaxis]))\n\n# + {\"colab_type\": \"text\", \"id\": \"eVh-ugqN8NRy\", \"cell_type\": \"markdown\"}\n# Next we move onto executing the graph. When it comes to calculations that need to be made frequently and repeatedly, this method of first-defining and then executing graphs provides a handy speed boost. We can actually use a custom `evaluate()` function that allows us to evaluate tensors whether we are operating in TF Graph mode, or whether we have Eager mode active. The function looks like the following:\n#\n# ```python\n#\n# def evaluate(tensors):\n# \"\"\"Evaluates Tensor or EagerTensor to Numpy `ndarray`s.\n# Args:\n# tensors: Object of `Tensor` or EagerTensor`s; can be `list`, `tuple`,\n# `namedtuple` or combinations thereof.\n#\n# Returns:\n# ndarrays: Object with same structure as `tensors` except with `Tensor` or\n# `EagerTensor`s replaced by Numpy `ndarray`s.\n# \"\"\"\n# if tf.executing_eagerly():\n# return tf.contrib.framework.nest.pack_sequence_as(\n# tensors,\n# [t.numpy() if tf.contrib.framework.is_tensor(t) else t\n# for t in tf.contrib.framework.nest.flatten(tensors)])\n# return sess.run(tensors)\n#\n# ```\n#\n# To plot the tensors, we need to convert them into numpy variables. One handy way of associating tensors with their corrresponding numpy variables is to append an underscore to the numpy-like arrays. For example, if the input to `evaluate()` is `variable`, then we assign that value to `variable_`. Below we see an example of how we use both `evaluate()` and this new styling.\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"Ex3djpOu7_-m\"}\n# Execute graph\n[num_trials_,\nprobs_of_heads_,\nobserved_probs_heads_,\ncumulative_headcounts_,\n] = evaluate([\n num_trials,\n probs_of_heads,\n observed_probs_heads,\n cumulative_headcounts\n])\n\n# + {\"colab_type\": \"text\", \"id\": \"IUAm6LEA8FFW\", \"cell_type\": \"markdown\"}\n# Finally, we move onto plotting our evaluated tensors in matplotlib.\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 697}, \"colab_type\": \"code\", \"id\": \"4fdWiFUT6H-A\", \"outputId\": \"a232d7e8-6825-4e41-f363-1f6c07b176e7\"}\n# For the already prepared, I'm using Binomial's conj. prior.\nplt.figure(figsize(16, 9))\nfor i in range(len(num_trials_)):\n sx = plt.subplot(len(num_trials_)/2, 2, i+1)\n plt.xlabel(\"$p$, probability of heads\") \\\n if i in [0, len(num_trials_)-1] else None\n plt.setp(sx.get_yticklabels(), visible=False)\n plt.plot(probs_of_heads_, observed_probs_heads_[i], \n label=\"observe %d tosses,\\n %d heads\" % (num_trials_[i], cumulative_headcounts_[i]))\n plt.fill_between(probs_of_heads_, 0, observed_probs_heads_[i], \n color=TFColor[3], alpha=0.4)\n plt.vlines(0.5, 0, 4, color=\"k\", linestyles=\"--\", lw=1)\n leg = plt.legend()\n leg.get_frame().set_alpha(0.4)\n plt.autoscale(tight=True)\n\n\nplt.suptitle(\"Bayesian updating of posterior probabilities\", y=1.02,\n fontsize=14)\nplt.tight_layout()\n\n# + {\"colab_type\": \"text\", \"id\": \"jTqKXlGRmKuh\", \"cell_type\": \"markdown\"}\n# The posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line).\n#\n# Notice that the plots are not always peaked at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what p is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased away from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.\n#\n# The next example is a simple demonstration of the mathematics of Bayesian inference.\n\n# + {\"colab_type\": \"text\", \"id\": \"5UKnxit-mevN\", \"cell_type\": \"markdown\"}\n# ## Example: Bug, or just sweet, unintended feature?\n# Let $A$ denote the event that our code has no bugs in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A)=p$.\n#\n# We are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.\n#\n# What is $P(X|A)$, i.e., the probability that the code passes $X$ tests given there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests.\n#\n# $P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event X occurring even though our code indeed has bugs (denoted $∼A$, spoken not $A$), or event $X$ without bugs $(A)$. $ P(X)$ can be represented as:\n\n# + {\"colab_type\": \"text\", \"id\": \"7rDu4o6DnjT7\", \"cell_type\": \"markdown\"}\n# $$ \\begin{align*}\n# P(A|X) &= \\frac{P(X | A) P(A) }{P(X) } \\\\\n# P(X) &= P(X \\text{ and } A) + P(X \\text{ and } \\sim A) \\\\\n# &= P(X|A)P(A) + P(X | \\sim A)P(\\sim A) \\\\\n# &= P(X|A)p + P(X | \\sim A)(1-p) \\end{align*} $$\n#\n\n# + {\"colab_type\": \"text\", \"id\": \"S48e_3wph3I_\", \"cell_type\": \"markdown\"}\n# We have already computed $P(X|A)$ above. On the other hand, $P(X|\\sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\\sim A)=0.5$. Then:\n#\n# $$ \\begin{align*}\n# P(A | X) &= \\frac{1\\cdot p}{ 1\\cdot p +0.5 (1-p) } \\\\\n# &= \\frac{ 2 p}{1+p} \\end{align*} $$\n#\n# This is the posterior probability. What does it look like as a function of our prior, $p\\in[0,1]$?\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 404}, \"colab_type\": \"code\", \"id\": \"MwjluXPenvAy\", \"outputId\": \"fc433206-8324-4d63-fafc-4f49127182eb\"}\n# Defining our range of probabilities\np = tf.linspace(start=0., stop=1., num=50)\n\n# Convert from TF to numpy.\n[p_] = evaluate([p])\n\n# Visualization.\nplt.figure(figsize=(12.5, 6))\nplt.plot(p_, 2*p_/(1+p_), color=TFColor[3], lw=3)\n#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=[\"#A60628\"])\nplt.scatter(0.2, 2*(0.2)/1.2, s=140, c=TFColor[3])\nplt.xlim(0, 1)\nplt.ylim(0, 1)\nplt.xlabel(r\"Prior, $P(A) = p$\")\nplt.ylabel(r\"Posterior, $P(A|X)$, with $P(A) = p$\")\nplt.title(r\"Are there bugs in my code?\");\n\n# + {\"colab_type\": \"text\", \"id\": \"dvcD8UWloYxn\", \"cell_type\": \"markdown\"}\n# We can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33.\n#\n# Recall that the prior is a probability: $p$ is the prior probability that there are no bugs, so $1 \\text{-} p$ is the prior probability that there are bugs.\n#\n# Similarly, our posterior is also a probability, with $P(A|X)$ the probability there is no bug given we saw all tests pass, hence $1 \\text{-} P(A|X)$ is the probability there is a bug given all tests passed. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities.\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 279}, \"colab_type\": \"code\", \"id\": \"Aot_QO3n1r4o\", \"outputId\": \"6aa056b4-43c4-4dd3-c616-5fa57028db59\"}\n# Defining our priors and posteriors\nprior = tf.constant([0.20, 0.80])\nposterior = tf.constant([1./3, 2./3])\n\n# Convert from TF to numpy.\n[\n prior_,\n posterior_,\n] = evaluate([\n prior,\n posterior,\n])\n\n\n# Our Simple Visualization\nplt.figure(figsize=(12.5, 4))\ncolours = [TFColor[0], TFColor[3]]\nplt.bar([0, .7], prior_, alpha=0.70, width=0.25,\n color=colours[0], label=\"prior distribution\",\n lw=\"3\", edgecolor=colours[0])\nplt.bar([0+0.25, .7+0.25], posterior_, alpha=0.7,\n width=0.25, color=colours[1],\n label=r\"posterior distribution\",\n lw=\"3\", edgecolor=colours[1])\n\nplt.xticks([0.20, .95], [\"Bugs Absent\", \"Bugs Present\"])\nplt.title(r\"Prior and Posterior probability of bugs present\")\nplt.ylabel(\"Probability\")\nplt.legend(loc=\"upper left\");\n\n# + {\"colab_type\": \"text\", \"id\": \"Xl6KbBeoCkiM\", \"cell_type\": \"markdown\"}\n# Notice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.\n#\n# This was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with probability distributions. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.\n\n# + {\"colab_type\": \"text\", \"id\": \"2zNt6157C0Cr\", \"cell_type\": \"markdown\"}\n# ## Probability Distributions\n# Let's quickly recall what a probability distribution is: Let $Z$ be some random variable. Then associated with $Z$ is a probability distribution function that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter.\n#\n# We can divide random variables into three classifications:\n#\n# * $Z$ is discrete: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...\n#\n# * $Z$ is continuous: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.\n#\n# * $Z$ is mixed: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories.\n#\n#\n#\n\n# + {\"colab_type\": \"text\", \"id\": \"xG03a_sgDRlc\", \"cell_type\": \"markdown\"}\n# ### Discrete Case\n#\n# If $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:\n# \n# $$P(Z = k) =\\frac{ \\lambda^k e^{-\\lambda} }{k!}, \\; \\; k=0,1,2, \\dots $$\n#\n#\n# $\\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\\lambda$ can be any positive number. By increasing $\\lambda$, we add more probability to larger values, and conversely by decreasing $\\lambda$ we add more probability to smaller values. One can describe $\\lambda$ as the *intensity* of the Poisson distribution. \n#\n# Unlike $\\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members. \n#\n#\n# If a random variable $Z$ has a Poisson mass distribution, we denote this by writing\n# \n# $$Z \\sim \\text{Poi}(\\lambda) $$\n# \n# One useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:\n#\n# $$E\\large[ \\;Z\\; | \\; \\lambda \\;\\large] = \\lambda $$\n#\n#\n# We will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\\lambda$ values. The first thing to notice is that by increasing $\\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 511}, \"colab_type\": \"code\", \"id\": \"7x8Y_YtNqoPY\", \"outputId\": \"34957d57-c33c-4327-d037-486406bad447\"}\n# Build graph.\nx = tf.range (start=0., limit=16.)\nlambdas = tf.constant([1.5, 4.25])\n\npoi_pmf = tfd.Poisson(\n rate=lambdas[:, tf.newaxis]).prob(x)\n\n# Execute graph\n[\n x_,\n lambdas_,\n poi_pmf_,\n] = evaluate([\n x,\n lambdas,\n poi_pmf,\n])\n\nplt.figure(figsize=(12.5, 8))\n\n# Display results in two different histograms, for easier comparison\ncolours = [TFColor[0], TFColor[3]]\nfor i in [0,1]:\n ax = plt.subplot(2,1,i+1)\n ax.set_autoscaley_on(False)\n plt.title(\"Probability mass function of a Poisson random variable\");\n\n plt.bar(x_,\n poi_pmf_[i],\n color=colours[i],\n label=r\"$\\lambda = %.1f$\" % lambdas_[i], alpha=0.60,\n edgecolor=colours[i], lw=\"3\")\n plt.xticks(x_ + 0.4, x_)\n plt.ylim([0, .5])\n plt.legend()\n plt.ylabel(r\"probability of $k$\")\n plt.xlabel(r\"$k$\")\n\n# + {\"colab_type\": \"text\", \"id\": \"ipS19FlBEmqK\", \"cell_type\": \"markdown\"}\n# ### Continuous Case\n#\n# Instead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:\n#\n# $$f_Z(z | \\lambda) = \\lambda e^{-\\lambda z }, \\;\\; z\\ge 0$$\n# \n# Like a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\\lambda$ values. \n#\n# When a random variable $Z$ has an exponential distribution with parameter $\\lambda$, we say *$Z$ is exponential* and write\n#\n# $$Z \\sim \\text{Exp}(\\lambda)$$\n# \n# Given a specific $\\lambda$, the expected value of an exponential random variable is equal to the inverse of $\\lambda$, that is:\n#\n# $$E[\\; Z \\;|\\; \\lambda \\;] = \\frac{1}{\\lambda}$$\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 296}, \"colab_type\": \"code\", \"id\": \"o1aeMH4VE9xs\", \"outputId\": \"34756f32-6058-4cf2-e8a1-1a5da2cb85a6\"}\n# Defining our Data and assumptions (use tf.linspace for continuous)\na = tf.range(start=0., limit=4., delta=0.04)\na = a[..., tf.newaxis]\nlambdas = tf.constant([0.5, 1.])\n\n# Now we use TFP to compute probabilities in a vectorized manner.\nexpo_pdf = tfd.Exponential(rate=lambdas).prob(a)\n\n# Convert from TF to numpy\n[\n a_,\n lambdas_,\n expo_pdf_,\n] = evaluate([\n a,\n lambdas,\n expo_pdf,\n])\n\n# Visualizing our results\nplt.figure(figsize=(12.5, 4))\nfor i in range(lambdas_.size):\n plt.plot(a_.T[0], expo_pdf_.T[[i]][0],\n lw=3, color=TFColor[i], label=r\"$\\lambda = %.1f$\" % lambdas_[i])\n plt.fill_between(a_.T[0], expo_pdf_.T[[i]][0],\n color=TFColor[i], alpha=.33)\nplt.legend()\nplt.ylabel(\"PDF at $z$\")\nplt.xlabel(\"$z$\")\nplt.ylim(0,1.2)\nplt.title(r\"Probability density function of an Exponential random variable; differing $\\lambda$\");\n\n\n# + {\"colab_type\": \"text\", \"id\": \"_1fhqQhAFLkk\", \"cell_type\": \"markdown\"}\n# \n# ## But what is $\\lambda \\;$?\n#\n# **This question is what motivates statistics**. In the real world, $\\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\\lambda$. Many different methods have been created to solve the problem of estimating $\\lambda$, but since $\\lambda$ is never actually observed, no one can say for certain which method is best! \n#\n# Bayesian inference is concerned with *beliefs* about what $\\lambda$ might be. Rather than try to guess $\\lambda$ exactly, we can only talk about what $\\lambda$ is likely to be by assigning a probability distribution to $\\lambda$.\n# \n# This might seem odd at first. After all, $\\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\\lambda$. \n#\n\n# + {\"colab_type\": \"text\", \"id\": \"JrRddMMfHHKJ\", \"cell_type\": \"markdown\"}\n# \n# #### Example: Inferring behaviour from text-message data\n# \n# Let's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:\n#\n# > You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)\n#\n#\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 294}, \"colab_type\": \"code\", \"id\": \"cOBOnwa2IIaB\", \"outputId\": \"43123229-1b53-4ba0-9527-ee633a683b13\"}\n# Defining our Data and assumptions\ncount_data = tf.constant([\n 13, 24, 8, 24, 7, 35, 14, 11, 15, 11, 22, 22, 11, 57, \n 11, 19, 29, 6, 19, 12, 22, 12, 18, 72, 32, 9, 7, 13, \n 19, 23, 27, 20, 6, 17, 13, 10, 14, 6, 16, 15, 7, 2, \n 15, 15, 19, 70, 49, 7, 53, 22, 21, 31, 19, 11, 18, 20, \n 12, 35, 17, 23, 17, 4, 2, 31, 30, 13, 27, 0, 39, 37, \n 5, 14, 13, 22,\n], dtype=tf.float32)\nn_count_data = tf.shape(count_data)\ndays = tf.range(n_count_data[0])\n\n# Convert from TF to numpy.\n\n[\n count_data_, \n n_count_data_, \n days_,\n] = evaluate([\n count_data, \n n_count_data,\n days,\n])\n\n# Visualizing the Results\n \nplt.figure(figsize=(12.5, 4))\nplt.bar(days_, count_data_, color=\"#5DA5DA\")\nplt.xlabel(\"Time (days)\")\nplt.ylabel(\"count of text-msgs received\")\nplt.title(\"Did the user's texting habits change over time?\")\nplt.xlim(0, n_count_data_[0]);\n\n\n# + {\"colab_type\": \"text\", \"id\": \"i-PRmpvsIZKq\", \"cell_type\": \"markdown\"}\n#\n# Before we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period? \n# \n# How can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$, \n# \n# $$ C_i \\sim \\text{Poisson}(\\lambda) $$\n# \n# We are not sure what the value of the $\\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\\lambda$ increases at some point during the observations. (Recall that a higher value of $\\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)\n# \n# How can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\\tau$), the parameter $\\lambda$ suddenly jumps to a higher value. So we really have two $\\lambda$ parameters: one for the period before $\\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:\n# \n# $$\\lambda = \n# \\begin{cases} \\lambda_1 & \\text{if } t \\lt \\tau \\cr\n# \\lambda_2 & \\text{if } t \\ge \\tau\n# \\end{cases}\n# $$\n#\n# If, in reality, no sudden change occurred and indeed $\\lambda_1 = \\lambda_2$, then the $\\lambda$s posterior distributions should look about equal.\n#\n# We are interested in inferring the unknown $\\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\\lambda$. What would be good prior probability distributions for $\\lambda_1$ and $\\lambda_2$? Recall that $\\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\\alpha$.\n# $$\n# \\begin{align}\n# &\\lambda_1 \\sim \\text{Exp}( \\alpha ) \\\\\n# &\\lambda_2 \\sim \\text{Exp}( \\alpha )\n# \\end{align}\n# $$\n# $\\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\\alpha$ does not influence the model too strongly, so we have some flexibility in our choice. A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:\n#\n# $$\\frac{1}{N}\\sum_{i=0}^N \\;C_i \\approx E[\\; \\lambda \\; |\\; \\alpha ] = \\frac{1}{\\alpha}$$ \n# \n# An alternative, and something I encourage the reader to try, would be to have two priors: one for each $\\lambda_i$. Creating two exponential distributions with different $\\alpha$ values reflects our prior belief that the rate changed at some point during the observations.\n# \n# What about $\\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying\n# $$\n# \\begin{align}\n# & \\tau \\sim \\text{DiscreteUniform(1,70) }\\\\\n# & \\Rightarrow P( \\tau = k ) = \\frac{1}{70}\n# \\end{align}\n# $$\n# So after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.\n#\n# We next turn to [TensorFlow Probability](https://tensorflow.org/probability), a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created.\n\n# + {\"colab_type\": \"text\", \"id\": \"mCz2BozPcYNy\", \"cell_type\": \"markdown\"}\n# ## Introducing our first hammer: TensorFlow Probability\n#\n# TensorFlow Probability (TFP) is a Python library for programming Bayesian analysis. It is intended for data scientists, statisticians, machine learning practitioners, and scientists. Since it is built on the TensorFlow (TF) stack, it brings the runtime benefits of TF to Bayesian analysis. These include write-once run-many (ability to run your development model in production) and speedups via state-of-the-art hardware (GPUs and TPUs). \n#\n# Since TFP is relatively new, the TFP community is actively developing documentation, \n# especially docs and examples that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why TFP is so cool.\n#\n# We will model the problem above using TFP. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. \n#\n# B. Cronin [[4]](#scrollTo=nDdph0r1ABCn) has a very motivating description of probabilistic programming:\n#\n# > Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.\n#\n# Because of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is. \n# \n# TFP code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\\tau, \\lambda_1, \\lambda_2$ ) as variables.\n\n# + {\"colab_type\": \"text\", \"id\": \"gYVjgZQ3hOw-\", \"cell_type\": \"markdown\"}\n# ## Specify the joint log-density\n#\n# We'll assume the data is a consequence of the following generative model:\n#\n# $$\\begin{align*}\n# \\lambda_{1}^{(0)} &\\sim \\text{Exponential}(\\text{rate}=\\alpha) \\\\\n# \\lambda_{2}^{(0)} &\\sim \\text{Exponential}(\\text{rate}=\\alpha) \\\\\n# \\tau &\\sim \\text{Uniform}[\\text{low}=0,\\text{high}=1) \\\\\n# \\text{for } i &= 1\\ldots N: \\\\\n# \\lambda_i &= \\begin{cases} \\lambda_{1}^{(0)}, & \\tau > i/N \\\\ \\lambda_{2}^{(0)}, & \\text{otherwise}\\end{cases}\\\\\n# X_i &\\sim \\text{Poisson}(\\text{rate}=\\lambda_i)\n# \\end{align*}$$\n#\n# Happily, this model can be easily implemented using TF and TFP's distributions:\n#\n#\n# This code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\\lambda$ from above. The [gather](https://https://www.tensorflow.org/api_docs/python/tf/gather) function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.\n#\n# Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.\n#\n# TFP performs probabilistic inference by evaluating the model parameters using a joint_log_prob function, which we'll describe more in Chapter 2.\n#\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"rYc_bbho-QzH\"}\ndef joint_log_prob(count_data, lambda_1, lambda_2, tau):\n tfd = tfp.distributions\n \n alpha = np.array(1. / count_data.mean(), np.float32)\n rv_lambda_1 = tfd.Exponential(rate=alpha)\n rv_lambda_2 = tfd.Exponential(rate=alpha)\n \n rv_tau = tfd.Uniform()\n \n lambda_ = tf.gather(\n [lambda_1, lambda_2],\n indices=tf.to_int32(tau * count_data.size <= np.arange(count_data.size)))\n rv_observation = tfd.Poisson(rate=lambda_)\n \n return (\n rv_lambda_1.log_prob(lambda_1)\n + rv_lambda_2.log_prob(lambda_2)\n + rv_tau.log_prob(tau)\n + tf.reduce_sum(rv_observation.log_prob(count_data))\n )\n\n\n# + {\"colab_type\": \"text\", \"id\": \"t7Vvrj68jsr7\", \"cell_type\": \"markdown\"}\n# Notice that the implementation is arguably very close to being a 1:1 translation of the mathematical model. The main difference is merely that once we've specified the probabilistic model, we return the sum of the log_probs.\n\n# + {\"colab_type\": \"text\", \"id\": \"KnyDyY8Tjyiy\", \"cell_type\": \"markdown\"}\n# ## Specify the posterior sampler\n\n# + {\"colab_type\": \"text\", \"id\": \"CGreTr4ljwuF\", \"cell_type\": \"markdown\"}\n# The code below will be explained in Chapter 3, but we show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which we also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\\lambda_1, \\lambda_2$ and $\\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"YBCXrK9gj8Gx\"}\n# Set the chain's start state.\ninitial_chain_state = [\n tf.cast(tf.reduce_mean(count_data), tf.float32) * tf.ones([], dtype=tf.float32, name=\"init_lambda1\"),\n tf.cast(tf.reduce_mean(count_data), tf.float32) * tf.ones([], dtype=tf.float32, name=\"init_lambda2\", tf.float32),\n 0.5 * tf.ones([], dtype=tf.float32, name=\"init_tau\"),\n]\n\n\n# Since HMC operates over unconstrained space, we need to transform the\n# samples so they live in real-space.\nunconstraining_bijectors = [\n tfp.bijectors.Exp(), # Maps a positive real to R.\n tfp.bijectors.Exp(), # Maps a positive real to R.\n tfp.bijectors.Sigmoid(), # Maps [0,1] to R. \n]\n\n\ndef joint_log_prob(count_data, lambda_1, lambda_2, tau):\n tfd = tfp.distributions\n \n alpha = (1. / tf.reduce_mean(count_data))\n rv_lambda_1 = tfd.Exponential(rate=alpha)\n rv_lambda_2 = tfd.Exponential(rate=alpha)\n \n rv_tau = tfd.Uniform()\n \n\n lambda_ = tf.gather(\n [lambda_1, lambda_2],\n indices=tf.to_int32(tau * tf.cast(tf.size(count_data), tf.float32) <= tf.cast(tf.range(tf.size(count_data)), tf.float32)))\n rv_observation = tfd.Poisson(rate=lambda_)\n \n return (\n rv_lambda_1.log_prob(lambda_1)\n + rv_lambda_2.log_prob(lambda_2)\n + rv_tau.log_prob(tau)\n + tf.reduce_sum(rv_observation.log_prob(count_data))\n )\n\n\n# Define a closure over our joint_log_prob.\ndef unnormalized_log_posterior(lambda1, lambda2, tau):\n return joint_log_prob(count_data, lambda1, lambda2, tau)\n\n\n# Initialize the step_size. (It will be automatically adapted.)\nwith tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):\n step_size = tf.get_variable(\n name='step_size',\n initializer=tf.constant(0.05, dtype=tf.float32),\n trainable=False,\n use_resource=True\n )\n\n# Sample from the chain.\n[\n lambda_1_samples,\n lambda_2_samples,\n posterior_tau,\n], kernel_results = tfp.mcmc.sample_chain(\n num_results=100000,\n num_burnin_steps=10000,\n current_state=initial_chain_state,\n kernel=tfp.mcmc.TransformedTransitionKernel(\n inner_kernel=tfp.mcmc.HamiltonianMonteCarlo(\n target_log_prob_fn=unnormalized_log_posterior,\n num_leapfrog_steps=2,\n step_size=step_size,\n step_size_update_fn=tfp.mcmc.make_simple_step_size_update_policy(),\n state_gradients_are_stopped=True),\n bijector=unconstraining_bijectors))\n\ntau_samples = tf.floor(posterior_tau * tf.cast(tf.size(count_data)), tf.float32)\n\n# tau_samples, lambda_1_samples, lambda_2_samples contain\n# N samples from the corresponding posterior distribution\nN = tf.shape(tau_samples)[0]\nexpected_texts_per_day = tf.zeros(n_count_data)\n\n\n# Initialize any created variables.\ninit_g = tf.global_variables_initializer()\ninit_l = tf.local_variables_initializer()\n\n\n# + {\"colab_type\": \"text\", \"id\": \"N1mb2NDUkJLU\", \"cell_type\": \"markdown\"}\n# ## Executing the TF graph to sample from the posterior\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 53}, \"colab_type\": \"code\", \"id\": \"NpNv545ZkLjb\", \"outputId\": \"e0fdbba7-3a66-44a5-910c-d2caa3d84a4f\"}\nevaluate(init_g)\nevaluate(init_l)\n[\n lambda_1_samples_,\n lambda_2_samples_,\n tau_samples_,\n kernel_results_,\n N_,\n expected_texts_per_day_,\n] = evaluate([\n lambda_1_samples,\n lambda_2_samples,\n tau_samples,\n kernel_results,\n N,\n expected_texts_per_day,\n])\n\n \nprint(\"acceptance rate: {}\".format(\n kernel_results_.inner_results.is_accepted.mean()))\nprint(\"final step size: {}\".format(\n kernel_results_.inner_results.extra.step_size_assign[-100:].mean()))\n\n\n\n# + {\"colab_type\": \"text\", \"id\": \"vIxEqx9qkhWr\", \"cell_type\": \"markdown\"}\n# ## Plot the Results\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 896}, \"colab_type\": \"code\", \"id\": \"viLRm6DEkRPM\", \"outputId\": \"bab21304-d1da-4f91-ed27-66ef070202f5\"}\nplt.figure(figsize=(12.5, 15))\n#histogram of the samples:\n\nax = plt.subplot(311)\nax.set_autoscaley_on(False)\n\nplt.hist(lambda_1_samples_, histtype='stepfilled', bins=30, alpha=0.85,\n label=r\"posterior of $\\lambda_1$\", color=TFColor[0], density=True)\nplt.legend(loc=\"upper left\")\nplt.title(r\"\"\"Posterior distributions of the variables $\\lambda_1,\\;\\lambda_2,\\;\\tau$\"\"\")\nplt.xlim([15, 30])\nplt.xlabel(r\"$\\lambda_1$ value\")\n\nax = plt.subplot(312)\nax.set_autoscaley_on(False)\nplt.hist(lambda_2_samples_, histtype='stepfilled', bins=30, alpha=0.85,\n label=r\"posterior of $\\lambda_2$\", color=TFColor[6], density=True)\nplt.legend(loc=\"upper left\")\nplt.xlim([15, 30])\nplt.xlabel(r\"$\\lambda_2$ value\")\n\nplt.subplot(313)\nw = 1.0 / tau_samples_.shape[0] * np.ones_like(tau_samples_)\nplt.hist(tau_samples_, bins=n_count_data_[0], alpha=1,\n label=r\"posterior of $\\tau$\",\n color=TFColor[2], weights=w, rwidth=2.)\nplt.xticks(np.arange(n_count_data_[0]))\n\nplt.legend(loc=\"upper left\")\nplt.ylim([0, .75])\nplt.xlim([35, len(count_data_)-20])\nplt.xlabel(r\"$\\tau$ (in days)\")\nplt.ylabel(r\"probability\");\n\n# + {\"colab_type\": \"text\", \"id\": \"FfiTXgF80sDA\", \"cell_type\": \"markdown\"}\n# ## Interpretation\n#\n# Recall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\\lambda$s and $\\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\\lambda_1$ is around 18 and $\\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.\n#\n# What other observations can you make? If you look at the original data again, do these results seem reasonable? \n#\n# Notice also that the posterior distributions for the $\\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.\n# \n# Our analysis also returned a distribution for $\\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points. \n#\n# ### Why would I want samples from the posterior, anyways?\n#\n# We will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.\n#\n# We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \\; 0 \\le t \\le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\\lambda$. Therefore, the question is equivalent to *what is the expected value of $\\lambda$ at time $t$*?\n# \n# In the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\\lambda_i$ for that day $t$, using $\\lambda_i = \\lambda_{1,i}$ if $t \\lt \\tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\\lambda_i = \\lambda_{2,i}$. \n#\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 566}, \"colab_type\": \"code\", \"id\": \"DgNkjkmO1h4I\", \"outputId\": \"195a4269-7f76-4bc3-ec1b-a2f9c6a09ceb\"}\nplt.figure(figsize=(12.5, 9))\n\nfor day in range(0, n_count_data_[0]):\n # ix is a bool index of all tau samples corresponding to\n # the switchpoint occurring prior to value of 'day'\n ix = day < tau_samples_\n # Each posterior sample corresponds to a value for tau.\n # for each day, that value of tau indicates whether we're \"before\"\n # (in the lambda1 \"regime\") or\n # \"after\" (in the lambda2 \"regime\") the switchpoint.\n # by taking the posterior sample of lambda1/2 accordingly, we can average\n # over all samples to get an expected value for lambda on that day.\n # As explained, the \"message count\" random variable is Poisson distributed,\n # and therefore lambda (the poisson parameter) is the expected value of\n # \"message count\".\n expected_texts_per_day_[day] = (lambda_1_samples_[ix].sum()\n + lambda_2_samples_[~ix].sum()) / N_\n\n\nplt.plot(range(n_count_data_[0]), expected_texts_per_day_, lw=4, color=\"#E24A33\",\n label=\"expected number of text-messages received\")\nplt.xlim(0, n_count_data_[0])\nplt.xlabel(\"Day\")\nplt.ylabel(\"Expected # text-messages\")\nplt.title(\"Expected number of text-messages received\")\nplt.ylim(0, 60)\nplt.bar(np.arange(len(count_data_)), count_data_, color=\"#5DA5DA\", alpha=0.65,\n label=\"observed texts per day\")\n\nplt.legend(loc=\"upper left\");\n\n# + {\"colab_type\": \"text\", \"id\": \"cgCrDy8M3IZT\", \"cell_type\": \"markdown\"}\n# Our analysis shows strong support for believing the user's behavior did change ($\\lambda_1$ would have been close in value to $\\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)\n#\n#\n# ## Exercises\n# \n# 1. Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\\lambda_1$ and $\\lambda_2$?\n#\n#\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"ddpQzca9ACJF\"}\n#type your code here.\n\n# + {\"colab_type\": \"text\", \"id\": \"p4krLq5J_356\", \"cell_type\": \"markdown\"}\n# 2. What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"qWoCGbmEAEvb\"}\n#type your code here.\n\n# + {\"colab_type\": \"text\", \"id\": \"vGHVkSlp_9zf\", \"cell_type\": \"markdown\"}\n# 3. What is the mean of $\\lambda_1$ **given** that we know $\\tau$ is less than 45? That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\\lambda_1$ now? (You do not need to redo the TFP part. Just consider all instances where `tau_samples < 45`.)\n\n# + {\"colab\": {}, \"colab_type\": \"code\", \"id\": \"worLRhcVAFeK\"}\n#type your code here.\n\n# + {\"colab_type\": \"text\", \"id\": \"nDdph0r1ABCn\", \"cell_type\": \"markdown\"}\n# ## References\n#\n# [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg)\n# \n# [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).\n#\n# [3] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.\n#\n# [4] Cronin, Beau. \"Why Probabilistic Programming Matters.\" 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. .\n\n# + {\"colab\": {\"base_uri\": \"https://localhost:8080/\", \"height\": 331}, \"colab_type\": \"code\", \"id\": \"FY5Ftmqh3IC6\", \"outputId\": \"d4cac394-c473-4de5-86d9-b58a08c33fd6\"}\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = open(\"../styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()\n\n", "meta": {"hexsha": "901f98e337113a064baf28476b292287c126025e", "size": 66768, "ext": "py", "lang": "Python", "max_stars_repo_path": "Chapter1_Introduction/Ch1_Introduction_TFP.py", "max_stars_repo_name": "pjleimbigler/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_stars_repo_head_hexsha": "0d7bd5d6e447fb64d91d93b1098421c717435229", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter1_Introduction/Ch1_Introduction_TFP.py", "max_issues_repo_name": "pjleimbigler/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_issues_repo_head_hexsha": "0d7bd5d6e447fb64d91d93b1098421c717435229", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter1_Introduction/Ch1_Introduction_TFP.py", "max_forks_repo_name": "pjleimbigler/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers", "max_forks_repo_head_hexsha": "0d7bd5d6e447fb64d91d93b1098421c717435229", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.1097674419, "max_line_length": 904, "alphanum_fraction": 0.7243739516, "include": true, "reason": "import numpy", "num_tokens": 17632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.22541661063147309, "lm_q1q2_score": 0.09267121873607406}} {"text": "from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport numpy as np\nimport os\nimport sys\nimport esutil\nimport time\n\nfrom .fgcmUtilities import _pickle_method\nfrom .fgcmUtilities import objFlagDict\nfrom .fgcmUtilities import retrievalFlagDict\n\nimport types\ntry:\n import copy_reg as copyreg\nexcept ImportError:\n import copyreg\n\nimport multiprocessing\nfrom multiprocessing import Pool\n\nfrom .sharedNumpyMemManager import SharedNumpyMemManager as snmm\n\ncopyreg.pickle(types.MethodType, _pickle_method)\n\n## FIXME: derivatives should not be zero when hitting the boundary (check)\n\nclass FgcmChisq(object):\n \"\"\"\n Class which computes the chi-squared for the fit.\n\n parameters\n ----------\n fgcmConfig: FgcmConfig\n Config object\n fgcmPars: FgcmParameters\n Parameter object\n fgcmStars: FgcmStars\n Stars object\n fgcmLUT: FgcmLUT\n LUT object\n\n Config variables\n ----------------\n nCore: int\n Number of cores to run in multiprocessing\n nStarPerRun: int\n Number of stars per run. More can use more memory.\n noChromaticCorrections: bool\n If set to True, then no chromatic corrections are applied. (bad idea).\n \"\"\"\n\n def __init__(self,fgcmConfig,fgcmPars,fgcmStars,fgcmLUT):\n\n self.fgcmLog = fgcmConfig.fgcmLog\n\n #self.fgcmLog.log('INFO','Initializing FgcmChisq')\n self.fgcmLog.info('Initializing FgcmChisq')\n\n # does this need to be shm'd?\n self.fgcmPars = fgcmPars\n\n # this is shm'd\n self.fgcmLUT = fgcmLUT\n\n # also shm'd\n self.fgcmStars = fgcmStars\n\n # need to configure\n self.nCore = fgcmConfig.nCore\n self.ccdStartIndex = fgcmConfig.ccdStartIndex\n self.nStarPerRun = fgcmConfig.nStarPerRun\n self.noChromaticCorrections = fgcmConfig.noChromaticCorrections\n\n # these are the standard *band* I10s\n self.I10StdBand = fgcmConfig.I10StdBand\n\n self.illegalValue = fgcmConfig.illegalValue\n\n if (fgcmConfig.useSedLUT and self.fgcmLUT.hasSedLUT):\n self.useSedLUT = True\n else:\n self.useSedLUT = False\n\n self.resetFitChisqList()\n\n # this is the default number of parameters\n self.nActualFitPars = self.fgcmPars.nFitPars\n #self.fgcmLog.log('INFO','Default: fit %d parameters.' % (self.nActualFitPars))\n self.fgcmLog.info('Default: fit %d parameters.' % (self.nActualFitPars))\n\n self.clearMatchCache()\n\n\n def resetFitChisqList(self):\n \"\"\"\n Reset the recorded list of chi-squared values.\n \"\"\"\n\n self.fitChisqs = []\n\n def clearMatchCache(self):\n \"\"\"\n Clear the pre-match cache. Note that this isn't working right.\n \"\"\"\n self.matchesCached = False\n self.goodObs = None\n self.goodStarsSub = None\n\n def __call__(self,fitParams,fitterUnits=False,computeDerivatives=False,computeSEDSlopes=False,useMatchCache=False,debug=False,allExposures=False,includeReserve=False,fgcmGray=None):\n \"\"\"\n Compute the chi-squared for a given set of parameters.\n\n parameters\n ----------\n fitParams: numpy array of floats\n Array with the numerical values of the parameters (properly formatted).\n fitterUnits: bool, default=False\n Are the units of fitParams normalized for the minimizer?\n computeDerivatives: bool, default=False\n Compute fit derivatives?\n computeSEDSlopes: bool, default=False\n Compute SED slopes from magnitudes?\n useMatchCache: bool, default=False\n Cache observation matches. Do not use!\n debug: bool, default=False\n Debug mode with no multiprocessing\n allExposures: bool, default=False\n Compute using all exposures, including flagged/non-photometric\n includeReserve: bool, default=False\n Compute using all objects, including those put in reserve.\n fgcmGray: FgcmGray, default=None\n CCD Gray information for computing with \"ccd crunch\"\n \"\"\"\n\n # computeDerivatives: do we want to compute the derivatives?\n # computeSEDSlope: compute SED Slope and recompute mean mags?\n # fitterUnits: units of th fitter or \"true\" units?\n\n self.computeDerivatives = computeDerivatives\n self.computeSEDSlopes = computeSEDSlopes\n self.fitterUnits = fitterUnits\n self.allExposures = allExposures\n self.useMatchCache = useMatchCache\n self.includeReserve = includeReserve\n self.fgcmGray = fgcmGray # may be None\n\n self.fgcmLog.debug('FgcmChisq: computeDerivatives = %d' %\n (int(computeDerivatives)))\n self.fgcmLog.debug('FgcmChisq: computeSEDSlopes = %d' %\n (int(computeSEDSlopes)))\n self.fgcmLog.debug('FgcmChisq: fitterUnits = %d' %\n (int(fitterUnits)))\n self.fgcmLog.debug('FgcmChisq: allExposures = %d' %\n (int(allExposures)))\n self.fgcmLog.debug('FgcmChisq: includeReserve = %d' %\n (int(includeReserve)))\n\n startTime = time.time()\n\n if (self.allExposures and (self.computeDerivatives or\n self.computeSEDSlopes)):\n raise ValueError(\"Cannot set allExposures and computeDerivatives or computeSEDSlopes\")\n self.fgcmPars.reloadParArray(fitParams,fitterUnits=self.fitterUnits)\n self.fgcmPars.parsToExposures()\n\n\n # and reset numbers if necessary\n if (not self.allExposures):\n snmm.getArray(self.fgcmStars.objMagStdMeanHandle)[:] = 99.0\n snmm.getArray(self.fgcmStars.objMagStdMeanNoChromHandle)[:] = 99.0\n snmm.getArray(self.fgcmStars.objMagStdMeanErrHandle)[:] = 99.0\n\n # do we want to include reserve stars?\n if (self.includeReserve):\n # this mask will filter everything but RESERVED\n resMask = 255 & ~objFlagDict['RESERVED']\n goodStars,=np.where((snmm.getArray(self.fgcmStars.objFlagHandle) & resMask) == 0)\n else:\n goodStars,=np.where(snmm.getArray(self.fgcmStars.objFlagHandle) == 0)\n\n self.fgcmLog.info('Found %d good stars for chisq' % (goodStars.size))\n\n if (goodStars.size == 0):\n raise ValueError(\"No good stars to fit!\")\n\n # do global pre-matching before giving to workers, because\n # it is faster this way\n\n obsObjIDIndex = snmm.getArray(self.fgcmStars.obsObjIDIndexHandle)\n obsExpIndex = snmm.getArray(self.fgcmStars.obsExpIndexHandle)\n obsFlag = snmm.getArray(self.fgcmStars.obsFlagHandle)\n\n if (self.useMatchCache and self.matchesCached) :\n # we have already done the matching\n self.fgcmLog.info('Retrieving cached matches')\n goodObs = self.goodObs\n goodStarsSub = self.goodStarsSub\n else:\n # we need to do matching\n preStartTime=time.time()\n self.fgcmLog.info('Pre-matching stars and observations...')\n goodStarsSub,goodObs = esutil.numpy_util.match(goodStars,\n obsObjIDIndex,\n presorted=True)\n\n if (goodStarsSub[0] != 0.0):\n raise ValueError(\"Very strange that the goodStarsSub first element is non-zero.\")\n\n if (not self.allExposures):\n # cut out all bad exposures and bad observations\n gd,=np.where((self.fgcmPars.expFlag[obsExpIndex[goodObs]] == 0) &\n (obsFlag[goodObs] == 0))\n else:\n # just cut out bad observations\n gd,=np.where(obsFlag[goodObs] == 0)\n\n # crop out both goodObs and goodStarsSub\n goodObs=goodObs[gd]\n goodStarsSub=goodStarsSub[gd]\n\n self.fgcmLog.info('Pre-matching done in %.1f sec.' %\n (time.time() - preStartTime))\n\n if (self.useMatchCache) :\n self.fgcmLog.info('Caching matches for next iteration')\n self.matchesCached = True\n self.goodObs = goodObs\n self.goodStarsSub = goodStarsSub\n\n self.nSums = 2 # chisq, nobs\n if (self.computeDerivatives):\n # we have one for each of the derivatives\n # and a duplicate set to track which parameters were \"touched\"\n self.nSums += 2*self.fgcmPars.nFitPars\n\n self.debug = debug\n if (self.debug):\n # debug mode: single core\n self.totalHandleDict = {}\n self.totalHandleDict[0] = snmm.createArray(self.nSums,dtype='f8')\n\n self._worker((goodStars,goodObs))\n\n partialSums = snmm.getArray(self.totalHandleDict[0])[:]\n else:\n # regular multi-core\n\n\n # make a dummy process to discover starting child number\n proc = multiprocessing.Process()\n workerIndex = proc._identity[0]+1\n proc = None\n\n self.totalHandleDict = {}\n for thisCore in xrange(self.nCore):\n self.totalHandleDict[workerIndex + thisCore] = (\n snmm.createArray(self.nSums,dtype='f8'))\n\n # split goodStars into a list of arrays of roughly equal size\n\n prepStartTime = time.time()\n nSections = goodStars.size // self.nStarPerRun + 1\n goodStarsList = np.array_split(goodStars,nSections)\n\n\n # is there a better way of getting all the first elements from the list?\n # note that we need to skip the first which should be zero (checked above)\n # see also fgcmBrightObs.py\n # splitValues is the first of the goodStars in each list\n splitValues = np.zeros(nSections-1,dtype='i4')\n for i in xrange(1,nSections):\n splitValues[i-1] = goodStarsList[i][0]\n\n # get the indices from the goodStarsSub matched list (matched to goodStars)\n splitIndices = np.searchsorted(goodStars[goodStarsSub], splitValues)\n\n # and split along the indices\n goodObsList = np.split(goodObs,splitIndices)\n\n workerList = list(zip(goodStarsList,goodObsList))\n\n # reverse sort so the longest running go first\n workerList.sort(key=lambda elt:elt[1].size, reverse=True)\n\n self.fgcmLog.info('Using %d sections (%.1f seconds)' %\n (nSections,time.time()-prepStartTime))\n\n self.fgcmLog.info('Running chisq on %d cores' % (self.nCore))\n\n # make a pool\n pool = Pool(processes=self.nCore)\n pool.map(self._worker,workerList,chunksize=1)\n pool.close()\n pool.join()\n\n # sum up the partial sums from the different jobs\n partialSums = np.zeros(self.nSums,dtype='f8')\n for thisCore in xrange(self.nCore):\n partialSums[:] += snmm.getArray(\n self.totalHandleDict[workerIndex + thisCore])[:]\n\n\n if (not self.allExposures):\n # we get the number of fit parameters by counting which of the parameters\n # have been touched by the data (number of touches is irrelevant)\n\n if (self.computeDerivatives):\n nonZero, = np.where(partialSums[self.fgcmPars.nFitPars:\n 2*self.fgcmPars.nFitPars] > 0)\n self.nActualFitPars = nonZero.size\n self.fgcmLog.info('Actually fit %d parameters.' % (self.nActualFitPars))\n\n fitDOF = partialSums[-1] - float(self.nActualFitPars)\n\n if (fitDOF <= 0):\n raise ValueError(\"Number of parameters fitted is more than number of constraints! (%d > %d)\" % (self.fgcmPars.nFitPars,partialSums[-1]))\n\n fitChisq = partialSums[-2] / fitDOF\n if (self.computeDerivatives):\n dChisqdP = partialSums[0:self.fgcmPars.nFitPars] / fitDOF\n\n # want to append this...\n self.fitChisqs.append(fitChisq)\n\n self.fgcmLog.info('Chisq/dof = %.2f (%d iterations)' %\n (fitChisq, len(self.fitChisqs)))\n\n else:\n try:\n fitChisq = self.fitChisqs[-1]\n except:\n fitChisq = 0.0\n\n # free shared arrays\n for key in self.totalHandleDict.keys():\n snmm.freeArray(self.totalHandleDict[key])\n\n self.fgcmLog.info('Chisq computation took %.2f seconds.' %\n (time.time() - startTime))\n\n self.fgcmStars.magStdComputed = True\n if (self.allExposures):\n self.fgcmStars.allMagStdComputed = True\n\n if (self.computeDerivatives):\n return fitChisq, dChisqdP\n else:\n return fitChisq\n\n def _worker(self,goodStarsAndObs):\n \"\"\"\n Multiprocessing worker for FgcmChisq. Not to be called on its own.\n\n parameters\n ----------\n goodStarsAndObs: tuple[2]\n (goodStars, goodObs)\n \"\"\"\n\n # NOTE: No logging is allowed in the _worker method\n\n workerStartTime = time.time()\n\n goodStars = goodStarsAndObs[0]\n goodObs = goodStarsAndObs[1]\n\n if self.debug:\n thisCore = 0\n else:\n thisCore = multiprocessing.current_process()._identity[0]\n\n objMagStdMean = snmm.getArray(self.fgcmStars.objMagStdMeanHandle)\n objMagStdMeanNoChrom = snmm.getArray(self.fgcmStars.objMagStdMeanNoChromHandle)\n objMagStdMeanErr = snmm.getArray(self.fgcmStars.objMagStdMeanErrHandle)\n objSEDSlope = snmm.getArray(self.fgcmStars.objSEDSlopeHandle)\n objNGoodObs = snmm.getArray(self.fgcmStars.objNGoodObsHandle)\n\n obsObjIDIndex = snmm.getArray(self.fgcmStars.obsObjIDIndexHandle)\n\n obsExpIndex = snmm.getArray(self.fgcmStars.obsExpIndexHandle)\n obsBandIndex = snmm.getArray(self.fgcmStars.obsBandIndexHandle)\n obsLUTFilterIndex = snmm.getArray(self.fgcmStars.obsLUTFilterIndexHandle)\n obsCCDIndex = snmm.getArray(self.fgcmStars.obsCCDHandle) - self.ccdStartIndex\n obsFlag = snmm.getArray(self.fgcmStars.obsFlagHandle)\n obsSecZenith = snmm.getArray(self.fgcmStars.obsSecZenithHandle)\n obsMagADU = snmm.getArray(self.fgcmStars.obsMagADUHandle)\n # obsMagADUErr = snmm.getArray(self.fgcmStars.obsMagADUErrHandle)\n obsMagADUModelErr = snmm.getArray(self.fgcmStars.obsMagADUModelErrHandle)\n obsMagStd = snmm.getArray(self.fgcmStars.obsMagStdHandle)\n\n # and fgcmGray stuff (if desired)\n if (self.fgcmGray is not None):\n ccdGray = snmm.getArray(self.fgcmGray.ccdGrayHandle)\n # this is ccdGray[expIndex, ccdIndex]\n # and we only apply when > self.illegalValue\n # same sign as FGCM_DUST (QESys)\n\n # and the arrays for locking access\n objMagStdMeanLock = snmm.getArrayBase(self.fgcmStars.objMagStdMeanHandle).get_lock()\n obsMagStdLock = snmm.getArrayBase(self.fgcmStars.obsMagStdHandle).get_lock()\n\n\n # cut these down now, faster later\n obsObjIDIndexGO = obsObjIDIndex[goodObs]\n obsBandIndexGO = obsBandIndex[goodObs]\n obsLUTFilterIndexGO = obsLUTFilterIndex[goodObs]\n obsExpIndexGO = obsExpIndex[goodObs]\n obsSecZenithGO = obsSecZenith[goodObs]\n obsCCDIndexGO = obsCCDIndex[goodObs]\n\n # which observations are used in the fit?\n _,obsFitUseGO = esutil.numpy_util.match(self.fgcmPars.fitBandIndex,\n obsBandIndexGO)\n\n # now refer to obsBandIndex[goodObs]\n # add GO to index names that are cut to goodObs\n # add GOF to index names that are cut to goodObs[obsFitUseGO]\n\n lutIndicesGO = self.fgcmLUT.getIndices(obsLUTFilterIndexGO,\n self.fgcmPars.expPWV[obsExpIndexGO],\n self.fgcmPars.expO3[obsExpIndexGO],\n #np.log(self.fgcmPars.expTau[obsExpIndexGO]),\n self.fgcmPars.expLnTau[obsExpIndexGO],\n self.fgcmPars.expAlpha[obsExpIndexGO],\n obsSecZenithGO,\n obsCCDIndexGO,\n self.fgcmPars.expPmb[obsExpIndexGO])\n I0GO = self.fgcmLUT.computeI0(self.fgcmPars.expPWV[obsExpIndexGO],\n self.fgcmPars.expO3[obsExpIndexGO],\n #np.log(self.fgcmPars.expTau[obsExpIndexGO]),\n self.fgcmPars.expLnTau[obsExpIndexGO],\n self.fgcmPars.expAlpha[obsExpIndexGO],\n obsSecZenithGO,\n self.fgcmPars.expPmb[obsExpIndexGO],\n lutIndicesGO)\n I10GO = self.fgcmLUT.computeI1(self.fgcmPars.expPWV[obsExpIndexGO],\n self.fgcmPars.expO3[obsExpIndexGO],\n #np.log(self.fgcmPars.expTau[obsExpIndexGO]),\n self.fgcmPars.expLnTau[obsExpIndexGO],\n self.fgcmPars.expAlpha[obsExpIndexGO],\n obsSecZenithGO,\n self.fgcmPars.expPmb[obsExpIndexGO],\n lutIndicesGO) / I0GO\n\n\n qeSysGO = self.fgcmPars.expQESys[obsExpIndexGO]\n\n obsMagGO = obsMagADU[goodObs] + 2.5*np.log10(I0GO) + qeSysGO\n\n if (self.fgcmGray is not None):\n # We want to apply the \"CCD Gray Crunch\"\n # make sure we aren't adding something crazy, but this shouldn't happen\n # because we're filtering good observations (I hope!)\n ok,=np.where(ccdGray[obsExpIndexGO, obsCCDIndexGO] > self.illegalValue)\n obsMagGO[ok] += ccdGray[obsExpIndexGO[ok], obsCCDIndexGO[ok]]\n\n # Compute the sub-selected error-squared, using model error when available\n obsMagErr2GO = obsMagADUModelErr[goodObs]**2.\n\n if (self.computeSEDSlopes):\n # first, compute mean mags (code same as below. FIXME: consolidate, but how?)\n\n # make temp vars. With memory overhead\n\n wtSum = np.zeros_like(objMagStdMean,dtype='f8')\n objMagStdMeanTemp = np.zeros_like(objMagStdMean)\n\n np.add.at(wtSum,\n (obsObjIDIndexGO,obsBandIndexGO),\n 1./obsMagErr2GO)\n np.add.at(objMagStdMeanTemp,\n (obsObjIDIndexGO,obsBandIndexGO),\n obsMagGO/obsMagErr2GO)\n\n # these are good object/bands that were observed\n gd=np.where(wtSum > 0.0)\n\n # and acquire lock to save the values\n objMagStdMeanLock.acquire()\n\n objMagStdMean[gd] = objMagStdMeanTemp[gd] / wtSum[gd]\n objMagStdMeanErr[gd] = np.sqrt(1./wtSum[gd])\n\n # and release the lock.\n objMagStdMeanLock.release()\n\n if (self.useSedLUT):\n self.fgcmStars.computeObjectSEDSlopesLUT(goodStars,self.fgcmLUT)\n else:\n self.fgcmStars.computeObjectSEDSlopes(goodStars)\n\n # compute linearized chromatic correction\n deltaStdGO = 2.5 * np.log10((1.0 +\n objSEDSlope[obsObjIDIndexGO,\n obsBandIndexGO] * I10GO) /\n (1.0 + objSEDSlope[obsObjIDIndexGO,\n obsBandIndexGO] *\n self.I10StdBand[obsBandIndexGO]))\n\n if self.noChromaticCorrections:\n # NOT RECOMMENDED\n deltaStdGO *= 0.0\n\n # we can only do this for calibration stars.\n # must reference the full array to save\n\n # acquire lock when we write to and retrieve from full array\n obsMagStdLock.acquire()\n\n obsMagStd[goodObs] = obsMagGO + deltaStdGO\n # this is cut here\n obsMagStdGO = obsMagStd[goodObs]\n\n # we now have a local cut copy, so release\n obsMagStdLock.release()\n\n # kick out if we're just computing magstd for all exposures\n if (self.allExposures) :\n # kick out\n return None\n\n # compute mean mags\n\n # we make temporary variables. These are less than ideal because they\n # take up the full memory footprint. MAYBE look at making a smaller\n # array just for the stars under consideration, but this would make the\n # indexing in the np.add.at() more difficult\n\n wtSum = np.zeros_like(objMagStdMean,dtype='f8')\n objMagStdMeanTemp = np.zeros_like(objMagStdMean)\n objMagStdMeanNoChromTemp = np.zeros_like(objMagStdMeanNoChrom)\n\n np.add.at(wtSum,\n (obsObjIDIndexGO,obsBandIndexGO),\n 1./obsMagErr2GO)\n\n np.add.at(objMagStdMeanTemp,\n (obsObjIDIndexGO,obsBandIndexGO),\n obsMagStdGO/obsMagErr2GO)\n\n # And the same thing with the non-chromatic corrected values\n np.add.at(objMagStdMeanNoChromTemp,\n (obsObjIDIndexGO,obsBandIndexGO),\n obsMagGO/obsMagErr2GO)\n\n # which objects/bands have observations?\n gd=np.where(wtSum > 0.0)\n\n # and acquire lock to save the values\n objMagStdMeanLock.acquire()\n\n objMagStdMean[gd] = objMagStdMeanTemp[gd] / wtSum[gd]\n objMagStdMeanNoChrom[gd] = objMagStdMeanNoChromTemp[gd] / wtSum[gd]\n objMagStdMeanErr[gd] = np.sqrt(1./wtSum[gd])\n\n # also make local copies for Good Observations\n objMagStdMeanGO = objMagStdMean[obsObjIDIndexGO,obsBandIndexGO]\n objMagStdMeanErr2GO = objMagStdMeanErr[obsObjIDIndexGO,obsBandIndexGO]**2.\n\n # and release the lock.\n objMagStdMeanLock.release()\n\n # compute delta-mags\n\n deltaMagGO = (obsMagStdGO - objMagStdMeanGO)\n\n # Note that this is the model error when we have it\n obsWeightGO = 1. / obsMagErr2GO\n\n deltaMagWeightedGOF = deltaMagGO[obsFitUseGO] * obsWeightGO[obsFitUseGO]\n\n partialChisq = np.sum(deltaMagGO[obsFitUseGO]**2. * obsWeightGO[obsFitUseGO])\n\n partialArray = np.zeros(self.nSums,dtype='f8')\n partialArray[-2] = partialChisq\n partialArray[-1] = obsFitUseGO.size\n\n if (self.computeDerivatives):\n unitDict=self.fgcmPars.getUnitDict(fitterUnits=self.fitterUnits)\n\n # this is going to be ugly. wow, how many indices and sub-indices?\n # or does it simplify since we need all the obs on a night?\n # we shall see! And speed up!\n\n (dLdPWVGO,dLdO3GO,dLdTauGO,dLdAlphaGO) = (\n self.fgcmLUT.computeLogDerivatives(lutIndicesGO,\n I0GO))\n\n if (self.fgcmLUT.hasI1Derivatives):\n (dLdPWVI1GO,dLdO3I1GO,dLdTauI1GO,dLdAlphaI1GO) = (\n self.fgcmLUT.computeLogDerivativesI1(lutIndicesGO,\n I0GO,\n I10GO,\n objSEDSlope[obsObjIDIndexGO,\n obsBandIndexGO]))\n dLdPWVGO += dLdPWVI1GO\n dLdO3GO += dLdO3I1GO\n dLdTauGO += dLdTauI1GO\n dLdAlphaGO += dLdAlphaI1GO\n\n\n # we have objMagStdMeanErr[objIndex,:] = \\Sum_{i\"} 1/\\sigma^2_{i\"j}\n # note that this is summed over all observations of an object in a band\n # so that this is already done\n\n # we need magdLdp = \\Sum_{i'} (1/\\sigma^2_{i'j}) dL(i',j|p)\n # note that this is summed over all observations in a filter that\n # touch a given parameter\n\n # set up arrays\n magdLdPWVIntercept = np.zeros((self.fgcmPars.nCampaignNights,\n self.fgcmPars.nFitBands))\n magdLdPWVPerSlope = np.zeros_like(magdLdPWVIntercept)\n magdLdPWVOffset = np.zeros_like(magdLdPWVIntercept)\n magdLdTauIntercept = np.zeros_like(magdLdPWVIntercept)\n magdLdTauPerSlope = np.zeros_like(magdLdPWVIntercept)\n magdLdTauOffset = np.zeros_like(magdLdPWVIntercept)\n magdLdAlpha = np.zeros_like(magdLdPWVIntercept)\n magdLdO3 = np.zeros_like(magdLdPWVIntercept)\n\n magdLdPWVScale = np.zeros(self.fgcmPars.nFitBands,dtype='f4')\n magdLdTauScale = np.zeros_like(magdLdPWVScale)\n\n magdLdPWVRetrievedScale = np.zeros(self.fgcmPars.nFitBands,dtype='f4')\n magdLdPWVRetrievedOffset = np.zeros_like(magdLdPWVRetrievedScale)\n magdLdPWVRetrievedNightlyOffset = np.zeros_like(magdLdPWVIntercept)\n\n magdLdWashIntercept = np.zeros((self.fgcmPars.nWashIntervals,\n self.fgcmPars.nFitBands))\n magdLdWashSlope = np.zeros_like(magdLdWashIntercept)\n\n # note below that objMagStdMeanErr2GO is the the square of the error,\n # and already cut to [obsObjIDIndexGO,obsBandIndexGO]\n\n ##########\n ## O3\n ##########\n\n expNightIndexGOF = self.fgcmPars.expNightIndex[obsExpIndexGO[obsFitUseGO]]\n uNightIndex = np.unique(expNightIndexGOF)\n\n np.add.at(magdLdO3,\n (expNightIndexGOF,obsBandIndexGO[obsFitUseGO]),\n dLdO3GO[obsFitUseGO] / obsMagErr2GO[obsFitUseGO])\n np.multiply.at(magdLdO3,\n (expNightIndexGOF,obsBandIndexGO[obsFitUseGO]),\n objMagStdMeanErr2GO[obsFitUseGO])\n np.add.at(partialArray[self.fgcmPars.parO3Loc:\n (self.fgcmPars.parO3Loc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF,\n deltaMagWeightedGOF * (\n (dLdO3GO[obsFitUseGO] -\n magdLdO3[expNightIndexGOF,obsBandIndexGO[obsFitUseGO]])))\n\n partialArray[self.fgcmPars.parO3Loc +\n uNightIndex] *= (2.0 / unitDict['o3Unit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parO3Loc +\n uNightIndex] += 1\n\n ###########\n ## Alpha\n ###########\n\n np.add.at(magdLdAlpha,\n (expNightIndexGOF,obsBandIndexGO[obsFitUseGO]),\n dLdAlphaGO[obsFitUseGO] / obsMagErr2GO[obsFitUseGO])\n np.multiply.at(magdLdAlpha,\n (expNightIndexGOF,obsBandIndexGO[obsFitUseGO]),\n objMagStdMeanErr2GO[obsFitUseGO])\n np.add.at(partialArray[self.fgcmPars.parAlphaLoc:\n (self.fgcmPars.parAlphaLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF,\n deltaMagWeightedGOF * (\n (dLdAlphaGO[obsFitUseGO] -\n magdLdAlpha[expNightIndexGOF,obsBandIndexGO[obsFitUseGO]])))\n\n partialArray[self.fgcmPars.parAlphaLoc +\n uNightIndex] *= (2.0 / unitDict['alphaUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parAlphaLoc +\n uNightIndex] += 1\n\n\n ###########\n ## PWV External\n ###########\n\n if (self.fgcmPars.hasExternalPWV and not self.fgcmPars.useRetrievedPWV):\n hasExtGOF,=np.where(self.fgcmPars.externalPWVFlag[obsExpIndexGO[obsFitUseGO]])\n uNightIndexHasExt = np.unique(expNightIndexGOF[hasExtGOF])\n\n # PWV Nightly Offset\n np.add.at(magdLdPWVOffset,\n (expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]),\n dLdPWVGO[obsFitUseGO[hasExtGOF]] /\n obsMagErr2GO[obsFitUseGO[hasExtGOF]])\n np.multiply.at(magdLdPWVOffset,\n (expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[hasExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parExternalPWVOffsetLoc:\n (self.fgcmPars.parExternalPWVOffsetLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[hasExtGOF],\n deltaMagWeightedGOF[hasExtGOF] * (\n (dLdPWVGO[obsFitUseGO[hasExtGOF]] -\n magdLdPWVOffset[expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]])))\n partialArray[self.fgcmPars.parExternalPWVOffsetLoc +\n uNightIndexHasExt] *= (2.0 / unitDict['pwvUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parExternalPWVOffsetLoc +\n uNightIndexHasExt] += 1\n\n\n # PWV Global Scale\n np.add.at(magdLdPWVScale,\n obsBandIndexGO[obsFitUseGO[hasExtGOF]],\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[hasExtGOF]]] *\n dLdPWVGO[obsFitUseGO[hasExtGOF]] /\n obsMagErr2GO[obsFitUseGO[hasExtGOF]])\n np.multiply.at(magdLdPWVScale,\n obsBandIndexGO[obsFitUseGO[hasExtGOF]],\n objMagStdMeanErr2GO[obsFitUseGO[hasExtGOF]])\n partialArray[self.fgcmPars.parExternalPWVScaleLoc] = 2.0 * (\n np.sum(deltaMagWeightedGOF[hasExtGOF] * (\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[hasExtGOF]]] *\n dLdPWVGO[obsFitUseGO[hasExtGOF]] -\n magdLdPWVScale[obsBandIndexGO[obsFitUseGO[hasExtGOF]]])) /\n unitDict['pwvGlobalUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parExternalPWVScaleLoc] += 1\n\n ################\n ## PWV Retrieved\n ################\n\n if (self.fgcmPars.useRetrievedPWV):\n hasRetrievedPWVGOF, = np.where((self.fgcmPars.compRetrievedPWVFlag[obsExpIndexGO[obsFitUseGO]] &\n retrievalFlagDict['EXPOSURE_RETRIEVED']) > 0)\n\n if hasRetrievedPWVGOF.size > 0:\n # note this might be zero-size on first run\n\n # PWV Retrieved Global Scale\n np.add.at(magdLdPWVRetrievedScale,\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]],\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]] *\n dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] /\n obsMagErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n np.multiply.at(magdLdPWVRetrievedScale,\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]],\n objMagStdMeanErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n partialArray[self.fgcmPars.parRetrievedPWVScaleLoc] = 2.0 * (\n np.sum(deltaMagWeightedGOF[hasRetrievedPWVGOF] * (\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]] *\n dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] -\n magdLdPWVRetrievedScale[obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]])) /\n unitDict['pwvGlobalUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parRetrievedPWVScaleLoc] += 1\n\n if self.fgcmPars.useNightlyRetrievedPWV:\n # PWV Retrieved Nightly Offset\n\n uNightIndexHasRetrievedPWV = np.unique(expNightIndexGOF[hasRetrievedPWVGOF])\n\n np.add.at(magdLdPWVRetrievedNightlyOffset,\n (expNightIndexGOF[hasRetrievedPWVGOF],\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]),\n dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] /\n obsMagErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n np.multiply.at(magdLdPWVRetrievedNightlyOffset,\n (expNightIndexGOF[hasRetrievedPWVGOF],\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n np.add.at(partialArray[self.fgcmPars.parRetrievedPWVNightlyOffsetLoc:\n (self.fgcmPars.parRetrievedPWVNightlyOffsetLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[hasRetrievedPWVGOF],\n deltaMagWeightedGOF[hasRetrievedPWVGOF] * (\n (dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] -\n magdLdPWVRetrievedNightlyOffset[expNightIndexGOF[hasRetrievedPWVGOF],\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]])))\n partialArray[self.fgcmPars.parRetrievedPWVNightlyOffsetLoc +\n uNightIndexHasRetrievedPWV] *= (2.0 / unitDict['pwvUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parRetrievedPWVNightlyOffsetLoc +\n uNightIndexHasRetrievedPWV] += 1\n\n else:\n # PWV Retrieved Global Offset\n np.add.at(magdLdPWVRetrievedOffset,\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]],\n dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] /\n obsMagErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n np.multiply.at(magdLdPWVRetrievedOffset,\n obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]],\n objMagStdMeanErr2GO[obsFitUseGO[hasRetrievedPWVGOF]])\n partialArray[self.fgcmPars.parRetrievedPWVOffsetLoc] = 2.0 * (\n np.sum(deltaMagWeightedGOF[hasRetrievedPWVGOF] * (\n dLdPWVGO[obsFitUseGO[hasRetrievedPWVGOF]] -\n magdLdPWVRetrievedOffset[obsBandIndexGO[obsFitUseGO[hasRetrievedPWVGOF]]])) /\n unitDict['pwvGlobalUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parRetrievedPWVOffsetLoc] += 1\n\n else:\n ###########\n ## PWV No External\n ###########\n\n noExtGOF, = np.where(~self.fgcmPars.externalPWVFlag[obsExpIndexGO[obsFitUseGO]])\n uNightIndexNoExt = np.unique(expNightIndexGOF[noExtGOF])\n\n # PWV Nightly Intercept\n\n np.add.at(magdLdPWVIntercept,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n dLdPWVGO[obsFitUseGO[noExtGOF]] /\n obsMagErr2GO[obsFitUseGO[noExtGOF]])\n np.multiply.at(magdLdPWVIntercept,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[noExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parPWVInterceptLoc:\n (self.fgcmPars.parPWVInterceptLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[noExtGOF],\n deltaMagWeightedGOF[noExtGOF] * (\n (dLdPWVGO[obsFitUseGO[noExtGOF]] -\n magdLdPWVOffset[expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]])))\n\n partialArray[self.fgcmPars.parPWVInterceptLoc +\n uNightIndexNoExt] *= (2.0 / unitDict['pwvUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parPWVInterceptLoc +\n uNightIndexNoExt] += 1\n\n # PWV Nightly Percent Slope\n np.add.at(magdLdPWVPerSlope,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n self.fgcmPars.expDeltaUT[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n dLdPWVGO[obsFitUseGO[noExtGOF]] /\n obsMagErr2GO[obsFitUseGO[noExtGOF]])\n np.multiply.at(magdLdPWVPerSlope,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[noExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parPWVPerSlopeLoc:\n (self.fgcmPars.parPWVPerSlopeLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[noExtGOF],\n deltaMagWeightedGOF[noExtGOF] * (\n (self.fgcmPars.expDeltaUT[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n self.fgcmPars.expPWV[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n dLdPWVGO[obsFitUseGO[noExtGOF]] -\n magdLdPWVPerSlope[expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]])))\n\n partialArray[self.fgcmPars.parPWVPerSlopeLoc +\n uNightIndex] *= (2.0 / unitDict['pwvPerSlopeUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parPWVPerSlopeLoc] += 1\n\n #############\n ## Tau External\n #############\n\n if (self.fgcmPars.hasExternalTau):\n hasExtGOF,=np.where(self.fgcmPars.externalTauFlag[obsExpIndexGO[obsFitUseGO]])\n uNightIndexHasExt = np.unique(expNightIndexGOF[hasExtGOF])\n\n # Tau Nightly Offset\n np.add.at(magdLdTauOffset,\n (expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]),\n dLdTauGO[obsFitUseGO[hasExtGOF]] /\n obsMagErr2GO[obsFitUseGO[hasExtGOF]])\n np.multiply.at(magdLdTauOffset,\n (expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[hasExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parExternalTauOffsetLoc:\n (self.fgcmPars.parExternalTauOffsetLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[hasExtGOF],\n deltaMagWeightedGOF[hasExtGOF] * (\n (dLdTauGO[obsFitUseGO[hasExtGOF]] -\n magdLdTauOffset[expNightIndexGOF[hasExtGOF],\n obsBandIndexGO[obsFitUseGO[hasExtGOF]]])))\n\n partialArray[self.fgcmPars.parExternalTauOffsetLoc +\n uNightIndexHasExt] *= (2.0 / unitDict['tauUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parExternalTauOffsetLoc +\n uNightIndexHasExt] += 1\n\n # Tau Global Scale\n ## MAYBE: is this correct with the logs?\n np.add.at(magdLdTauScale,\n obsBandIndexGO[obsFitUseGO[hasExtGOF]],\n self.fgcmPars.expTau[obsExpIndexGO[obsFitUseGO[hasExtGOF]]] *\n dLdTauGO[obsFitUseGO[hasExtGOF]] /\n obsMagErr2GO[obsFitUseGO[hasExtGOF]])\n np.multiply.at(magdLdTauScale,\n obsBandIndexGO[obsFitUseGO[hasExtGOF]],\n objMagStdMeanErr2GO[obsFitUseGO[hasExtGOF]])\n partialArray[self.fgcmPars.parExternalTauScaleLoc] = 2.0 * (\n np.sum(deltaMagWeightedGOF[hasExtGOF] * (\n self.fgcmPars.expTau[obsExpIndexGO[obsFitUseGO[hasExtGOF]]] *\n dLdTauGO[obsFitUseGO[hasExtGOF]] -\n magdLdPWVScale[obsBandIndexGO[obsFitUseGO[hasExtGOF]]])) /\n unitDict['tauUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parExternalTauScaleLoc] += 1\n\n ###########\n ## Tau No External\n ###########\n\n noExtGOF, = np.where(~self.fgcmPars.externalTauFlag[obsExpIndexGO[obsFitUseGO]])\n uNightIndexNoExt = np.unique(expNightIndexGOF[noExtGOF])\n\n # lnTau Nightly Intercept\n np.add.at(magdLdTauIntercept,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n dLdTauGO[obsFitUseGO[noExtGOF]] /\n obsMagErr2GO[obsFitUseGO[noExtGOF]])\n np.multiply.at(magdLdTauIntercept,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[noExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parLnTauInterceptLoc:\n (self.fgcmPars.parLnTauInterceptLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[noExtGOF],\n deltaMagWeightedGOF[noExtGOF] * (\n (dLdTauGO[obsFitUseGO[noExtGOF]] -\n magdLdTauOffset[expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]])))\n\n partialArray[self.fgcmPars.parLnTauInterceptLoc +\n uNightIndexNoExt] *= (2.0 / unitDict['lnTauUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parLnTauInterceptLoc +\n uNightIndexNoExt] += 1\n\n # lnTau nightly slope\n np.add.at(magdLdTauPerSlope,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n self.fgcmPars.expDeltaUT[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n #self.fgcmPars.expTau[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n dLdTauGO[obsFitUseGO[noExtGOF]] /\n obsMagErr2GO[obsFitUseGO[noExtGOF]])\n np.multiply.at(magdLdTauPerSlope,\n (expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]),\n objMagStdMeanErr2GO[obsFitUseGO[noExtGOF]])\n np.add.at(partialArray[self.fgcmPars.parLnTauSlopeLoc:\n (self.fgcmPars.parLnTauSlopeLoc+\n self.fgcmPars.nCampaignNights)],\n expNightIndexGOF[noExtGOF],\n deltaMagWeightedGOF[noExtGOF] * (\n (self.fgcmPars.expDeltaUT[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n #self.fgcmPars.expTau[obsExpIndexGO[obsFitUseGO[noExtGOF]]] *\n dLdTauGO[obsFitUseGO[noExtGOF]] -\n magdLdTauPerSlope[expNightIndexGOF[noExtGOF],\n obsBandIndexGO[obsFitUseGO[noExtGOF]]])))\n\n partialArray[self.fgcmPars.parLnTauSlopeLoc +\n uNightIndexNoExt] *= (2.0 / unitDict['lnTauSlopeUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parLnTauSlopeLoc +\n uNightIndexNoExt] += 1\n\n\n #############\n ## Washes (QE Sys)\n #############\n\n expWashIndexGOF = self.fgcmPars.expWashIndex[obsExpIndexGO[obsFitUseGO]]\n uWashIndex = np.unique(expWashIndexGOF)\n\n # Wash Intercept\n np.add.at(magdLdWashIntercept,\n (expWashIndexGOF,obsBandIndexGO[obsFitUseGO]),\n 1./obsMagErr2GO[obsFitUseGO])\n np.multiply.at(magdLdWashIntercept,\n (expWashIndexGOF,obsBandIndexGO[obsFitUseGO]),\n objMagStdMeanErr2GO[obsFitUseGO])\n np.add.at(partialArray[self.fgcmPars.parQESysInterceptLoc:\n (self.fgcmPars.parQESysInterceptLoc +\n self.fgcmPars.nWashIntervals)],\n expWashIndexGOF,\n deltaMagWeightedGOF * (\n (1.0 - magdLdWashIntercept[expWashIndexGOF,\n obsBandIndexGO[obsFitUseGO]])))\n\n partialArray[self.fgcmPars.parQESysInterceptLoc +\n uWashIndex] *= (2.0 / unitDict['qeSysUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parQESysInterceptLoc +\n uWashIndex] += 1\n\n # Wash Slope\n np.add.at(magdLdWashSlope,\n (expWashIndexGOF,obsBandIndexGO[obsFitUseGO]),\n (self.fgcmPars.expMJD[obsExpIndexGO[obsFitUseGO]] -\n self.fgcmPars.washMJDs[expWashIndexGOF]) /\n obsMagErr2GO[obsFitUseGO])\n np.multiply.at(magdLdWashSlope,\n (expWashIndexGOF,obsBandIndexGO[obsFitUseGO]),\n objMagStdMeanErr2GO[obsFitUseGO])\n np.add.at(partialArray[self.fgcmPars.parQESysSlopeLoc:\n (self.fgcmPars.parQESysSlopeLoc +\n self.fgcmPars.nWashIntervals)],\n expWashIndexGOF,\n deltaMagWeightedGOF * (\n (self.fgcmPars.expMJD[obsExpIndexGO[obsFitUseGO]] -\n self.fgcmPars.washMJDs[expWashIndexGOF]) -\n magdLdWashSlope[expWashIndexGOF,\n obsBandIndexGO[obsFitUseGO]]))\n partialArray[self.fgcmPars.parQESysSlopeLoc +\n uWashIndex] *= (2.0 / unitDict['qeSysSlopeUnit'])\n partialArray[self.fgcmPars.nFitPars +\n self.fgcmPars.parQESysSlopeLoc +\n uWashIndex] += 1\n\n\n # note that this store doesn't need locking because we only access\n # a given array from a single process\n\n totalArr = snmm.getArray(self.totalHandleDict[thisCore])\n totalArr[:] = totalArr[:] + partialArray\n\n # and we're done\n return None\n\n def __getstate__(self):\n # Don't try to pickle the logger.\n\n state = self.__dict__.copy()\n del state['fgcmLog']\n return state\n", "meta": {"hexsha": "d1d56ca89d805858d582c5655a1fdd0cbd2f3055", "size": 48875, "ext": "py", "lang": "Python", "max_stars_repo_path": "fgcm/fgcmChisq.py", "max_stars_repo_name": "gcmshadow/fgcm", "max_stars_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fgcm/fgcmChisq.py", "max_issues_repo_name": "gcmshadow/fgcm", "max_issues_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fgcm/fgcmChisq.py", "max_forks_repo_name": "gcmshadow/fgcm", "max_forks_repo_head_hexsha": "f94231d90dc5f1b5711af3b1e259d26a6144cc15", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1956521739, "max_line_length": 185, "alphanum_fraction": 0.5530434783, "include": true, "reason": "import numpy", "num_tokens": 12290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.1824255260288117, "lm_q1q2_score": 0.09192534822793161}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Face Recognition\n# \n# Welcome! In this assignment, you're going to build a face recognition system. Many of the ideas presented here are from [FaceNet](https://arxiv.org/pdf/1503.03832.pdf). In the lecture, you also encountered [DeepFace](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf).\n# \n# Face recognition problems commonly fall into one of two categories: \n# \n# **Face Verification** \"Is this the claimed person?\" For example, at some airports, you can pass through customs by letting a system scan your passport and then verifying that you (the person carrying the passport) are the correct person. A mobile phone that unlocks using your face is also using face verification. This is a 1:1 matching problem.\n# \n# **Face Recognition** \"Who is this person?\" For example, the video lecture showed a [face recognition video](https://www.youtube.com/watch?v=wr4rx0Spihs) of Baidu employees entering the office without needing to otherwise identify themselves. This is a 1:K matching problem.\n# \n# FaceNet learns a neural network that encodes a face image into a vector of 128 numbers. By comparing two such vectors, you can then determine if two pictures are of the same person.\n# \n# By the end of this assignment, you'll be able to: \n# \n# * Differentiate between face recognition and face verification\n# * Implement one-shot learning to solve a face recognition problem\n# * Apply the triplet loss function to learn a network's parameters in the context of face recognition\n# * Explain how to pose face recognition as a binary classification problem\n# * Map face images into 128-dimensional encodings using a pretrained model\n# * Perform face verification and face recognition with these encodings\n# \n# **Channels-last notation**\n# \n# For this assignment, you'll be using a pre-trained model which represents ConvNet activations using a \"channels last\" convention, as used during the lecture and in previous programming assignments.\n# \n# In other words, a batch of images will be of shape $(m, n_H, n_W, n_C)$. \n\n# ## Table of Contents\n# \n# - [1 - Packages](#1)\n# - [2 - Naive Face Verification](#2)\n# - [3 - Encoding Face Images into a 128-Dimensional Vector](#3)\n# - [3.1 - Using a ConvNet to Compute Encodings](#3-1)\n# - [3.2 - The Triplet Loss](#3-2)\n# - [Exercise 1 - triplet_loss](#ex-1)\n# - [4 - Loading the Pre-trained Model](#4)\n# - [5 - Applying the Model](#5)\n# - [5.1 - Face Verification](#5-1)\n# - [Exercise 2 - verify](#ex-2)\n# - [5.2 - Face Recognition](#5-2)\n# - [Exercise 3 - who_is_it](#ex-3)\n# - [6 - References](#6)\n\n# \n# ## 1 - Packages\n# \n# Go ahead and run the cell below to import the packages you'll need.\n\n# In[1]:\n\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import MaxPooling2D, AveragePooling2D\nfrom tensorflow.keras.layers import Concatenate\nfrom tensorflow.keras.layers import Lambda, Flatten, Dense\nfrom tensorflow.keras.initializers import glorot_uniform\nfrom tensorflow.keras.layers import Layer\nfrom tensorflow.keras import backend as K\nK.set_image_data_format('channels_last')\nimport os\nimport numpy as np\nfrom numpy import genfromtxt\nimport pandas as pd\nimport tensorflow as tf\nimport PIL\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().run_line_magic('load_ext', 'autoreload')\nget_ipython().run_line_magic('autoreload', '2')\n\n\n# \n# ## 2 - Naive Face Verification\n# \n# In Face Verification, you're given two images and you have to determine if they are of the same person. The simplest way to do this is to compare the two images pixel-by-pixel. If the distance between the raw images is below a chosen threshold, it may be the same person!\n# \n# \n#
Figure 1
\n# \n# Of course, this algorithm performs poorly, since the pixel values change dramatically due to variations in lighting, orientation of the person's face, minor changes in head position, and so on.\n# \n# You'll see that rather than using the raw image, you can learn an encoding, $f(img)$.\n# \n# By using an encoding for each image, an element-wise comparison produces a more accurate judgement as to whether two pictures are of the same person.\n\n# \n# ## 3 - Encoding Face Images into a 128-Dimensional Vector\n# \n# \n# ### 3.1 - Using a ConvNet to Compute Encodings\n# \n# The FaceNet model takes a lot of data and a long time to train. So following the common practice in applied deep learning, you'll load weights that someone else has already trained. The network architecture follows the Inception model from [Szegedy *et al*..](https://arxiv.org/abs/1409.4842) An Inception network implementation has been provided for you, and you can find it in the file `inception_blocks_v2.py` to get a closer look at how it is implemented. \n# \n# *Hot tip:* Go to \"File->Open...\" at the top of this notebook. This opens the file directory that contains the `.py` file).\n# \n# The key things to be aware of are:\n# \n# - This network uses 160x160 dimensional RGB images as its input. Specifically, a face image (or batch of $m$ face images) as a tensor of shape $(m, n_H, n_W, n_C) = (m, 160, 160, 3)$\n# - The input images are originally of shape 96x96, thus, you need to scale them to 160x160. This is done in the `img_to_encoding()` function.\n# - The output is a matrix of shape $(m, 128)$ that encodes each input face image into a 128-dimensional vector\n# \n# Run the cell below to create the model for face images!\n\n# In[2]:\n\n\nfrom tensorflow.keras.models import model_from_json\n\njson_file = open('keras-facenet-h5/model.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel = model_from_json(loaded_model_json)\nmodel.load_weights('keras-facenet-h5/model.h5')\n\n\n# Now summarize the input and output shapes: \n\n# In[3]:\n\n\nprint(model.inputs)\nprint(model.outputs)\n\n\n# By using a 128-neuron fully connected layer as its last layer, the model ensures that the output is an encoding vector of size 128. You then use the encodings to compare two face images as follows:\n# \n# \n#
Figure 2:
By computing the distance between two encodings and thresholding, you can determine if the two pictures represent the same person
\n# \n# So, an encoding is a good one if:\n# \n# - The encodings of two images of the same person are quite similar to each other.\n# - The encodings of two images of different persons are very different.\n# \n# The triplet loss function formalizes this, and tries to \"push\" the encodings of two images of the same person (Anchor and Positive) closer together, while \"pulling\" the encodings of two images of different persons (Anchor, Negative) further apart.\n# \n#
\n#
Figure 3:
In the next section, you'll call the pictures from left to right: Anchor (A), Positive (P), Negative (N)
\n\n# \n# ### 3.2 - The Triplet Loss\n# \n# **Important Note**: Since you're using a pretrained model, you won't actually need to implement the triplet loss function in this assignment. *However*, the triplet loss is the main ingredient of the face recognition algorithm, and you'll need to know how to use it for training your own FaceNet model, as well as other types of image similarity problems. Therefore, you'll implement it below, for fun and edification. :) \n# \n# For an image $x$, its encoding is denoted as $f(x)$, where $f$ is the function computed by the neural network.\n# \n# \n# \n# Training will use triplets of images $(A, P, N)$:\n# \n# - A is an \"Anchor\" image--a picture of a person.\n# - P is a \"Positive\" image--a picture of the same person as the Anchor image.\n# - N is a \"Negative\" image--a picture of a different person than the Anchor image.\n# \n# These triplets are picked from the training dataset. $(A^{(i)}, P^{(i)}, N^{(i)})$ is used here to denote the $i$-th training example.\n# \n# You'd like to make sure that an image $A^{(i)}$ of an individual is closer to the Positive $P^{(i)}$ than to the Negative image $N^{(i)}$) by at least a margin $\\alpha$:\n# \n# $$\n# || f\\left(A^{(i)}\\right)-f\\left(P^{(i)}\\right)||_{2}^{2}+\\alpha<|| f\\left(A^{(i)}\\right)-f\\left(N^{(i)}\\right)||_{2}^{2}\n# $$\n# \n# \n# You would thus like to minimize the following \"triplet cost\":\n# \n# $$\\mathcal{J} = \\sum^{m}_{i=1} \\large[ \\small \\underbrace{\\mid \\mid f(A^{(i)}) - f(P^{(i)}) \\mid \\mid_2^2}_\\text{(1)} - \\underbrace{\\mid \\mid f(A^{(i)}) - f(N^{(i)}) \\mid \\mid_2^2}_\\text{(2)} + \\alpha \\large ] \\small_+ \\tag{3}$$\n# Here, the notation \"$[z]_+$\" is used to denote $max(z,0)$.\n# \n# **Notes**:\n# \n# - The term (1) is the squared distance between the anchor \"A\" and the positive \"P\" for a given triplet; you want this to be small.\n# - The term (2) is the squared distance between the anchor \"A\" and the negative \"N\" for a given triplet, you want this to be relatively large. It has a minus sign preceding it because minimizing the negative of the term is the same as maximizing that term.\n# - $\\alpha$ is called the margin. It's a hyperparameter that you pick manually. You'll use $\\alpha = 0.2$.\n# \n# Most implementations also rescale the encoding vectors to haven L2 norm equal to one (i.e., $\\mid \\mid f(img)\\mid \\mid_2$=1); you won't have to worry about that in this assignment.\n# \n# \n# ### Exercise 1 - triplet_loss\n# \n# Implement the triplet loss as defined by formula (3). These are the 4 steps:\n# \n# 1. Compute the distance between the encodings of \"anchor\" and \"positive\": $\\mid \\mid f(A^{(i)}) - f(P^{(i)}) \\mid \\mid_2^2$\n# 2. Compute the distance between the encodings of \"anchor\" and \"negative\": $\\mid \\mid f(A^{(i)}) - f(N^{(i)}) \\mid \\mid_2^2$\n# 3. Compute the formula per training example: $ \\mid \\mid f(A^{(i)}) - f(P^{(i)}) \\mid \\mid_2^2 - \\mid \\mid f(A^{(i)}) - f(N^{(i)}) \\mid \\mid_2^2 + \\alpha$\n# 4. Compute the full formula by taking the max with zero and summing over the training examples:$$\\mathcal{J} = \\sum^{m}_{i=1} \\large[ \\small \\mid \\mid f(A^{(i)}) - f(P^{(i)}) \\mid \\mid_2^2 - \\mid \\mid f(A^{(i)}) - f(N^{(i)}) \\mid \\mid_2^2+ \\alpha \\large ] \\small_+ \\tag{3}$$\n# \n# *Hints*:\n# \n# - Useful functions: `tf.reduce_sum()`, `tf.square()`, `tf.subtract()`, `tf.add()`, `tf.maximum()`.\n# \n# - For steps 1 and 2, sum over the entries of $\\mid \\mid f(A^{(i)}) - f(P^{(i)}) \\mid \\mid_2^2$ and $\\mid \\mid f(A^{(i)}) - f(N^{(i)}) \\mid \\mid_2^2$.\n# \n# - For step 4, you will sum over the training examples.\n# \n# *Additional Hints*:\n# \n# - Recall that the square of the L2 norm is the sum of the squared differences: $||x - y||_{2}^{2} = \\sum_{i=1}^{N}(x_{i} - y_{i})^{2}$\n# \n# - Note that the anchor, positive and negative encodings are of shape (*m*,128), where *m* is the number of training examples and 128 is the number of elements used to encode a single example.\n# \n# - For steps 1 and 2, maintain the number of *m* training examples and sum along the 128 values of each encoding. `tf.reduce_sum` has an axis parameter. This chooses along which axis the sums are applied.\n# \n# - Note that one way to choose the last axis in a tensor is to use negative indexing (axis=-1).\n# \n# - In step 4, when summing over training examples, the result will be a single scalar value.\n# \n# - For `tf.reduce_sum` to sum across all axes, keep the default value axis=None.\n\n# In[18]:\n\n\n# UNQ_C1(UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: triplet_loss\n\ndef triplet_loss(y_true, y_pred, alpha = 0.2):\n \"\"\"\n Implementation of the triplet loss as defined by formula (3)\n \n Arguments:\n y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.\n y_pred -- python list containing three objects:\n anchor -- the encodings for the anchor images, of shape (None, 128)\n positive -- the encodings for the positive images, of shape (None, 128)\n negative -- the encodings for the negative images, of shape (None, 128)\n \n Returns:\n loss -- real number, value of the loss\n \"\"\"\n \n anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]\n \n ### START CODE HERE\n #(≈ 4 lines)\n # Step 1: Compute the (encoding) distance between the anchor and the positive\n pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)\n # Step 2: Compute the (encoding) distance between the anchor and the negative\n neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=-1)\n # Step 3: subtract the two previous distances and add alpha.\n basic_loss = pos_dist - neg_dist + alpha\n # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.\n loss = tf.reduce_sum(tf.maximum(basic_loss, 0))\n ### END CODE HERE\n \n return loss\n\n\n# In[19]:\n\n\n# BEGIN UNIT TEST\ntf.random.set_seed(1)\ny_true = (None, None, None) # It is not used\ny_pred = (tf.keras.backend.random_normal([3, 128], mean=6, stddev=0.1, seed = 1),\n tf.keras.backend.random_normal([3, 128], mean=1, stddev=1, seed = 1),\n tf.keras.backend.random_normal([3, 128], mean=3, stddev=4, seed = 1))\nloss = triplet_loss(y_true, y_pred)\n\nassert type(loss) == tf.python.framework.ops.EagerTensor, \"Use tensorflow functions\"\nprint(\"loss = \" + str(loss))\n\ny_pred_perfect = ([1., 1.], [1., 1.], [1., 1.,])\nloss = triplet_loss(y_true, y_pred_perfect, 5)\nassert loss == 5, \"Wrong value. Did you add the alpha to basic_loss?\"\ny_pred_perfect = ([1., 1.],[1., 1.], [0., 0.,])\nloss = triplet_loss(y_true, y_pred_perfect, 3)\nassert loss == 1., \"Wrong value. Check that pos_dist = 0 and neg_dist = 2 in this example\"\ny_pred_perfect = ([1., 1.],[0., 0.], [1., 1.,])\nloss = triplet_loss(y_true, y_pred_perfect, 0)\nassert loss == 2., \"Wrong value. Check that pos_dist = 2 and neg_dist = 0 in this example\"\ny_pred_perfect = ([0., 0.],[0., 0.], [0., 0.,])\nloss = triplet_loss(y_true, y_pred_perfect, -2)\nassert loss == 0, \"Wrong value. Are you taking the maximum between basic_loss and 0?\"\ny_pred_perfect = ([[1., 0.], [1., 0.]],[[1., 0.], [1., 0.]], [[0., 1.], [0., 1.]])\nloss = triplet_loss(y_true, y_pred_perfect, 3)\nassert loss == 2., \"Wrong value. Are you applying tf.reduce_sum to get the loss?\"\ny_pred_perfect = ([[1., 1.], [2., 0.]], [[0., 3.], [1., 1.]], [[1., 0.], [0., 1.,]])\nloss = triplet_loss(y_true, y_pred_perfect, 1)\nif (loss == 4.):\n raise Exception('Perhaps you are not using axis=-1 in reduce_sum?')\nassert loss == 5, \"Wrong value. Check your implementation\"\n# END UNIT TEST\n\n\n# **Expected Output**:\n# \n# \n# \n# \n# \n# \n#
\n# loss\n# \n# 527.2598\n#
\n\n# \n# ## 4 - Loading the Pre-trained Model\n# \n# FaceNet is trained by minimizing the triplet loss. But since training requires a lot of data and a lot of computation, you won't train it from scratch here. Instead, you'll load a previously trained model in the following cell; which might take a couple of minutes to run.\n\n# In[20]:\n\n\nFRmodel = model\n\n\n# Here are some examples of distances between the encodings between three individuals:\n# \n#
\n#
Figure 4:
Example of distance outputs between three individuals' encodings
\n# \n# Now use this model to perform face verification and face recognition!\n\n# \n# ## 5 - Applying the Model\n# \n# You're building a system for an office building where the building manager would like to offer facial recognition to allow the employees to enter the building.\n# \n# You'd like to build a face verification system that gives access to a list of people. To be admitted, each person has to swipe an identification card at the entrance. The face recognition system then verifies that they are who they claim to be.\n# \n# \n# ### 5.1 - Face Verification\n# \n# Now you'll build a database containing one encoding vector for each person who is allowed to enter the office. To generate the encoding, you'll use `img_to_encoding(image_path, model)`, which runs the forward propagation of the model on the specified image.\n# \n# Run the following code to build the database (represented as a Python dictionary). This database maps each person's name to a 128-dimensional encoding of their face.\n\n# In[21]:\n\n\n#tf.keras.backend.set_image_data_format('channels_last')\ndef img_to_encoding(image_path, model):\n img = tf.keras.preprocessing.image.load_img(image_path, target_size=(160, 160))\n img = np.around(np.array(img) / 255.0, decimals=12)\n x_train = np.expand_dims(img, axis=0)\n embedding = model.predict_on_batch(x_train)\n return embedding / np.linalg.norm(embedding, ord=2)\n\n\n# In[22]:\n\n\ndatabase = {}\ndatabase[\"danielle\"] = img_to_encoding(\"images/danielle.png\", FRmodel)\ndatabase[\"younes\"] = img_to_encoding(\"images/younes.jpg\", FRmodel)\ndatabase[\"tian\"] = img_to_encoding(\"images/tian.jpg\", FRmodel)\ndatabase[\"andrew\"] = img_to_encoding(\"images/andrew.jpg\", FRmodel)\ndatabase[\"kian\"] = img_to_encoding(\"images/kian.jpg\", FRmodel)\ndatabase[\"dan\"] = img_to_encoding(\"images/dan.jpg\", FRmodel)\ndatabase[\"sebastiano\"] = img_to_encoding(\"images/sebastiano.jpg\", FRmodel)\ndatabase[\"bertrand\"] = img_to_encoding(\"images/bertrand.jpg\", FRmodel)\ndatabase[\"kevin\"] = img_to_encoding(\"images/kevin.jpg\", FRmodel)\ndatabase[\"felix\"] = img_to_encoding(\"images/felix.jpg\", FRmodel)\ndatabase[\"benoit\"] = img_to_encoding(\"images/benoit.jpg\", FRmodel)\ndatabase[\"arnaud\"] = img_to_encoding(\"images/arnaud.jpg\", FRmodel)\n\n\n# Load the images of Danielle and Kian: \n\n# In[23]:\n\n\ndanielle = tf.keras.preprocessing.image.load_img(\"images/danielle.png\", target_size=(160, 160))\nkian = tf.keras.preprocessing.image.load_img(\"images/kian.jpg\", target_size=(160, 160))\n\n\n# In[24]:\n\n\nnp.around(np.array(kian) / 255.0, decimals=12).shape\n\n\n# In[25]:\n\n\nkian\n\n\n# In[26]:\n\n\nnp.around(np.array(danielle) / 255.0, decimals=12).shape\n\n\n# In[27]:\n\n\ndanielle\n\n\n# Now, when someone shows up at your front door and swipes their ID card (thus giving you their name), you can look up their encoding in the database, and use it to check if the person standing at the front door matches the name on the ID.\n# \n# \n# ### Exercise 2 - verify\n# \n# Implement the `verify()` function, which checks if the front-door camera picture (`image_path`) is actually the person called \"identity\". You will have to go through the following steps:\n# \n# - Compute the encoding of the image from `image_path`.\n# - Compute the distance between this encoding and the encoding of the identity image stored in the database.\n# - Open the door if the distance is less than 0.7, else do not open it.\n# \n# As presented above, you should use the L2 distance `np.linalg.norm`.\n# \n# **Note**: In this implementation, compare the L2 distance, not the square of the L2 distance, to the threshold 0.7.\n# \n# *Hints*:\n# \n# - `identity` is a string that is also a key in the database dictionary.\n# - `img_to_encoding` has two parameters: the image_path and model.\n\n# In[30]:\n\n\n# UNQ_C2(UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: verify\n\ndef verify(image_path, identity, database, model):\n \"\"\"\n Function that verifies if the person on the \"image_path\" image is \"identity\".\n \n Arguments:\n image_path -- path to an image\n identity -- string, name of the person you'd like to verify the identity. Has to be an employee who works in the office.\n database -- python dictionary mapping names of allowed people's names (strings) to their encodings (vectors).\n model -- your Inception model instance in Keras\n \n Returns:\n dist -- distance between the image_path and the image of \"identity\" in the database.\n door_open -- True, if the door should open. False otherwise.\n \"\"\"\n ### START CODE HERE\n # Step 1: Compute the encoding for the image. Use img_to_encoding() see example above. (≈ 1 line)\n encoding = img_to_encoding(image_path, model)\n # Step 2: Compute distance with identity's image (≈ 1 line)\n dist = np.linalg.norm(database[identity] - encoding)\n # Step 3: Open the door if dist < 0.7, else don't open (≈ 3 lines)\n if dist < 0.7:\n print(\"It's \" + str(identity) + \", welcome in!\")\n door_open = True\n else:\n print(\"It's not \" + str(identity) + \", please go away\")\n door_open = False\n ### END CODE HERE \n return dist, door_open\n\n\n# Younes is trying to enter the office and the camera takes a picture of him (\"images/camera_0.jpg\"). Let's run your verification algorithm on this picture:\n# \n# \n\n# In[31]:\n\n\n# BEGIN UNIT TEST\nassert(np.allclose(verify(\"images/camera_1.jpg\", \"bertrand\", database, FRmodel), (0.54364836, True)))\nassert(np.allclose(verify(\"images/camera_3.jpg\", \"bertrand\", database, FRmodel), (0.38616243, True)))\nassert(np.allclose(verify(\"images/camera_1.jpg\", \"younes\", database, FRmodel), (1.3963861, False)))\nassert(np.allclose(verify(\"images/camera_3.jpg\", \"younes\", database, FRmodel), (1.3872949, False)))\n\nverify(\"images/camera_0.jpg\", \"younes\", database, FRmodel)\n# END UNIT TEST\n\n\n# **Expected Output**:\n# \n# \n# \n# \n# \n# \n#
\n# It's Younes, welcome in!\n# \n# (0.5992946, True)\n#
\n\n# Benoit, who does not work in the office, stole Kian's ID card and tried to enter the office. Naughty Benoit! The camera took a picture of Benoit (\"images/camera_2.jpg). \n# \n# \n# \n# Run the verification algorithm to check if Benoit can enter.\n\n# In[32]:\n\n\nverify(\"images/camera_2.jpg\", \"kian\", database, FRmodel)\n\n\n# **Expected Output**:\n# \n# \n# \n# \n# \n# \n#
\n# It's not Kian, please go away\n# \n# (1.0259346, False)\n#
\n\n# \n# ### 5.2 - Face Recognition\n# \n# Your face verification system is mostly working. But since Kian got his ID card stolen, when he came back to the office the next day he couldn't get in!\n# \n# To solve this, you'd like to change your face verification system to a face recognition system. This way, no one has to carry an ID card anymore. An authorized person can just walk up to the building, and the door will unlock for them!\n# \n# You'll implement a face recognition system that takes as input an image, and figures out if it is one of the authorized persons (and if so, who). Unlike the previous face verification system, you will no longer get a person's name as one of the inputs.\n# \n# \n# ### Exercise 3 - who_is_it\n# \n# Implement `who_is_it()` with the following steps:\n# \n# - Compute the target encoding of the image from `image_path`\n# - Find the encoding from the database that has smallest distance with the target encoding.\n# - Initialize the `min_dist` variable to a large enough number (100). This helps you keep track of the closest encoding to the input's encoding.\n# - Loop over the database dictionary's names and encodings. To loop use for (name, db_enc) in `database.items()`.\n# - Compute the L2 distance between the target \"encoding\" and the current \"encoding\" from the database. If this distance is less than the min_dist, then set min_dist to dist, and identity to name.\n\n# In[33]:\n\n\n# UNQ_C3(UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: who_is_it\n\ndef who_is_it(image_path, database, model):\n \"\"\"\n Implements face recognition for the office by finding who is the person on the image_path image.\n \n Arguments:\n image_path -- path to an image\n database -- database containing image encodings along with the name of the person on the image\n model -- your Inception model instance in Keras\n \n Returns:\n min_dist -- the minimum distance between image_path encoding and the encodings from the database\n identity -- string, the name prediction for the person on image_path\n \"\"\"\n \n ### START CODE HERE\n\n ## Step 1: Compute the target \"encoding\" for the image. Use img_to_encoding() see example above. ## (≈ 1 line)\n encoding = img_to_encoding(image_path, model)\n \n ## Step 2: Find the closest encoding ##\n \n # Initialize \"min_dist\" to a large value, say 100 (≈1 line)\n min_dist = 100\n \n # Loop over the database dictionary's names and encodings.\n for (name, db_enc) in database.items():\n \n # Compute L2 distance between the target \"encoding\" and the current db_enc from the database. (≈ 1 line)\n dist = np.linalg.norm(db_enc - encoding)\n\n # If this distance is less than the min_dist, then set min_dist to dist, and identity to name. (≈ 3 lines)\n if dist < min_dist:\n min_dist = dist\n identity = name\n ### END CODE HERE\n \n if min_dist > 0.7:\n print(\"Not in the database.\")\n else:\n print (\"it's \" + str(identity) + \", the distance is \" + str(min_dist))\n \n return min_dist, identity\n\n\n# Younes is at the front door and the camera takes a picture of him (\"images/camera_0.jpg\"). Let's see if your `who_it_is()` algorithm identifies Younes.\n\n# In[34]:\n\n\n# BEGIN UNIT TEST\n# Test 1 with Younes pictures \nwho_is_it(\"images/camera_0.jpg\", database, FRmodel)\n\n# Test 2 with Younes pictures \ntest1 = who_is_it(\"images/camera_0.jpg\", database, FRmodel)\nassert np.isclose(test1[0], 0.5992946)\nassert test1[1] == 'younes'\n\n# Test 3 with Younes pictures \ntest2 = who_is_it(\"images/younes.jpg\", database, FRmodel)\nassert np.isclose(test2[0], 0.0)\nassert test2[1] == 'younes'\n# END UNIT TEST\n\n\n# **Expected Output**:\n# \n# \n# \n# \n# \n# \n#
\n# it's Younes, the distance is 0.5992946\n# \n# (0.5992946, 'younes')\n#
\n# \n# You can change \"camera_0.jpg\" (picture of Younes) to \"camera_1.jpg\" (picture of Bertrand) and see the result.\n\n# **Congratulations**! \n# You've completed this assignment, and your face recognition system is working well! It not only lets in authorized persons, but now people don't need to carry an ID card around anymore!\n# \n# You've now seen how a state-of-the-art face recognition system works, and can describe the difference between face recognition and face verification. Here's a quick recap of what you've accomplished: \n# \n# - Posed face recognition as a binary classification problem\n# - Implemented one-shot learning for a face recognition problem\n# - Applied the triplet loss function to learn a network's parameters in the context of face recognition\n# - Mapped face images into 128-dimensional encodings using a pretrained model\n# - Performed face verification and face recognition with these encodings\n# \n# Great work! \n\n# \n# \n# **What you should remember**:\n# \n# - Face verification solves an easier 1:1 matching problem; face recognition addresses a harder 1:K matching problem.\n# \n# - Triplet loss is an effective loss function for training a neural network to learn an encoding of a face image.\n# \n# - The same encoding can be used for verification and recognition. Measuring distances between two images' encodings allows you to determine whether they are pictures of the same person.\n\n# **Ways to improve your facial recognition model**:\n# \n# Although you won't implement these here, here are some ways to further improve the algorithm:\n# \n# - Put more images of each person (under different lighting conditions, taken on different days, etc.) into the database. Then, given a new image, compare the new face to multiple pictures of the person. This would increase accuracy.\n# \n# - Crop the images to contain just the face, and less of the \"border\" region around the face. This preprocessing removes some of the irrelevant pixels around the face, and also makes the algorithm more robust.\n\n# \n# ## 6 - References\n# 1. Florian Schroff, Dmitry Kalenichenko, James Philbin (2015). [FaceNet: A Unified Embedding for Face Recognition and Clustering](https://arxiv.org/pdf/1503.03832.pdf)\n# \n# 2. Yaniv Taigman, Ming Yang, Marc'Aurelio Ranzato, Lior Wolf (2014). [DeepFace: Closing the gap to human-level performance in face verification](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-face-verification.pdf)\n# \n# 3. This implementation also took a lot of inspiration from the official FaceNet github repository: https://github.com/davidsandberg/facenet\n# \n# 4. Further inspiration was found here: https://machinelearningmastery.com/how-to-develop-a-face-recognition-system-using-facenet-in-keras-and-an-svm-classifier/\n# \n# 5. And here: https://github.com/nyoki-mtl/keras-facenet/blob/master/notebook/tf_to_keras.ipynb\n", "meta": {"hexsha": "bd46b1f3d6b273153c1cb2da9bd4b44322a39fa0", "size": 29722, "ext": "py", "lang": "Python", "max_stars_repo_path": "4 - Convolutional Neural Networks/Face_Recognition.py", "max_stars_repo_name": "pouyalj/DeepLearningCoursera", "max_stars_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-01T00:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T00:14:18.000Z", "max_issues_repo_path": "4 - Convolutional Neural Networks/Face_Recognition.py", "max_issues_repo_name": "pouyalj/DeepLearningCoursera", "max_issues_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 - Convolutional Neural Networks/Face_Recognition.py", "max_forks_repo_name": "pouyalj/DeepLearningCoursera", "max_forks_repo_head_hexsha": "4c0d79a53bbdd24fbb77503fed35e73d24949be2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2389649924, "max_line_length": 463, "alphanum_fraction": 0.6955790324, "include": true, "reason": "import numpy,from numpy", "num_tokens": 8089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.19193279106941585, "lm_q1q2_score": 0.09147126259553963}} {"text": "\"\"\"\nDefines comparer functions used by FormulaGrader and its subclasses.\n\nSimple Comparer Functions\n=========================\n\nA comparer function must have signature\n`comparer_func(comparer_params_eval, student_eval, utils)` and should return\nTrue, False, 'partial', or a dictionary with required key 'grade_decimal' and\noptional key 'msg'. When `FormulaGrader` (or its subclasses) call your custom\ncomparer function, `comparer_func`'s argument values are:\n\n- `comparer_params_eval`: The `comparer_params` list, numerically evaluated\n according to variable and function sampling.\n- `student_eval`: The student's input, numerically evaluated according to\n variable and function sampling.\n- `utils`: A convenience object that may be helpful when writing custom\n comparer functions. It has attributes:\n\n - `utils.tolerance`: The tolerance specified in grader configuration,\n `0.01%` by default\n - `utils.within_tolerance(x, y)`: checks that `y` is within specified\n tolerance of `x`. Can handle scalars, vectors, and matrices.\n If tolerance was specified as a percentage, then checks that\n `|x-y| < tolerance * x`.\n\n Comparer functions used inside `MatrixGrader` have the following additional\n `utils` method:\n\n - `utils.validate_shape(student_eval, shape)`: Checks that `student_eval`\n has specified `shape`, where `shape` is a Numpy shape tuple.\n\nA comparer function must return either:\n\n - a boolean, or\n - a dictionary with keys:\n - `'grade_decimal'`: number between 0 and 1 (required)\n - `'ok'`: `True` or `False` or `'partial'` (optional, inferred from\n grade_decimal by default)\n - `'msg'`: a feedback message (optional, defaults to `''`)\n\n\nNOTE: doctests in this module show how the comparer function would be used\n inside a grader\n\nCorrelated Comparers\n====================\nSee ./baseclasses.py and ./linear_comparer.py for examples.\n\"\"\"\nfrom __future__ import print_function, division, absolute_import, unicode_literals\n\nfrom numbers import Number\nimport numpy as np\n\nimport six\nfrom voluptuous import Schema, Required, Any, Range, All\n\nfrom mitxgraders.exceptions import InputTypeError, StudentFacingError\nfrom mitxgraders.helpers.validatorfuncs import is_callable, Nullable, text_string\nfrom mitxgraders.helpers.calc.mathfuncs import is_nearly_zero\nfrom mitxgraders.helpers.calc.math_array import are_same_length_vectors, is_vector\nfrom mitxgraders.comparers.baseclasses import Comparer, CorrelatedComparer\n\ndef identity_transform(x):\n \"\"\"\n Returns the input.\n\n Note: used instead of lambdas because it prints a nice name.\n \"\"\"\n return x\n\nclass EqualityComparer(Comparer):\n \"\"\"\n This comparer checks for equality between the student and instructor results,\n up to a desired tolerance. If desired, a transforming function can be applied\n before the comparison is carried out.\n\n comparer_params: ['expect']\n\n By default, equality_comparer is used in FormulaGrader, NumericalGrader and MatrixGrader.\n >>> from mitxgraders import *\n >>> equality_comparer == EqualityComparer()\n True\n >>> grader = FormulaGrader(\n ... answers='2*x',\n ... variables=['x']\n ... )\n >>> grader(None, 'x')['ok']\n False\n >>> grader(None, 'x*2')['ok']\n True\n\n The following example applies cosine to the expected answer and student input\n before comparison:\n >>> import numpy as np\n >>> grader = FormulaGrader(\n ... answers={\n ... 'comparer': EqualityComparer(transform=np.cos),\n ... 'comparer_params': ['x']\n ... },\n ... variables=['x']\n ... )\n >>> grader(None, 'x')['ok']\n True\n >>> grader(None, '-x')['ok']\n True\n >>> grader(None, 'x + 2*pi')['ok']\n True\n >>> grader(None, 'x + pi')['ok']\n False\n\n The following example takes the norm of the expected answer and student input\n before comparison. Note the different method of changing the comparer.\n >>> MatrixGrader.set_default_comparer(EqualityComparer(transform=np.linalg.norm))\n >>> grader = MatrixGrader(\n ... answers='[1, 0, 0]'\n ... )\n >>> grader(None, '[1, 0, 0]')['ok']\n True\n >>> grader(None, '[0, 1, 0]')['ok']\n True\n >>> grader(None, '[1/sqrt(2), 0, 1/sqrt(2)]')['ok']\n True\n >>> MatrixGrader.reset_default_comparer()\n\n FormulaGrader and MatrixGrader both have set_default_comparer() and\n reset_default_comparer() methods.\n\n \"\"\"\n schema_config = Schema({\n Required('transform', default=None): All(\n Nullable(is_callable),\n # if f is None, coerce to identity function\n lambda f: identity_transform if f is None else f\n )\n })\n\n @staticmethod\n def validate(expected_eval, student_eval, utils):\n if hasattr(utils, 'validate_shape'):\n # in numpy, scalars have empty tuples as their shapes\n shape = tuple() if isinstance(expected_eval, Number) else expected_eval.shape\n utils.validate_shape(student_eval, shape)\n\n def __call__(self, comparer_params_eval, student_eval, utils):\n expected_eval = comparer_params_eval[0]\n self.validate(expected_eval, student_eval, utils)\n\n transform = self.config['transform']\n expected_eval = transform(expected_eval)\n student_eval = transform(student_eval)\n\n return utils.within_tolerance(expected_eval, student_eval)\n\nequality_comparer = EqualityComparer()\n\nclass MatrixEntryComparer(CorrelatedComparer):\n \"\"\"\n Default comparer for MatrixGrader. Compares student and instructor array\n evaluations entry-by-entry for equality. Note that despite the name, this comparer\n works equally well on vectors/matrices/tensors.\n\n Configuration\n =============\n transform (None | function): same as EqualityComparer (default None)\n\n entry_partial_credit ('proportional' | number): Determines how partial credit\n is awarded. If set to 'proportional', then credit is proportional to\n the number of correct array entries. If a numeric value betweem 0 and 1\n is provided, this flat rate of partial credit is provided as long as\n some but not all entries are correct. Default is the numeric value 0\n (no partial credit).\n\n entry_partial_msg (str): A text string message shown when partial credit\n is awarded. The string may optionally contain the formatting key {error_indices},\n which will be replaced with a diagram showing the correct/incorrect entries.\n To show no message, use the the empty string.\n Default value is:\n \"Some array entries are incorrect, marked below:\\n{error_locations}\"\n \"\"\"\n\n default_msg = \"Some array entries are incorrect, marked below:\\n{error_locations}\"\n schema_config = EqualityComparer.schema_config.extend({\n Required('entry_partial_credit', default=0): Any(All(float, Range(0, 1)), 0, 1, 'proportional'),\n Required('entry_partial_msg', default=default_msg): text_string\n })\n\n @staticmethod\n def format_message_with_locations(format_string, locs):\n \"\"\"\n Returns format_string with {error_locations} replaced by a diagram showing\n correct/incorrect entries.\n\n Arguments:\n format_string: a string that may contain {error_locations} formatting key.\n locs: a boolean array with False values indicating incorrect entries\n \"\"\"\n # Not the most elegant way to do these replacements, but this was what\n # I came up with to minimize the amount of extra u prefixes in Python 2\n\n # These are the edX colors, at least as of July 2019\n bad_str = '\\u2717'\n good_str = '\\u2713'\n matrix_as_text = six.text_type(locs).replace(\" \", \" \").replace(\"[ \", \"[\")\n matrix_as_text = matrix_as_text.replace(\"True\", good_str).replace(\"False\", bad_str)\n matrix_as_text = matrix_as_text.replace('\\n', '
')\n formatted_locs = '
{mat}
'.format(mat=matrix_as_text)\n return format_string.format(error_locations=formatted_locs)\n\n @staticmethod\n def validate(expected_evals, student_evals, utils):\n for x, y in zip(expected_evals, student_evals):\n EqualityComparer.validate(x, y, utils)\n\n def __call__(self, comparer_params_evals, student_evals, utils):\n expected_evals = [params[0] for params in comparer_params_evals]\n self.validate(expected_evals, student_evals, utils)\n\n transform = self.config['transform']\n expected_evals = [transform(x) for x in expected_evals]\n student_evals = [transform(x) for x in student_evals]\n vec_within_tol = np.vectorize(utils.within_tolerance)\n # comparisons_by_eval is a boolean array of entry-by-entry comparisons,\n # one for each comparison. Its numpy shape is (n_evals, *eval_shape)\n comparisons_by_eval = vec_within_tol(expected_evals, student_evals)\n comparisons_summary = np.all(comparisons_by_eval, axis=0)\n\n num_entries = comparisons_summary.size\n percent_correct = np.sum(comparisons_summary).item()/num_entries\n msg = self.format_message_with_locations(self.config['entry_partial_msg'], comparisons_summary)\n partial_credit = self.config['entry_partial_credit']\n\n if percent_correct == 1:\n return True\n elif percent_correct == 0:\n return {'ok': False, 'grade_decimal': 0, 'msg': msg}\n elif partial_credit == 'proportional':\n return {'ok': 'partial', 'grade_decimal': percent_correct, 'msg': msg}\n else:\n return {'ok': 'partial', 'grade_decimal': partial_credit, 'msg': msg}\n\ndef between_comparer(comparer_params_eval, student_eval, utils):\n \"\"\"\n Used to check that input is real and between two parameters.\n\n comparer_params: ['start', 'stop']\n\n Example:\n >>> from mitxgraders import NumericalGrader\n >>> grader = NumericalGrader(\n ... answers={\n ... 'comparer': between_comparer,\n ... 'comparer_params': ['1e6', '1e9']\n ... }\n ... )\n >>> grader(None, '2.5e8')['ok']\n True\n >>> grader(None, '0.001e8')['ok']\n False\n >>> grader(None, '5e7')['ok']\n True\n\n Input must be real:\n >>> try:\n ... grader(None, '5e8+2e6*i')['ok']\n ... except InputTypeError as error:\n ... print(error)\n Input must be real.\n \"\"\"\n start, stop = comparer_params_eval\n\n if not np.isreal(student_eval):\n raise InputTypeError(\"Input must be real.\")\n\n return start <= student_eval <= stop\n\ndef congruence_comparer(comparer_params_eval, student_eval, utils):\n \"\"\"\n Compares the student input to a target, moduli a given modulus.\n Will often set modulus to 2*pi in order to compare angles.\n\n comparer_params: [target, modulus]\n\n Example usage:\n >>> from mitxgraders import FormulaGrader\n >>> grader = FormulaGrader(\n ... answers={\n ... 'comparer': congruence_comparer,\n ... 'comparer_params': [\n ... 'b^2/a', # target\n ... 'c' # modulus\n ... ]\n ... },\n ... variables=['a', 'b', 'c']\n ... )\n >>> grader(None, 'b^2/a')['ok']\n True\n >>> grader(None, 'b^2/a + 1.5*c')['ok']\n False\n >>> grader(None, 'b^2/a + 2*c ')['ok']\n True\n \"\"\"\n expected, modulus = comparer_params_eval\n\n expected_reduced = expected % modulus\n input_reduced = student_eval % modulus\n return utils.within_tolerance(expected_reduced, input_reduced)\n\ndef eigenvector_comparer(comparer_params_eval, student_eval, utils):\n \"\"\"\n Used to check that a student's answer is an eigenvector of a matrix\n with a given eigenvalue. Ignores scaling of the eigenvector.\n\n comparer_params: [matrix, eigenvalue]\n\n Example Usage:\n >>> from mitxgraders import MatrixGrader\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[[1, x], [x, -1]]', # matrix\n ... 'sqrt(1+x^2)' # eigenvalue\n ... ],\n ... 'comparer': eigenvector_comparer\n ... },\n ... variables=['x']\n ... )\n >>> grader(None, '[1+sqrt(1+x^2), x]')['ok']\n True\n >>> grader(None, '2*[1+sqrt(1+x^2), x]')['ok']\n True\n >>> grader(None, '[1+sqrt(1+x^2), 1]')['ok']\n False\n >>> grader(None, '[0, 0]') == {\n ... 'ok': False,\n ... 'msg': 'Eigenvectors must be nonzero.',\n ... 'grade_decimal': 0\n ... }\n True\n\n \"\"\"\n\n matrix, eigenvalue = comparer_params_eval\n\n # matrix is square with shape (n, n); student input should have shape (n, )\n expected_input_shape = (matrix.shape[0], )\n utils.validate_shape(student_eval, expected_input_shape)\n\n expected = eigenvalue * student_eval\n actual = matrix * student_eval\n\n if utils.within_tolerance(0, np.linalg.norm(student_eval)):\n return {\n 'ok': False,\n 'grade_decimal': 0,\n 'msg': 'Eigenvectors must be nonzero.'\n }\n\n return utils.within_tolerance(actual, expected)\n\ndef vector_span_comparer(comparer_params_eval, student_eval, utils):\n \"\"\"\n Check whether student's answer is nonzero and in the span of some given\n vectors.\n\n comparer_params: A list of vectors\n\n Usage\n =====\n\n Use a single vector as comparer_params to test whether student input is\n parallel to a particular vector:\n >>> from mitxgraders import MatrixGrader\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[3, x, 1 + i]',\n ... ],\n ... 'comparer': vector_span_comparer\n ... },\n ... variables=['x'],\n ... )\n >>> grader(None, '[3, x, 1 + i]')['ok']\n True\n >>> grader(None, '[9, 3*x, 3 + 3*i]')['ok']\n True\n >>> grader(None, '[9, 3*x, 3 - 3*i]')['ok']\n False\n\n Complex scale factors work, too:\n >>> grader(None, '(4 + 2*i)*[3, x, 1 + i]')['ok']\n True\n\n Student input should be nonzero:\n >>> result = grader(None, '[0, 0, 0]')\n >>> expected = {\n ... 'ok': False,\n ... 'grade_decimal': 0.0,\n ... 'msg': 'Input should be a nonzero vector.'\n ... }\n >>> result == expected\n True\n\n Input shape is validated:\n >>> try:\n ... grader(None, '5')\n ... except InputTypeError as error:\n ... print(error)\n Expected answer to be a vector, but input is a scalar\n\n Multiple vectors can be provided:\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[1, 1, 0]', # v0\n ... '[0, 1, 2]' # v1\n ... ],\n ... 'comparer': vector_span_comparer\n ... },\n ... )\n\n The vector 2*v0 + 3i*v1 = [2, 2+3i, 6i] is in the span of v0 and v1:\n >>> grader(None, '[2, 2 + 3*i, 6*i]')['ok']\n True\n\n The comparer_params should be list of equal-length vectors:\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[1, 1, 0]',\n ... '5'\n ... ],\n ... 'comparer': vector_span_comparer\n ... },\n ... )\n >>> try:\n ... grader(None, '[1, 2, 3]') # doctest: +ELLIPSIS\n ... except StudentFacingError as error:\n ... print(error)\n Problem Configuration Error: ...to equal-length vectors\n \"\"\"\n\n # Validate the comparer params\n if not are_same_length_vectors(comparer_params_eval):\n raise StudentFacingError('Problem Configuration Error: comparer_params '\n 'should be a list of strings that evaluate to equal-length vectors')\n\n # Validate student input shape\n utils.validate_shape(student_eval, comparer_params_eval[0].shape)\n\n if utils.within_tolerance(0, np.linalg.norm(student_eval)):\n return {\n 'ok': False,\n 'grade_decimal': 0,\n 'msg': 'Input should be a nonzero vector.'\n }\n\n # Use ordinary least squares to find an approximation to student_eval\n # that lies within the span of given vectors, then check that the\n # residual-sum is small in comparison to student input.\n column_vectors = np.array(comparer_params_eval).transpose()\n # rcond=-1 uses machine precision for testing singular values\n # In numpy 1.14+, use rcond=None fo this behavior. (we use 1.6)\n ols = np.linalg.lstsq(column_vectors, student_eval, rcond=-1)\n error = np.sqrt(ols[1])\n\n # Check that error is nearly zero, using student_eval as a reference\n # when tolerance is specified as a percentage\n return is_nearly_zero(error, utils.tolerance, reference=student_eval)\n\ndef vector_phase_comparer(comparer_params_eval, student_eval, utils):\n \"\"\"\n Check that student input equals a given input (to within tolerance), up to\n an overall phase factor.\n\n comparer_params: [target_vector]\n\n Usage\n =====\n\n >>> from mitxgraders import MatrixGrader\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[1, exp(-i*phi)]',\n ... ],\n ... 'comparer': vector_phase_comparer\n ... },\n ... variables=['phi'],\n ... )\n\n >>> grader(None, '[1, exp(-i*phi)]')['ok']\n True\n >>> grader(None, '[exp(i*phi/2), exp(-i*phi/2)]')['ok']\n True\n >>> grader(None, '[i, exp(i*(pi/2 - phi))]')['ok']\n True\n\n >>> grader(None, '[1, exp(+i*phi)]')['ok']\n False\n >>> grader(None, '[2, 2*exp(-i*phi)]')['ok']\n False\n\n The comparer_params should be list with a single vector:\n >>> grader = MatrixGrader(\n ... answers={\n ... 'comparer_params': [\n ... '[1, 1, 0]',\n ... '[0, 1, 1]'\n ... ],\n ... 'comparer': vector_phase_comparer\n ... },\n ... )\n >>> try:\n ... grader(None, '[1, 2, 3]') # doctest: +ELLIPSIS\n ... except StudentFacingError as error:\n ... print(error)\n Problem Configuration Error: ...to a single vector.\n \"\"\"\n # Validate that author comparer_params evaluate to a single vector\n if not len(comparer_params_eval) == 1 and is_vector(comparer_params_eval[0]):\n raise StudentFacingError('Problem Configuration Error: comparer_params '\n 'should be a list of strings that evaluate to a single vector.')\n\n # We'll check that student input is in the span as target vector and that\n # it has the same magnitude\n\n in_span = vector_span_comparer(comparer_params_eval, student_eval, utils)\n\n expected_mag = np.linalg.norm(comparer_params_eval[0])\n student_mag = np.linalg.norm(student_eval)\n same_magnitude = utils.within_tolerance(expected_mag, student_mag)\n\n return in_span and same_magnitude\n", "meta": {"hexsha": "76f5a0bff40aaa5604c2bc062cf81f4da4bb4e0f", "size": 18902, "ext": "py", "lang": "Python", "max_stars_repo_path": "mitxgraders/comparers/comparers.py", "max_stars_repo_name": "ChristopherChudzicki/mitx-grading-library", "max_stars_repo_head_hexsha": "1d9a7107f26b5e0ebe24deb552cf943779693e18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mitxgraders/comparers/comparers.py", "max_issues_repo_name": "ChristopherChudzicki/mitx-grading-library", "max_issues_repo_head_hexsha": "1d9a7107f26b5e0ebe24deb552cf943779693e18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mitxgraders/comparers/comparers.py", "max_forks_repo_name": "ChristopherChudzicki/mitx-grading-library", "max_forks_repo_head_hexsha": "1d9a7107f26b5e0ebe24deb552cf943779693e18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3308411215, "max_line_length": 104, "alphanum_fraction": 0.6233202836, "include": true, "reason": "import numpy", "num_tokens": 4647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.18242552825126704, "lm_q1q2_score": 0.09050017890342647}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Lab 2: Astronomical Imaging I \n# \n# *Gather round, for I shall tell a tale old as time. \n# Long, long ago, astronomers gazed at the heavens, and with naught but their eyes, recorded the positions of the stars they saw there. \n# Then, with the telescope, long, heavy contraptions which reached for the skies like an outstretched arm, (thanks, f/20 focal lengths)\n# they gazed through eyepieces in freezing domes, falling, on occasion, to their deaths from cages suspended at prime foci.* \n# \n# *Next came glass -- emulsion plates -- which upon extended exposure revealed upon their ghostly frames the splotches of stars and soon, galaxies and nebulae. \n# Many a grad student, of course, spent their nights twiddling thumbs over micrometer dials to keep these stars in place. Manual guiding... this story teller shudders to imagine it.\n# And yet, even then, with permanent record, no measure could be made that weren't 'tween the eyes of an observer, peering at the glass through magnifying eyepiece, assigning grades of brightness and, amazingly, pretty much nailing the spectral classification of stars by their absorption features*. \n# \n# *And after this painstaking work, came the earliest CCDs, fractured by detector failures, riddled with readout noise, consumed by cosmic ray hits, laid low by low quantum efficiencies.* \n# \n# *Now... we use Python.* \n# \n\n#
\n# Astronomical images are one of the basic building blocks of astronomical research. While we now obtain data in myriad ways, from gravitational waves to neutrinos, from spectra to polarimetry, the basic tenant of astronomy (and it's most recongizable public impact) is the images we make of the sky. \n# \n# That is why the first science topic we'll be tackling is imaging. And along the way, we'll learn how `astropy` makes our lives *so* much easier when dealing with images, and how to use robust functions to perform the analyses one might want to carry out on images (after we're done admiring their beauty). \n# \n# # If the glove `FITS`\n# \n# Many of you are probably familiar with the `FITS` standard. It stands for `Flexible Image Transport System`, and for all intents and purposes, it acts as a container (much like a zip file). Within it, one can store several kinds of information: images (2d arrays of values), as the name implies, headers (dictionary like objects with metadata), and sometimes tabular data as well. A `FITS` file can contain any number of *extensions*, which just refer to \"slots\" where stuff is stored. Every \"slot\" has a `header` attribute and a `data` attribute. Thus, you could store a hundred astronomical images in 1 file, each with a different extension and a different header describing the image in that slot. \n# \n# ```{tip}\n# Contextual clues are important when dealing with `FITS` files. Files that are explicitly single images almost always have the image stored in the 0th extension, while files that are explicitly table data tend to have the table stored in the 1st extension (with the 0th empty). \n# ```\n# \n# The `FITS` standard is pretty old, and may be retired soon, but almost all ground based telescopes still use it for their native image output, so it behooves us to know how to get image data out of `FITS` files. \n# \n# ## Problem 1: Loading a FITS file\n# \n# Write a function which takes as its argument a `string` filepath to a `FITS` file, and should have an optional argument to set the extension (default 0). It should then load the given extension of that `fits` file using a [context manager](https://docs.astropy.org/en/stable/io/fits/index.html#opening-a-fits-file), and return a tuple containing the header and data of that extension. \n# \n# The function should have documentation that describes the inputs and outputs. Documentation is **incredibly important** when writing code, both in-line and (# comments) and at the top of functions, methods, and classes. \n# \n# In this class, we'll be using [Sphinx-compatible](https://www.sphinx-doc.org/en/master/) documentation written in the [Numpy/Scipy style](https://numpydoc.readthedocs.io/en/latest/format.html). There are several reasons to do this. \n# \n# 1. It is a user-friendly and write-friendly, readable documentation format that is easy to add to your functions.\n# 2. It can be rendered by Sphinx, the most popular automatic documentation renderer. If you've ever read the online documentation pages for functions in, e.g., numpy and scipy, those pages were rendered automatically based on the docstrings of the functions in question. This is possible with tools like Sphinx, but the documentation must be formatted correctly for this to work. \n# \n# In the cell below, I've provided a dummy function which takes in any number of inputs (mininum 3) and chooses a random input to return. The formatting of the documentation is shown there (as well as in the link above). \n# \n# \n\n# In[5]:\n\n\nimport numpy as np \n\ndef random_return(a,b,c,*args):\n '''\n A function which requires three inputs which are floats, accepts any number of additional inputs (of any kind), and returns one randomly chosen input. \n \n Parameters\n ----------\n a: int\n description of this integer input\n b: int\n description of this integer input\n c: int\n description of this integer input\n *args: tuple\n any additional arguments get stored here\n \n Returns\n -------\n choice \n The randomly selected input (type not specified)\n '''\n full_input_list = [a,b,c] + list(args)\n choice = np.random.choice(full_input_list)\n return choice\n\n\n# In[11]:\n\n\nrandom_return(1,5,4,6,4,21,6)\n\n\n# When our function has been imported in some code, we can use the `help` command to see the documentation at any time:\n\n# In[9]:\n\n\nhelp(random_return)\n\n\n# You will also notice my use of `*args` in this function. This allows me to enter additional function arguments. Similar is `**kwargs`, which allows additional arguments tied to an input keyword. The former gets stored in a tuple, while the latter gets stored in a dictionary. We'll be using these a lot in class --- you can refresh or learn the basics in Section 2.8 of the chapter on functional programming [here](https://prappleizer.github.io/Tutorials/FunctionalProgramming/FunctionalProgramming_web.html).\n# \n# So as a brief overview of documentation, it contains\n# 1. A brief summary of the function \n# 2. The word Parameters with the next line having underlines of the same length\n# 3. arguments, which are followed by a colon and the data type(s). On the next line, indented, descriptions of the arguments\n# 4. The word Returns, with the same underline scheme\n# 5. The returned objects, labeled the same way as the input. \n# \n# Also above, we saw how to format when no data type is specified. There, additional inputs could've been *any* data type, so we can't be sure what the output will be. The main thing we didn't cover is optional arguments. Those are set like this:\n# ```\n# a: int, optional\n# Description of the thing. (default 5)\n# ```\n# So we mark it as optional, and then give the default for it. \n# \n# With that, you're ready to write and document your code below. **All functions you write in this class should have documentation**. \n\n# In[10]:\n\n\nfrom astropy.io import fits \nimport os\n\n# your code\ndef load_fits(...):\n '''\n\n '''\n pass\n\n \n\n\n# ## Problem 2: Data I/O\n# ### Problem 2.1\n# Using the function you created above, read in the header and data of the file `antenna_Rband.fits` which came with the lab assignment. \n# ```{note}\n# While this may seem small, the fact that your read-in is now one line instead of ~5 does improve your efficiency! But only if you use your function enough times to overcome the initial time spent writing it... \n# We also have the flexibility to take our function and give it more features over time, which we will do in this class.\n# \n# ``` \n\n# ### Problem 2.2\n# Next, we need to plot the image data. There are several operations that we almost always perform when plotting astronomical data, as well as several user-preferences for how we \"by default\" plot images before we begin tweaking things. If you spend any time as an astronomer, you will plot quite literally *thousands* of images --- why set all these settings every time, when we can write a handy function to do it for us?\n# \n# Write a function which takes in as input arguments \n# - an image (2D array or masked array) \n# \n# as well as the following optional arguments (so set a default)\n# - figsize (default (15,13) )\n# - cmap (default 'gray_r')\n# - scale (default 0.5)\n# - \\*\\*kwargs (see [here](https://prappleizer.github.io/Tutorials/FunctionalProgramming/FunctionalProgramming_web.html))\n# \n# Inside the function, create figure and axes objects using `plt.subplots()`. When working in notebooks, it is often useful to set the `figsize` argument of subplots to a nice large-ish value, such as `(15,13)`, which will make the image fill most of the notebook. Since *your* function has set figsize as an argument, you can feed `figsize` directly into the `subplots` call, so that a user of the function can leave the default or set their own. \n# \n# Next, use `ax.imshow()` to actually plot the image. You'll want to save the output of this, e.g., `im = ax.imshow(...)`. In this plotting call, set `imshow`'s argument `origin='lower'`. We *always* want to do this when dealing with imaging, as we want (0,0) to be a coordinate. \n# ```{note}\n# By default, matplotlib uses a \"matrix-style\" plotting, where 0 of the y axis is in the *top* left corner, and 0 of the x axis is in the *bottom* left corner.\n# ```\n# Also within the call to `imshow()`, feed in the cmap from your function (i.e., `cmap=cmap`). The other critical `imshow()` arguments are `vmin` and `vmax`, which sets the saturation points (and thus the contrast) of the image. \n# \n# We haven't set `vmin` and `vmax` as arguments of our outer function, but because of `kwargs`, we can still create a default here that can be overriden from outside. \n# \n# As a default, within your function, calculate the mean and standard deviation of the image. Set some temporary variables with the quantities `mu - scale*sigma` and `mu + scale*sigma` (where here `mu` is the calculated mean and `sigma` is the calculated std dev, and `scale` was the optional input). Next, check the kwargs dictionary (which will exist in your function because we added the packing argument `**kwargs` to our function. IF `vmin` and `vmax` are in this dictionary, plug those into your imshow command. Otherwise, use the values determined by the calculation above. Bonus point for accomodating either no vmin/vmax entered, just vmin or vmax, or both (using the calculated values when things aren't provided). \n# \n# Your function should **return** the created `fig` and `ax` objects so the user can continue to tweak them.\n# \n# Run your function and test its outputs. Once you're satisfied it's working, use it to plot the provided data. Find either a vmin/vmax pair, or a choice of `scale` which makes the image look pretty!\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Your code\ndef implot(...):\n ''' \n WRITE DOCSTRING HERE\n '''\n pass #replace with your code\n\n\n# In[42]:\n\n\n# I've included my output below for your comparison. Overwrite it with your own! \n\n\n# ### Problem 2.3\n# \n# Copy your function down, we're going to keep messing with it. \n# \n# So far, we've made it so that with a simple function call and, potentially, with just the input of an image array, we get out a nice plot with a scaling, colormap, and origin selection. In this section, we are going to allow (optionally) for a colorbar to be added to the figure. We're also going to add in the ability for the figure to be plotted in celestial coordinates (i.e., RA and DEC) instead of pixel units, if information about the image (via the world coordinate system, WCS) exists in the image header. \n# \n# ```{note}\n# Generally, WCS information is present in the headers of *published* images like the one here, but *not* present in raw data gathered at the telescope. This is because images need to undergo a process known as *plate solving* to determine both the direction (coordinates) toward the image, as well as the pixel scale (i.e., how many arcseconds per pixel in the image). \n# ```\n# \n# Add three new optional arguments to your function.\n# - colorbar = False\n# - header = None\n# - wcs = None\n# \n# Let's start with the colorbar. At the end of your plotting commands, check if `colorbar=True`, and if so, create a colorbar via `plt.colorbar()`, setting the `mappable` argument to whatever you saved the output of `ax.imshow()` into above. Also set the `ax` argument to be your ax; this will tell `matplotlib` to steal a bit of space from that axis to make room for the colorbar. \n# \n# \n# \n\n# In[46]:\n\n\n# Your code\n\n\n# ```{tip}\n# When I do this, the colorbar is matching the figure height, rather than the axis height. If that bugs you like it bugs me, check out [this solution](https://stackoverflow.com/a/33505522) from StackOverflow, which you can adapt within your function to make the cbar match the axis height.\n# ```\n# \n# In order to plot in RA and DEC coordinates, we need to first have an `astropy` `WCS` object associated with the image in question. You can import `WCS` from `astropy.wcs`. WCS objects are created from the headers of plate-solved fits files. In our function, we allow the user to input either a header or a WCS object directly. More on WCS can be found in the lecture notes, or [here](https://docs.astropy.org/en/stable/wcs/index.html).\n# \n# Within your function, check if a wcs is input -- if it is, we're good to go and can safely ignore `header` (even if it is provided). If instead only `header` is provided, use the `WCS()` function to create a new wcs object from that header. \n# ```{tip}\n# You'll want to do this at the very top of your function.\n# ```\n# \n# We now need to move our `fig, ax = ....` creation line into an if-statement. If we are using WCS \"stuff\", you'll need to set a `projection` for your plot that uses the wcs. This is accomplished as follows:\n# \n# ```\n# fig, ax = plt.subplots(...,subplot_kw={'projection':wcs}) \n# ```\n# where `wcs` is whatever you've named the output of `WCS(header)` or is the WCS input directly into the function. \n# \n# \n\n# In[4]:\n\n\nfrom astropy.wcs import WCS\n\n# your code\n\n\n# ```{warning}\n# In this case, we will get an error from our function that happens because of some distortion coefficient nonsense between astropy and drizzled HST images. Since it's not pertinent to our lab, I'm providing below a snippet of code you should use to fix your header before running `WCS(header)`. \n# ```\n\n# In[203]:\n\n\ndef strip_SIP(header):\n A_prefixes = [i for i in header.keys() if i.startswith('A_')]\n B_prefixes = [i for i in header.keys() if i.startswith('B_')]\n for a,b in zip(A_prefixes,B_prefixes):\n del header[a]\n del header[b]\n return header\n\n\n# If this worked correctly, when you add the header you read in from our image, you should now see the axes of your plot change from pixels to `pos.eq.ra` and `pos.eq.dec`. We're now looking at actual on-sky coordinates! Yay!\n# \n# ### Problem 2.4 \n# Within the if-blocks of your function that sets the `ax` to be a wcs projection, set the $x$ and $y$ labels to read \"Right Ascension \\[hms\\]\" and \"Declination \\[degrees\\]\" in fontsize 15.\n# \n# Lastly, to polish things off, use `ax.tick_params()` to set inward, larger ticks, and increase the axis tick label size to 15. \n# \n# ```{note}\n# You'll notice (especially with larger ticks) that the are not perpendicular to the axes spines. This is because this particular image has been rotated with respect to the standard celestial coordinate axes. This can be seen more clearly if you add the following to your function:\n# `ax.coords.grid(color='gray', alpha=0.5, linestyle='solid')`. Try doing that, adding an optional keyword to your function called 'grid' and enabling this command if it is set.\n# ```\n# \n# ```{tip}\n# To check if a condition is true (e.g, `if condition == True:`), you can just type `if condition:`\n# ```\n# \n# It's taken us some time, but this image could now be placed in a scientific publication. And, since we have a handy function for it, we can make images that look this nice on the fly with a short one line command, yet still have a lot of flexibility over many important inputs. And of course, the figure and axes objects are returned, so one could run this function and then continue tweaking the plot after the fact.\n# \n# ```{note}\n# As a final note, I want to draw your attention to the fact that once you use the `wcs` projection on some plot, it's no longer a normal ax object, it's a wcsax object. This makes changing certain elements of those axes a little more involved than for a standard one. I use [this page](https://docs.astropy.org/en/stable/visualization/wcsaxes/ticks_labels_grid.html) and the others linked there when doing so. \n# ```\n\n# ## Problem 3: Cutouts and Aperture Photometry\n\n# When working with astronomical images, like the one we've been using in this lab, it is often advantageous to be working with a cutout -- a chunk of the image centered on a certain coordinate, and of a certain size. For example, if there is an HII region or star cluster of interest in the above image, we may like to zoom in on it to examine it more closely. \n# \n# Now that we've switched over to using celestial coordinates instead of pixels as our projection frame, zooming in on a region is not as simple as slicing our array, e.g., `image[500:700,200:550]`. On the plus side, the framework we'll learn here is very robust, and will allow for all sorts of useful measurements. \n# \n# \n# To make a cutout, we'll need the `Cutout2D` module within `astropy`, which I'll import below. To provide the position of the cutout, we need to be able to feed in astronomical coordinates. For this, we'll use `SkyCoord`, a module in `astropy.coordinates`. Finally, we'll need to integrate the `units` module in `astropy` to successfully create coordinate objects.\n\n# In[100]:\n\n\nfrom astropy.nddata import Cutout2D\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\n\n\n# Let's start with a `SkyCoord` object. There are several coordinate systems used in astronomy, e.g., Galactic coordinates ($b$, $l$), Equatorial ($RA$, $DEC$). The most common (especially in any extragalactic setting) is RA and DEC (as you can see in the image you've plotted already). \n# \n# The [documentation](https://docs.astropy.org/en/stable/api/astropy.coordinates.SkyCoord.html) for `SkyCoord` is solid, and worth reading. \n# \n# The general way we create these objects is, e.g.,\n\n# In[103]:\n\n\ncoord = SkyCoord('12:01:53.6 -18:53:11',unit=(u.hourangle,u.deg))\n\n\n# ```{tip}\n# You can input various types of strings and formattings for the coordinates, just be sure to specify the units as shown above. The documentation shows the various methods.\n# ```\n# \n# ### Problem 3.1\n# \n# In this case, the coordinates I set above are for NGC 4039, which is the smaller of the two galaxies in the image we're using. \n# \n# ```{note}\n# If at any point you're trying to make a coordinate object for a well known galaxy/object, try, e.g., `coord = SkyCoord.from_name('NGC 4038')`, and ususally that will work!\n# ```\n# \n# \n# In the cell below, use the coordinate we've created, plus a size (use 1x1 arcminutes), and the wcs object for our image, to create a `Cutout2D` object. \n\n# In[106]:\n\n\n#cutout = # your code here\n\n\n# Now, use your fancy new function to plot the new cutout. \n# ```{note}\n# Cutout objects contain the image and their own wcs, accessible via, e.g., `cutout.data` and `cutout.wcs`. \n# ```\n# \n\n# In[ ]:\n\n\n# plot it\n\n\n# ### Problem 3.2\n# \n# We're now going to do some aperture photometry. \n# ```{admonition} Definition\n# Aperture Photometry is the process of defining a region on an image (generally, but not always circular), and measuring the sum pixel value within that region. The region is known as an aperture, and the \"collapsing\" of the 2D spatial information about counts in each pixel into a single number is known as photometry.\n# ```\n# \n# Below, I provide a new coordinate, this time centered on the region between the two galaxies. Make a new cutout of that region (again, 1x1 arcmin), and plot it.\n\n# In[120]:\n\n\nnew_coord = SkyCoord('12:01:55.0 -18:52:45',unit=(u.hourangle,u.deg))\n\n\n# In[121]:\n\n\n# your code\n\n\n# In[5]:\n\n\n#plot it\n\n\n# In this region, there are a lot of blobby looking roughly circular sources --- Some of the larger ones are HII star forming regions, the smaller ones are likely stars. Later in this lab, we'll use multi-wavelength data to try to suss out what is what. \n# \n# Often, for calibration purposes, we'd need to create apertures around all those sources in the image. We definitely don't want to do that by hand! Instead, we're going to use the `sep` package. \n# \n# ```{note}\n# Simply `pip install sep` inside your `a330` environment terminal to get it installed, you should then be able to import it.\n# ```\n# \n# \n\n# In[123]:\n\n\nimport sep\n\n\n# There are three steps to performing aperture photometry with `sep`, which are detailed in [it's documentation](https://sep.readthedocs.io/en/v0.4.x/). \n# \n# - Estimate the background \n# - Find Sources \n# - Perform Aperture Photometry\n# \n# Using the instructions presented in the documentation linked, measure the background of the cutout image, and run the source extractor on it. Don't forget to subtract the background before running the extractor!\n# \n# To do this, write a function that takes as input the data (in this case, a `cutout.data` object and a threshold scale (to be multiplied by the `globalrms`, and performs these steps, returning the `objects` array. Don't forget to document it!\n# \n# ```{hint}\n# :class: dropdown\n# I used a threshold value of 2.0, and got ~100 objects. \n# ```\n# \n# ```{warning}\n# When I ran this, I got an error that my \"array was not C-contiguous.\" I found the solution to this issue in [this stackoverflow post](https://stackoverflow.com/a/26782930). Loosely, `sep` uses C-bindings to actually run the heavy lifting code in C rather than Python (it's faster). This means input arrays must be arranged in physical memory the way C is used to. This particular array was not, but it is easy to order it this way.\n# ```\n\n# In[173]:\n\n\n# Your code\n\ndef run_sep(...):\n '''\n DOCSTRING HERE \n '''\n pass\n\n\n# Run your function and store the output in a variable called `objects`. You should now have an object array containing many detected sources.\n\n# In[ ]:\n\n\n# run func\n\n\n# The positions of the determined sources are stored in the output structured array and can be indexed with, e.g., `objects['x']` and `objects['y']`. Replot your image of the cutout, but now circle the positions of all your detected sources. Do they line up with actual point sources in the image?\n# \n# ```{hint}\n# :class: dropdown\n# Try using ax.plot, setting your symbol to 'o', your color to 'None', your marker edge color (mec) to some color, and the marker size (ms) to some largeish value, for a quick way to circle objects.\n# ```\n\n# In[ ]:\n\n\n# Your code\n\n\n# In[167]:\n\n\n# Here's my image, for comparison \n\n\n# It looks like we've done a pretty adequate job finding the sources in this field -- there'a a few that got missed, and a few we might want to remove, but overall, this is pretty solid. \n# \n# We need to start working with these objects we've found. While `sep` can perform aperture photometry itself (reading the docs, you can see it is simple to feed in the objects and a pixel radius), we're going to be a bit more careful about things. To better visualize and work with this data, I'd like it to be a `pandas` `DataFrame`. We're going to be using those a lot in this course. Converting a `numpy` structured array to a dataframe is simple: I provide the code below. Run it, and then simply type `df` in a new cell to see a nicely formatted pandas table of our objects.\n\n# In[171]:\n\n\nimport pandas as pd\ndf = pd.DataFrame(objects)\n\n\n# In[ ]:\n\n\ndf #run this\n\n\n# With `sep` providing the first pass, we can cull a few objets from our sample that very clearly are not star forming regions. Using your DataFrame, plot the flux of each detected object using the `flux` column. You should have at least a few that are huge outliers, with dramatically more flux the rest. \n\n# In[6]:\n\n\n# plot\n\n\n# Write a function called `remove_outliers` that reads in a dataframe and a flux-min and flux-max. It should filter the dataframe to only include fluxes between the input values, and return the new dataframe. Then use this function on your data, choosing an appropriate cutoff.\n\n# In[182]:\n\n\n# Your Code \n\ndef remove_outliers(...):\n '''\n '''\n pass\n\n\n# In[183]:\n\n\n# run the function\n\n\n# In[7]:\n\n\n# plot again\n\n\n# Re-plot the set of sources you have now, over the data.\n\n# In[8]:\n\n\n# plot\n\n\n# You should see that some of the circles which were over bright parts of the galaxy are no longer here. \n# ```{note}\n# You may find that there are some visible sources which, despite tinkering, don't get caught by `sep`. That's okay -- if we really wanted them, we could just go in and put down apertures by hand. Generally when performing a step like this in the field, we have a pre-determined set of points to use, because we have measured fluxes for them, and wish to flux calibrate our data. \n# ```\n# \n# ## Problem 4: Continuum Subtraction \n# \n# At this point, we have the tools necessary to make flux measurements in apertures (at least, via `sep` -- we will also learn how to do this with the `photutils` package). However, $R$ band photometry of HII regions is not exceedingly interesting. More interesting is the flux in $H\\alpha$, an emission line caused by Hydrogen recombination. This line (at 6563 Angstrom) is located *within* the $R$ band, and is imaged using a narrow filter compared ot $R$. \n# \n# The flux measured by an $H\\alpha$ filter contains both the flux from the emission line as well as the underlying continuum --- essentially, the starlight from the galaxy. If we can get a clean measure of the flux in $H\\alpha$ (sans this continuum), we can make a direct estimate of the star formation rate of the system. \n# \n# ### Problem 4.1\n# To do this, we need to access an $H\\alpha$ image, and then subtract off the continuum present (which we'll infer from our $R$ band image). Located in the lab directory is a file called `antenna_Haband.fits`. Use your fits loader function from above to read in this new image, create an equivalent sized and centered cutout to the $R$ band data, and plot it, with the same sources found in the $R$ band circled. \n\n# In[9]:\n\n\n# Your Code\n\n\n# There's a few interesting things to note right away here. Looking just north of the center of the image, there's now a large amount of flux in $H\\alpha$ coming from some blobs which do not appear in the $R$ band. This is likely due to the fact that by zero-ing in on the ionized gas, we can see the large envelopes of gas being lit up by the star formation in this region. \n# ```{note}\n# The active merger scenario between these two galaxies is triggering a lot of star formation.\n# ```\n# \n# ### Problem 4.2\n# \n# To get a better idea of how the $H\\alpha$ flux compares to the $R$ band distribution, use the `plt.contour()` tool to measure contours of $H\\alpha$, drawing them over the \n# $H\\alpha$ image and tweaking the levels until you think you are well tracing the distribution. Then, plot those contours over the $R$ band data instead. \n# \n# ```{hint}\n# It is often beneficial to use `np.logspace()` when defining contour levels, as it allows you to cover large dynamic range with fewer contours. You may also find it helpful to set your contour `alpha` to something < 1, to better see both the image underneath and the contours.\n# ```\n\n# In[10]:\n\n\n# Your Code\n\n\n# To help guide you, I've shown what I got for my plot below --- you need not emulate it exactly. The blue box shown in the image will be useful to you in the next part of the problem.\n\n# In[267]:\n\n\n# My solution\n\n\n# We can now see things a lot more clearly! It is obvious that the $H\\alpha$ contours trace some of the sources we were seeing in the $R$ band, but that the gas is more extended around these clusters of sources, as we might expect.\n# \n# ### Problem 4.3\n# We must now attempt a continuum subtraction of the data. We can't simply subtract the $R$ band from the $H\\alpha$ band, because the $R$ band filter is much wider, and thus for similar exposure times, collects many more photons than the narrower $H\\alpha$ filter. Ideally, one could use a set of foreground stars (which are pure continuum sources in both images) to measure fluxes in both, and find a scaling constant. Here, all of the sources we see in this image are most likely actually HII regions. This means if we use them to scale between our images, we will likely oversubtract true flux. \n# \n# Instead, what I'm going to do here (which may be slightly sketchy), is pick a \"blank\" region of continuum emission from the $R$ band which has no $H\\alpha$ contours, and assert that this patch must have the same flux in both images. In the picture above, I indicated a blue rectangular patch on the sky. This is what we'll be using to measure our continuum-to-narrowband ratio. \n# \n# To make this patch, we're going to use `SkyRectangularAperture`, from `photutils`. You can pip install `photutils` in your `a330` environment if you don't have it. Then do the following imports:\n\n# In[268]:\n\n\nfrom photutils.aperture import SkyRectangularAperture\nfrom photutils.aperture import aperture_photometry\n\n\n# As shown in [it's documentation](https://photutils.readthedocs.io/en/stable/api/photutils.aperture.SkyRectangularAperture.html), we need to feed in a `SkyCoord` position, as well as a width and a height. \n# I've provided the new coordinate to use below. \n# \n# Create a rectangle of your own, measuring $0.27''$ by $0.2''$. You can now use the `aperture_photometry()` function to measure the flux in your aperture, applied to a certain image. Using the [documentation](https://photutils.readthedocs.io/en/stable/api/photutils.aperture.aperture_photometry.html#photutils.aperture.aperture_photometry) as needed, find the flux in this box for both the $R$ band and $H\\alpha$ band data, and then determine the ratio between those values. Don't forget about the `wcs`!\n\n# In[11]:\n\n\npatch_cent = SkyCoord('12:01:53.7 -18:52:52',unit=(u.hourangle,u.deg))\n\n# Your code\n\n\n# We can now use this ratio to perform our subtraction. \n# \n# ### Problem 4.4\n# Now, fill in the function below, which should read in your rectangular patch, the $R$ band image, and the $H\\alpha$ image. Within the function, copy in the code that determines the ratio, and then use the ratio you found to scale your $R$ band image, then subtract it from the $H\\alpha$ image. The function should return this new image array.\n# \n# Plot up your continuum subtracted image using your `implot()` function, adding back in the apertures we found earlier and the contours we made from the full $H\\alpha$ image.\n\n# In[12]:\n\n\n# your code\ndef continuum_subtract(...):\n '''\n DOCSTRING HERE\n '''\n pass \n\n\n# What do you notice about the distribution of apertures with respect to the distribution of $H\\alpha$ gas? Is there a strong alignment of the $R$ band sources and the gas? What does this imply about most of the $R$ band sources?\n# \n# \n\n# *Answer here*\n\n# ### Problem 4.5 \n# \n# Lastly, let's load up the $B$ band image. As you probably know, the $B$ band traces bluer light, and thus will more preferentially see young, hot stars (whereas the $R$ band traces the main sequence and turn off stellar distribution). \n# \n# Load up the `antenna_Bband.fits` image, make a cutout, and plot it below. Use your `load_fits()` function and your `implot()` function. Make a new set of countours from your *continuum subtracted* $H\\alpha$ data, and overplot that onto the $B$ band data. What do you see?\n# \n\n# In[13]:\n\n\n# Your code\n\n\n# In my own image, there are some clusters of $B$-band flux that align well with the $H\\alpha$ contours, and some $B$ band sources out on their own. It is unsurprising that there is a correspondance between them; excess in $B$ light implies the prescence of UV radiation as well, from young O/B stars. It is this radiation responsible for ionizing the gas that is shining in $H\\alpha$, so the $H\\alpha$-emitting gas should be loosely clustered around sources bright in the $B$ band (the experiment would be even cleaner if we used, say, *GALEX* FUV data). \n\n# ### Bonus Question (up to 3 points)\n# \n# If you want to take your analysis farther, try measuring some fluxes off of your continuum subtracted $H\\alpha$ data, placing several manual apertures down over the regions of highest $H\\alpha$ concentration (which also align with $B$ band concentrations). \n# \n# The measures you get from this will be in counts on the detector. We need to convert these counts into flux units (e.g., erg s$^{-1}$ cm$^{-2}$). To do this, \n# - pull the 'PHOTFLAM' keyword from the header of your $H\\alpha$ data\n# - also pull the 'EXPTIME' value from the header. \n# \n# Start by taking your fluxes in counts, multiplying by the `PHOTFLAM` value, and dividing by the `EXPTIME` value. This puts you in erg s$^{-1}$ cm$^{-2}$ *per Angstrom*. Thus, what we have is technically a *flux density*. To convert to a true flux, we'll simply integrate over the bandpass... but for this example, let's assume a constant flux across the bandpass, which for the ACS 658N filter ($H\\alpha$), is 136.27 angstroms. \n# \n# Once you have fluxes, use the distance to NGC 4038/9 to determine the luminosity in erg/s of your collective set of sources, and then use the $SFR(H\\alpha)$ calibration of [Kennicut & Bell](https://iopscience.iop.org/article/10.1086/319025/fulltext/52481.text.html) to convert to an SFR. How does your answer compare to, e.g., \n# - The SFR of the Milky Way?\n# - The SFR of the Orion Nebula?\n# - The SFR of the Tarantula Nebula?\n", "meta": {"hexsha": "e60ad9cdb2a8f4c949b7f248f3cca0eb46b69567", "size": 34128, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/Lab2/Lab2.py", "max_stars_repo_name": "Astro-330/Astro-330.github.io", "max_stars_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-28T23:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:35:17.000Z", "max_issues_repo_path": "_build/jupyter_execute/Lab2/Lab2.py", "max_issues_repo_name": "mgebran/Astro-330.github.io", "max_issues_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/Lab2/Lab2.py", "max_forks_repo_name": "mgebran/Astro-330.github.io", "max_forks_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-18T00:53:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:53:12.000Z", "avg_line_length": 54.3439490446, "max_line_length": 725, "alphanum_fraction": 0.7333567745, "include": true, "reason": "import numpy,import astropy,from astropy", "num_tokens": 8541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.18242552602881165, "lm_q1q2_score": 0.09050017780088007}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# \n# # Tutorial 1: \"What\" models\n# __Content creators:__ Matt Laporte, Byron Galbraith, Konrad Kording\n# \n# __Content reviewers:__ Dalin Guo, Aishwarya Balwani, Madineh Sarvestani, Maryam Vaziri-Pashkam, Michael Waskom\n# \n# We would like to acknowledge [Steinmetz _et al._ (2019)](https://www.nature.com/articles/s41586-019-1787-x) for sharing their data, a subset of which is used here.\n# \n\n# ___\n# # Tutorial Objectives\n# This is tutorial 1 of a 3-part series on different flavors of models used to understand neural data. In this tutorial we will explore 'What' models, used to describe the data. To understand what our data looks like, we will visualize it in different ways. Then we will compare it to simple mathematical models. Specifically, we will:\n# \n# - Load a dataset with spiking activity from hundreds of neurons and understand how it is organized\n# - Make plots to visualize characteristics of the spiking activity across the population\n# - Compute the distribution of \"inter-spike intervals\" (ISIs) for a single neuron\n# - Consider several formal models of this distribution's shape and fit them to the data \"by hand\"\n\n# In[ ]:\n\n\n#@title Video 1: \"What\" Models\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='KgqR_jbjMQg', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n\n# # Setup\n# \n# \n\n# Python requires you to explictly \"import\" libraries before their functions are available to use. We will always specify our imports at the beginning of each notebook or script.\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Tutorial notebooks typically begin with several set-up steps that are hidden from view by default.\n# \n# **Important:** Even though the code is hidden, you still need to run it so that the rest of the notebook can work properly. Step through each cell, either by pressing the play button in the upper-left-hand corner or with a keyboard shortcut (`Cmd-Return` on a Mac, `Ctrl-Enter` otherwise). A number will appear inside the brackets (e.g. `[3]`) to tell you that the cell was executed and what order that happened in.\n# \n# If you are curious to see what is going on inside each cell, you can double click to expand. Once expanded, double-click the white space to the right of the editor to collapse again.\n\n# In[ ]:\n\n\n#@title Figure Settings\nimport ipywidgets as widgets #interactive display\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().run_line_magic('config', \"InlineBackend.figure_format = 'retina'\")\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")\n\n\n# In[ ]:\n\n\n#@title Helper functions\n\n#@markdown Most of the tutorials make use of helper functions\n#@markdown to simplify the code that you need to write. They are defined here.\n\n# Please don't edit these, or worry about understanding them now!\n\ndef restrict_spike_times(spike_times, interval):\n \"\"\"Given a spike_time dataset, restrict to spikes within given interval.\n\n Args:\n spike_times (sequence of np.ndarray): List or array of arrays,\n each inner array has spike times for a single neuron.\n interval (tuple): Min, max time values; keep min <= t < max.\n\n Returns:\n np.ndarray: like `spike_times`, but only within `interval`\n \"\"\"\n interval_spike_times = []\n for spikes in spike_times:\n interval_mask = (spikes >= interval[0]) & (spikes < interval[1])\n interval_spike_times.append(spikes[interval_mask])\n return np.array(interval_spike_times, object)\n\n\n# In[ ]:\n\n\n#@title Data retrieval\n#@markdown This cell downloads the example dataset that we will use in this tutorial.\nimport io\nimport requests\nr = requests.get('https://osf.io/sy5xt/download')\nif r.status_code != 200:\n print('Failed to download data')\nelse:\n spike_times = np.load(io.BytesIO(r.content), allow_pickle=True)['spike_times']\n\n\n# ---\n# \n# # Section 1: Exploring the Steinmetz dataset\n# \n# In this tutorial we will explore the structure of a neuroscience dataset. \n# \n# We consider a subset of data from a study of [Steinmetz _et al._ (2019)](https://www.nature.com/articles/s41586-019-1787-x). In this study, Neuropixels probes were implanted in the brains of mice. Electrical potentials were measured by hundreds of electrodes along the length of each probe. Each electrode's measurements captured local variations in the electric field due to nearby spiking neurons. A spike sorting algorithm was used to infer spike times and cluster spikes according to common origin: a single cluster of sorted spikes is causally attributed to a single neuron.\n# \n# In particular, a single recording session of spike times and neuron assignments was loaded and assigned to `spike_times` in the preceding setup. \n# \n# Typically a dataset comes with some information about its structure. However, this information may be incomplete. You might also apply some transformations or \"pre-processing\" to create a working representation of the data of interest, which might go partly undocumented depending on the circumstances. In any case it is important to be able to use the available tools to investigate unfamiliar aspects of a data structure. \n# \n# Let's see what our data looks like...\n\n# ## Section 1.1: Warming up with `spike_times`\n\n# What is the Python type of our variable?\n\n# In[ ]:\n\n\ntype(spike_times)\n\n\n# You should see `numpy.ndarray`, which means that it's a normal NumPy array.\n# \n# If you see an error message, it probably means that you did not execute the set-up cells at the top of the notebook. So go ahead and make sure to do that.\n# \n# Once everything is running properly, we can ask the next question about the dataset: what's its shape?\n\n# In[ ]:\n\n\nspike_times.shape\n\n\n# There are 734 entries in one dimension, and no other dimensions. What is the Python type of the first entry, and what is *its* shape?\n\n# In[ ]:\n\n\nidx = 0\nprint(\n type(spike_times[idx]),\n spike_times[idx].shape,\n sep=\"\\n\",\n)\n\n\n# It's also a NumPy array with a 1D shape! Why didn't this show up as a second dimension in the shape of `spike_times`? That is, why not `spike_times.shape == (734, 826)`?\n# \n# To investigate, let's check another entry.\n\n# In[ ]:\n\n\nidx = 321\nprint(\n type(spike_times[idx]),\n spike_times[idx].shape,\n sep=\"\\n\",\n)\n\n\n# It's also a 1D NumPy array, but it has a different shape. Checking the NumPy types of the values in these arrays, and their first few elements, we see they are composed of floating point numbers (not another level of `np.ndarray`):\n\n# In[ ]:\n\n\ni_neurons = [0, 321]\ni_print = slice(0, 5)\n\nfor i in i_neurons:\n print(\n \"Neuron {}:\".format(i),\n spike_times[i].dtype,\n spike_times[i][i_print],\n \"\\n\",\n sep=\"\\n\"\n )\n\n\n# Note that this time we've checked the NumPy `dtype` rather than the Python variable type. These two arrays contain floating point numbers (\"floats\") with 32 bits of precision.\n# \n# The basic picture is coming together:\n# - `spike_times` is 1D, its entries are NumPy arrays, and its length is the number of neurons (734): by indexing it, we select a subset of neurons. \n# - An array in `spike_times` is also 1D and corresponds to a single neuron; its entries are floating point numbers, and its length is the number of spikes attributed to that neuron. By indexing it, we select a subset of spike times for that neuron. \n# \n# Visually, you can think of the data structure as looking something like this:\n# \n# ```\n# | . . . . . |\n# | . . . . . . . . |\n# | . . . |\n# | . . . . . . . |\n# ```\n# \n# Before moving on, we'll calculate and store the number of neurons in the dataset and the number of spikes per neuron:\n\n# In[ ]:\n\n\nn_neurons = len(spike_times)\ntotal_spikes_per_neuron = [len(spike_times_i) for spike_times_i in spike_times]\n\nprint(f\"Number of neurons: {n_neurons}\")\nprint(f\"Number of spikes for first five neurons: {total_spikes_per_neuron[:5]}\")\n\n\n# In[ ]:\n\n\n#@title Video 2: Exploring the dataset\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='oHwYWUI_o1U', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n\n# ## Section 1.2: Getting warmer: counting and plotting total spike counts\n# \n# As we've seen, the number of spikes over the entire recording is variable between neurons. More generally, some neurons tend to spike more than others in a given period. Lets explore what the distribution of spiking looks like across all the neurons in the dataset.\n\n# Are most neurons \"loud\" or \"quiet\", compared to the average? To see, we'll define bins of constant width in terms of total spikes and count the neurons that fall in each bin. This is known as a \"histogram\".\n# \n# You can plot a histogram with the matplotlib function `plt.hist`. If you just need to compute it, you can use the numpy function `np.histogram` instead.\n\n# In[ ]:\n\n\nplt.hist(total_spikes_per_neuron, bins=50, histtype=\"stepfilled\")\nplt.xlabel(\"Total spikes per neuron\")\nplt.ylabel(\"Number of neurons\");\n\n\n# Let's see what percentage of neurons have a below-average spike count:\n\n# In[ ]:\n\n\nmean_spike_count = np.mean(total_spikes_per_neuron)\nfrac_below_mean = (total_spikes_per_neuron < mean_spike_count).mean()\nprint(f\"{frac_below_mean:2.1%} of neurons are below the mean\")\n\n\n# We can also see this by adding the average spike count to the histogram plot:\n\n# In[ ]:\n\n\nplt.hist(total_spikes_per_neuron, bins=50, histtype=\"stepfilled\")\nplt.xlabel(\"Total spikes per neuron\")\nplt.ylabel(\"Number of neurons\")\nplt.axvline(mean_spike_count, color=\"orange\", label=\"Mean neuron\")\nplt.legend();\n\n\n# This shows that the majority of neurons are relatively \"quiet\" compared to the mean, while a small number of neurons are exceptionally \"loud\": they must have spiked more often to reach a large count.\n# \n# ### Exercise 1: Comparing mean and median neurons\n# \n# If the mean neuron is more active than 68% of the population, what does that imply about the relationship between the mean neuron and the median neuron?\n# \n# *Exercise objective:* Reproduce the plot above, but add the median neuron.\n# \n\n# In[ ]:\n\n\n# To complete the exercise, fill in the missing parts (...) and uncomment the code\n\nmedian_spike_count = ... # Hint: Try the function np.median\n\n# plt.hist(..., bins=50, histtype=\"stepfilled\")\n# plt.axvline(..., color=\"limegreen\", label=\"Median neuron\")\n# plt.axvline(mean_spike_count, color=\"orange\", label=\"Mean neuron\")\n# plt.xlabel(\"Total spikes per neuron\")\n# plt.ylabel(\"Number of neurons\")\n# plt.legend()\n\n\n# [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D1_ModelTypes/solutions/W1D1_Tutorial1_Solution_b3411d5d.py)\n# \n# *Example output:*\n# \n# Solution hint\n# \n# \n\n# \n# *Bonus:* The median is the 50th percentile. What about other percentiles? Can you show the interquartile range on the histogram?\n\n# ---\n# \n# # Section 2: Visualizing neuronal spiking activity\n\n# ## Section 2.1: Getting a subset of the data\n# \n# Now we'll visualize trains of spikes. Because the recordings are long, we will first define a short time interval and restrict the visualization to only the spikes in this interval. We defined a utility function, `restrict_spike_times`, to do this for you. If you call `help()` on the function, it will tell you a little bit about itself:\n\n# In[ ]:\n\n\nhelp(restrict_spike_times)\n\n\n# In[ ]:\n\n\nt_interval = (5, 15) # units are seconds after start of recording\ninterval_spike_times = restrict_spike_times(spike_times, t_interval)\n\n\n# Is this a representative interval? What fraction of the total spikes fall in this interval?\n\n# In[ ]:\n\n\noriginal_counts = sum([len(spikes) for spikes in spike_times])\ninterval_counts = sum([len(spikes) for spikes in interval_spike_times])\nfrac_interval_spikes = interval_counts / original_counts\nprint(f\"{frac_interval_spikes:.2%} of the total spikes are in the interval\")\n\n\n# How does this compare to the ratio between the interval duration and the experiment duration? (What fraction of the total time is in this interval?)\n# \n# We can approximate the experiment duration by taking the minimum and maximum spike time in the whole dataset. To do that, we \"concatenate\" all of the neurons into one array and then use `np.ptp` (\"peak-to-peak\") to get the difference between the maximum and minimum value:\n\n# In[ ]:\n\n\nspike_times_flat = np.concatenate(spike_times)\nexperiment_duration = np.ptp(spike_times_flat)\ninterval_duration = t_interval[1] - t_interval[0]\n\nfrac_interval_time = interval_duration / experiment_duration\nprint(f\"{frac_interval_time:.2%} of the total time is in the interval\")\n\n\n# These two values—the fraction of total spikes and the fraction of total time—are similar. This suggests the average spike rate of the neuronal population is not very different in this interval compared to the entire recording.\n# \n# ## Section 2.2: Plotting spike trains and rasters\n# \n# Now that we have a representative subset, we're ready to plot the spikes, using the matplotlib `plt.eventplot` function. Let's look at a single neuron first:\n\n# In[ ]:\n\n\nneuron_idx = 1\nplt.eventplot(interval_spike_times[neuron_idx], color=\".2\")\nplt.xlabel(\"Time (s)\")\nplt.yticks([]);\n\n\n# We can also plot multiple neurons. Here are three:\n\n# In[ ]:\n\n\nneuron_idx = [1, 11, 51]\nplt.eventplot(interval_spike_times[neuron_idx], color=\".2\")\nplt.xlabel(\"Time (s)\")\nplt.yticks([]);\n\n\n# This makes a \"raster\" plot, where the spikes from each neuron appear in a different row.\n# \n# Plotting a large number of neurons can give you a sense for the characteristics in the population. Let's show every 5th neuron that was recorded:\n\n# In[ ]:\n\n\nneuron_idx = np.arange(0, len(spike_times), 5)\nplt.eventplot(interval_spike_times[neuron_idx], color=\".2\")\nplt.xlabel(\"Time (s)\")\nplt.yticks([]);\n\n\n# *Question*: How does the information in this plot relate to the histogram of total spike counts that you saw above?\n\n# In[ ]:\n\n\n#@title Video 3: Visualizing activity\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='QGA5FCW7kkA', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n\n# ---\n# \n# # Section 3: Inter-spike intervals and their distributions\n\n# Given the ordered arrays of spike times for each neuron in `spike_times`, which we've just visualized, what can we ask next? \n# \n# Scientific questions are informed by existing models. So, what knowledge do we already have that can inform questions about this data?\n# \n# We know that there are physical constraints on neuron spiking. Spiking costs energy, which the neuron's cellular machinery can only obtain at a finite rate. Therefore neurons should have a refractory period: they can only fire as quickly as their metabolic processes can support, and there is a minimum delay between consecutive spikes of the same neuron.\n# \n# More generally, we can ask \"how long does a neuron wait to spike again?\" or \"what is the longest a neuron will wait?\" Can we transform spike times into something else, to address questions like these more directly?\n# \n# We can consider the inter-spike times (or interspike intervals: ISIs). These are simply the time differences between consecutive spikes of the same neuron.\n# \n# ### Exercise 2: Plot the distribution of ISIs for a single neuron\n# \n# *Exercise objective:* make a histogram, like we did for spike counts, to show the distribution of ISIs for one of the neurons in the dataset.\n# \n# Do this in three steps:\n# \n# 1. Extract the spike times for one of the neurons\n# 2. Compute the ISIs (the amount of time between spikes, or equivalently, the difference between adjacent spike times)\n# 3. Plot a histogram with the array of individual ISIs\n\n# In[ ]:\n\n\ndef compute_single_neuron_isis(spike_times, neuron_idx):\n \"\"\"Compute a vector of ISIs for a single neuron given spike times.\n\n Args:\n spike_times (list of 1D arrays): Spike time dataset, with the first\n dimension corresponding to different neurons.\n neuron_idx (int): Index of the unit to compute ISIs for.\n\n Returns:\n isis (1D array): Duration of time between each spike from one neuron.\n \"\"\"\n #############################################################################\n # Students: Fill in missing code (...) and comment or remove the next line\n raise NotImplementedError(\"Exercise: compute single neuron ISIs\")\n #############################################################################\n\n # Extract the spike times for the specified neuron\n single_neuron_spikes = ...\n\n # Compute the ISIs for this set of spikes\n # Hint: the function np.diff computes discrete differences along an array\n isis = ...\n\n return isis\n\n# Uncomment the following lines when you are ready to test your function\n# single_neuron_isis = compute_single_neuron_isis(spike_times, neuron_idx=283)\n# plt.hist(single_neuron_isis, bins=50, histtype=\"stepfilled\")\n# plt.axvline(single_neuron_isis.mean(), color=\"orange\", label=\"Mean ISI\")\n# plt.xlabel(\"ISI duration (s)\")\n# plt.ylabel(\"Number of spikes\")\n# plt.legend()\n\n\n# [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D1_ModelTypes/solutions/W1D1_Tutorial1_Solution_4792dbfa.py)\n# \n# *Example output:*\n# \n# Solution hint\n# \n# \n\n# ---\n# \n# In general, the shorter ISIs are predominant, with counts decreasing rapidly (and smoothly, more or less) with increasing ISI. However, counts also rapidly decrease to zero with _decreasing_ ISI, below the maximum of the distribution (8-11 ms). The absence of these very low ISIs agrees with the refractory period hypothesis: the neuron cannot fire quickly enough to populate this region of the ISI distribution.\n# \n# Check the distributions of some other neurons. To resolve various features of the distributions, you might need to play with the value of `n_bins`. Using too few bins might smooth over interesting details, but if you use too many bins, the random variability will start to dominate.\n# \n# You might also want to restrict the range to see the shape of the distribution when focusing on relatively short or long ISIs. *Hint:* `plt.hist` takes a `range` argument \n\n# ---\n# \n# # Section 4: What is the functional form of an ISI distribution?\n\n# In[ ]:\n\n\n#@title Video 4: ISI distribution\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='DHhM80MOTe8', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n\n# The ISI histograms seem to follow continuous, monotonically decreasing functions above their maxima. The function is clearly non-linear. Could it belong to a single family of functions?\n# \n# To motivate the idea of using a mathematical function to explain physiological phenomena, let's define a few different function forms that we might expect the relationship to follow: exponential, inverse, and linear.\n\n# In[ ]:\n\n\ndef exponential(xs, scale, rate, x0):\n \"\"\"A simple parametrized exponential function, applied element-wise.\n\n Args:\n xs (np.ndarray or float): Input(s) to the function.\n scale (float): Linear scaling factor.\n rate (float): Exponential growth (positive) or decay (negative) rate.\n x0 (float): Horizontal offset.\n\n \"\"\"\n ys = scale * np.exp(rate * (xs - x0))\n return ys\n\ndef inverse(xs, scale, x0):\n \"\"\"A simple parametrized inverse function (`1/x`), applied element-wise.\n\n Args:\n xs (np.ndarray or float): Input(s) to the function.\n scale (float): Linear scaling factor.\n x0 (float): Horizontal offset.\n\n \"\"\"\n ys = scale / (xs - x0)\n return ys\n\ndef linear(xs, slope, y0):\n \"\"\"A simple linear function, applied element-wise.\n\n Args:\n xs (np.ndarray or float): Input(s) to the function.\n slope (float): Slope of the line.\n y0 (float): y-intercept of the line.\n\n \"\"\"\n ys = slope * xs + y0\n return ys\n\n\n# ### Interactive Demo: ISI functions explorer\n# \n# Here is an interactive demo where you can vary the parameters of these functions and see how well the resulting outputs correspond to the data. Adjust the parameters by moving the sliders and see how close you can get the lines to follow the falling curve of the histogram. This will give you a taste of what you're trying to do when you *fit a model* to data.\n# \n# \"Interactive demo\" cells have hidden code that defines an interface where you can play with the parameters of some function using sliders. You don't need to worry about how the code works – but you do need to **run the cell** to enable the sliders.\n# \n\n# In[ ]:\n\n\n#@title\n\n#@markdown Be sure to run this cell to enable the demo\n# Don't worry about understanding this code! It's to setup an interactive plot.\nsingle_neuron_idx = 283\nsingle_neuron_spikes = spike_times[single_neuron_idx]\nsingle_neuron_isis = np.diff(single_neuron_spikes)\n\ncounts, edges = np.histogram(\n single_neuron_isis,\n bins=50,\n range=(0, single_neuron_isis.max())\n)\n\nfunctions = dict(\n exponential=exponential,\n inverse=inverse,\n linear=linear,\n)\n\ncolors = dict(\n exponential=\"C1\",\n inverse=\"C2\",\n linear=\"C4\",\n)\n\n@widgets.interact(\n exp_scale=widgets.FloatSlider(1000, min=0, max=20000, step=250),\n exp_rate=widgets.FloatSlider(-10, min=-200, max=50, step=1),\n exp_x0=widgets.FloatSlider(0.1, min=-0.5, max=0.5, step=0.005),\n inv_scale=widgets.FloatSlider(1000, min=0, max=3e2, step=10),\n inv_x0=widgets.FloatSlider(0, min=-0.2, max=0.2, step=0.01),\n lin_slope=widgets.FloatSlider(-1e5, min=-6e5, max=1e5, step=10000),\n lin_y0=widgets.FloatSlider(10000, min=0, max=4e4, step=1000),\n)\ndef fit_plot(\n exp_scale=1000, exp_rate=-10, exp_x0=0.1,\n inv_scale=1000, inv_x0=0,\n lin_slope=-1e5, lin_y0=2000,\n):\n \"\"\"Helper function for plotting function fits with interactive sliders.\"\"\"\n func_params = dict(\n exponential=(exp_scale, exp_rate, exp_x0),\n inverse=(inv_scale, inv_x0),\n linear=(lin_slope, lin_y0),\n )\n f, ax = plt.subplots()\n ax.fill_between(edges[:-1], counts, step=\"post\", alpha=.5)\n xs = np.linspace(1e-10, edges.max())\n for name, function in functions.items():\n ys = function(xs, *func_params[name])\n ax.plot(xs, ys, lw=3, color=colors[name], label=name);\n ax.set(\n xlim=(edges.min(), edges.max()),\n ylim=(0, counts.max() * 1.1),\n xlabel=\"ISI (s)\",\n ylabel=\"Number of spikes\",\n )\n ax.legend()\n\n\n# In[ ]:\n\n\n#@title Video 5: Fitting models by hand\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='uW2HDk_4-wk', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo\n\n\n# # Summary\n# \n# In this tutorial, we loaded some neural data and poked at it to understand how the dataset is organized. Then we made some basic plots to visualize (1) the average level of activity across the population and (2) the distribution of ISIs for an individual neuron. In the very last bit, we started to think about using mathematical formalisms to understand or explain some physiological phenomenon. All of this only allowed us to understand \"What\" the data looks like.\n# \n# This is the first step towards developing models that can tell us something about the brain. That's what we'll focus on in the next two tutorials.\n", "meta": {"hexsha": "724dcc6239721bf5d0a4f1861585733cf8ccfc19", "size": 23521, "ext": "py", "lang": "Python", "max_stars_repo_path": "prototype/_build/jupyter_execute/W1D1_Tutorial1.py", "max_stars_repo_name": "ebatty/prototype", "max_stars_repo_head_hexsha": "9789b6109d93d6bb166f8aea81364d15f5315455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/_build/jupyter_execute/W1D1_Tutorial1.py", "max_issues_repo_name": "ebatty/prototype", "max_issues_repo_head_hexsha": "9789b6109d93d6bb166f8aea81364d15f5315455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prototype/_build/jupyter_execute/W1D1_Tutorial1.py", "max_forks_repo_name": "ebatty/prototype", "max_forks_repo_head_hexsha": "9789b6109d93d6bb166f8aea81364d15f5315455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1834415584, "max_line_length": 581, "alphanum_fraction": 0.7365333107, "include": true, "reason": "import numpy", "num_tokens": 5869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.21733752611649484, "lm_q1q2_score": 0.09017308873405881}} {"text": "# python src/chapter7/chapter7note.py\n# python3 src/chapter7/chapter7note.py\n'''\nClass Chapter7_1\n\nClass Chapter7_2\n\nClass Chapter7_3\n\nClass Chapter7_4\n'''\n\nfrom __future__ import division, absolute_import, print_function\n\nimport sys as _sys\nimport math as _math\nimport random as _random\nimport time as _time\nfrom random import randint as _randint\nfrom copy import copy as _copy, deepcopy as _deepcopy\nfrom numpy import arange as _arange\n\nif __name__ == '__main__':\n import quicksort\n import stooge\nelse:\n from . import quicksort\n from . import stooge\n\nclass Chapter7_1:\n def note(self):\n '''\n Summary\n ====\n Print chapter7.1 note\n\n Example\n ====\n >>> Chapter7_1().note()\n '''\n print('chapter7.1 note as follow')\n print('第7章 快速排序')\n print('快速排序是一种排序算法,对包含n个数的输入数组进行排序,最坏情况的运行时间为Θ(n^2)')\n print('虽然这个最坏情况运行时间比较差,但是快速排序通常是用于排序最佳的实用选择,这是因为其平均性能相当好')\n print('快速排序期望的运行时间为Θ(nlgn),且Θ(nlgn)记号中隐含的常数因子很小')\n print('快速排序能够进行就地排序,在虚存坏境中也能很好地工作')\n print('7.1 快速排序的描述')\n print('像合并排序一样,快速排序也是基于分治模式的')\n print(' 1.分解:数组A[p..r]被划分成两个(可能为空的)子数组A[p..q-1]和A[q+1..r]')\n print(' 使得A[p..q-1]中的每个元素都小于等于A(q),而且,小于等于A[q+1..r]')\n print(' 下标q也在这个划分过程中进行计算')\n print(' 2.解决:通过递归调用快速排序,对子数组A[p..q-1]和A[q+1..r]排序')\n print(' 3.合并:因为这两个子数组是就地排序的(不开辟新的数组),将他们合并不需要任何操作,整个数组A[p..r]已经排好序')\n print('子数组快速排序伪代码')\n print('QUICKSORT(A,p,r)')\n print(' 1. if q < r')\n print(' 2. q <- PARTITION(A,p,r)')\n print(' 3. QUICKSORT(A,p,q-1)')\n print(' 3. QUICKSORT(A,q+1,r)')\n print('排序完整的数组A,调用QUICKSORT(A,0,len(A))即可')\n print('快速排序算法的关键是PARTITION过程,它对子数组A[q..r]进行就地重排')\n print('PARTITION(A,p,r)')\n print(' 1. x <- A[r]')\n print(' 2. i <- p-1')\n print(' 3. for j <- p to r-1')\n print(' 4. if A[j] <= x')\n print(' 5. i <- i+1')\n print(' 6. exchange A[i] <-> A[j]')\n print(' 7. exchange A[i+1] <-> A[r]')\n print(' 8. return i + 1')\n A = [8, 9, 6, 7, 4, 5, 2, 3, 1]\n print('数组A', _deepcopy(A), '的快速排序过程为:', \n quicksort.quicksort(A))\n A = [13, 19, 9, 5, 12, 8, 7, 4, 11, 2, 6, 21]\n print('练习7.1-1 数组A', _deepcopy(A), \n '的一步partition过程得到middle索引为:', \n quicksort.partition(A, 0, len(A) - 1))\n A = [11, 11, 11, 11, 11]\n print('练习7.1-2 数组A', _deepcopy(A), \n '的一步partition过程得到middle索引为:', \n quicksort.partition(A, 0, len(A) - 1))\n print('练习7.1-3 就一个长度为n的for循环,且一定会执行,所以时间复杂度为Θ(n),然后用确界的夹逼定义证明')\n print('练习7.1-4 不等号方向改变即可')\n # python src/chapter7/chapter7note.py\n # python3 src/chapter7/chapter7note.py\n\nclass Chapter7_2:\n def note(self):\n '''\n Summary\n ====\n Print chapter7.2 note\n\n Example\n ====\n >>> Chapter7_2().note()\n '''\n print('chapter7.2 note as follow')\n print('7.2 快速排序的性能')\n print('快速排序的运行时间与划分是否对称有关,而后者由与选择了哪个元素来进行划分有关')\n print('如果划分是对称的,那么快速排序算法从渐进上与合并算法一样快,否则就和插入排序一样慢')\n print('快速情况的最坏情况划分行为发生在划分过程产生的两个区域分别包含n-1个元素和1个0元素的时候')\n print('假设每次划分都出现了这种不对称划分,划分的时间代价为Θ(n),故算法的运行时间可以递归地写为')\n print('T(n)=T(n-1)+T(0)+Θ(n),递归式的解为T(n)=Θ(n^2)')\n print('快速排序的最坏情况并不比插入排序的最坏情况更好')\n print('另外,当一个已经排序好时,快速排序运行时间Θ(n^2),插入排序运行时间Θ(n)')\n print('快速排序最佳情况是是其中一个字问题的大小为[n/2],另一个问题的大小为[n/2]-1')\n print('在这种情况下,快速排序的运行时间要快的多,T(n)<=T(n/2)+Θ(n)')\n print('根据主定理,以上递归式的解为O(nlgn)')\n print('平衡的划分')\n print('快速排序的平均运行时间与其最佳运行时间很接近')\n print('练习7.2-1 T(1)=T(0)+Θ(n),T(2)=T(1)+Θ(n),T(n)=T(n-1)+Θ(n)')\n print(' 从第一个式子加到第n个式子,T(n)=Θ(n^2)')\n print('练习7.2-2 数组A中的每个元素都相同时,也属于元素已经排序好的情况,',\n '所以调用PARTITION子程序每次都会得到最差的分配,所以最坏情况运行时间为T(n)=Θ(n^2)')\n print('练习7.2-3 根据书中的描写降序排序好的元素,会导致每次分配都得到最差的情况,又递归式和主定理得T(n)=Θ(n^2)')\n print('练习7.2-4 对已经排序好的支票对于快速排序来说属于最差情况输入,运行时间为O(n^2)')\n print(' 而对于插入排序来说却是最优输入,运行时间为O(n)')\n print('练习7.2-5 [滑稽]但是平均的运行时间仍然为O(nlgn)')\n print('练习7.2-6 略')\n # python src/chapter7/chapter7note.py\n # python3 src/chapter7/chapter7note.py\n\nclass Chapter7_3:\n '''\n chapter7.3 content : note, function, etc..\n\n See Also\n ========\n Chapter7_1 Chapter7_2 Chapter7_4\n '''\n def note(self):\n '''\n Summary\n ====\n Print chapter7.3 note\n\n Example\n ====\n >>> Chapter7_3().note()\n '''\n print('chapter7.3 note as follow')\n print('7.3 快速排序的随机化版本')\n print('在探讨快速排序的平均性态过程中,假定输入数据的所有排列都是等可能的')\n print('但在工程中,这个假设就不会总是成立')\n print('虽然第五章介绍过一些随机算法,但是如果采用一种不同的,称为随机取样的随机化技术的话,可以使分析更加简单')\n print('在这种方法中,不是时钟采用A[r]作为主元,而是从子数组A[p..r]中随机选择一个元素')\n print('然后将这个随机元素与A[r]交换作为主元')\n print('因为主元元素是随机选择的,在期望的平均情况下,对输入数组的划分比较对称')\n A = [8, 7, 6, 5, 4, 3, 2, 1] \n print('数组[8, 7, 6, 5, 4, 3, 2, 1]的随机化快速排序:', \n quicksort.randomized_quicksort(A))\n print('练习7.3-1:大部分时候输入的待排序序列我们是不知道的,而对于快速排序来讲,一个平均的输入才能反映其算法性能,最坏情况出现的概率比较小')\n print('练习7.3-2:最佳情况调用Θ(n)次,最坏情况调用Θ(n^2)次')\n # python src/chapter7/chapter7note.py\n # python3 src/chapter7/chapter7note.py\n\nclass Chapter7_4:\n '''\n chapter7.4 content : note, function, etc..\n\n See Also\n ========\n Chapter7_1 Chapter7_2 Chapter7_3\n '''\n def note(self):\n '''\n Summary\n ====\n Print chapter7.4 note\n\n Example\n ====\n ``Chapter7_4().note()``\n '''\n print('chapter7.4 note as follow')\n print('7.4 快速排序分析')\n print('7.4.1 最坏情况分析')\n print('如果快速排序中每一层递归上所做的都是最坏情况划分,则运行时间为Θ(n^2)')\n print('7.4.2 期望的运行时间')\n print('RANDOMZIED-QUICKSORT的平均情况运行时间为O(nlgn)')\n print('运行时间和比较')\n print('quicksort的运行时间是由花在过程PARTITION上的时间所决定的。')\n print('每当PARTITION过程被调用时,就要选出一个主元元素,后续对QUICKSORT和PARTITION的各次递归调用中,都不会包含该元素')\n print('于是,在快速排序算法的整个执行过程中,最多只可能调用PARTITION过程n次,调用一次PARTITION的时间为O(1)在加上一段时间')\n print('引理7.1 设当QUICKSORT在一个包含n个元素的数组上运行时,PARTITION在第四行所做的比较次数为X,那么QUICKSORT的运行时间为O(n+X)')\n print('练习7.4-1 递归式子T(n)=max(T(q)+T(n-q-1)+Θ(n))中,T(n)=Ω(n^2)')\n print('练习7.4-2 快速排序的最佳情况运行时间为Ω(nlgn)')\n print('练习7.4-3 略')\n print('练习7.4-4 RANDOMIZED-QUICKSORT算法期望的运行时间为Ω(nlgn)')\n print('练习7.4-5 对插入排序来说,当其输入已经是几乎排好序的,运行时间是很快的')\n print(' 当在一个长度小于k的子数组上调用快速排序时,让它不做任何排序就返回。', \n '当顶层的快速排序调用返回后,对整个数组运行插入排序来完成排序过程。', \n '这一排序算法的期望运行时间为O(nk+nlg(n/k))')\n print('练习7.4-6 PARTITION过程做这样的修改,从数组A中随机地选出三个元素,并围绕这三个数的中数(即这三个元素的中间值)进行划分', \n '求出以a的函数形式表示的、最坏情况中a:(1-a)划分的近似概率')\n A = [13, 19, 9, 5, 12, 8, 7, 4, 11, 2, 6, 21]\n print('思考题7-1:数组A', _deepcopy(A), '的HOARE-PARTITION算法过程为:', \n quicksort.hoare_partition(A, 0, len(A) - 1))\n print('数组A', _deepcopy(A), '的HOARE-QUICKSORT的过程为:', quicksort.hoare_quicksort(A))\n print('思考题7-2:对快速排序算法的另一种分析')\n print(' 着重关注每一次QUICKSORT递归调用的期望运行时间,而不是执行的比较次数')\n print(' a) 给定一个大小为n的数组,任何特定元素被选为主元的概率为1/n')\n print('思考题7-3 Stooge排序')\n A = [8, 7, 56, 43, 21]\n print('数组A', _deepcopy(A), '的Stooge排序结果为:', stooge.stoogesort(A), A)\n print('思考题7-4 快速排序的堆栈深度')\n print(' 7.1中的快速排序算法包含有两个对其自身的递归调用,但是第二个递归不是必须的')\n A = [8, 7, 56, 43, 21]\n print('数组A', _deepcopy(A), '的尾递归快速排序结果为:', quicksort.morequicksort(A))\n print('思考题7-5 \\\"三数取中\\\"划分 也就是主元素RANDOMIZED-QUICKSORT的RANDOMIZED-PARTITION过程')\n print(' 三数取中方法仅仅影响其运行时间Ω(nlgn)中的常数因子')\n print('思考题7-6 对区间的模糊排序:算法的目标是对这些区间进行模糊排序')\n print('模糊排序算法的期望运行时间为Θ(nlgn),但当所有区间都重叠时,期望的运行时间为Θ(n)')\n # python src/chapter7/chapter7note.py\n # python3 src/chapter7/chapter7note.py\n\nchapter7_1 = Chapter7_1()\nchapter7_2 = Chapter7_2()\nchapter7_3 = Chapter7_3()\nchapter7_4 = Chapter7_4()\n\ndef printchapter7note():\n '''\n print chapter7 note.\n '''\n print('Run main : single chapter seven!') \n chapter7_1.note()\n chapter7_2.note()\n chapter7_3.note()\n chapter7_4.note()\n\n# python src/chapter7/chapter7note.py\n# python3 src/chapter7/chapter7note.py\nif __name__ == '__main__': \n printchapter7note()\nelse:\n pass\n", "meta": {"hexsha": "ac7fbdd0bf63106049014a09ace0a3faa9ca1176", "size": 8312, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chapter7/chapter7note.py", "max_stars_repo_name": "Peefy/CLRS_dugu_code-master", "max_stars_repo_head_hexsha": "98f00e75e1b0ebc13a7affb2604bec8501692a19", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-01-31T03:08:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T12:57:01.000Z", "max_issues_repo_path": "src/chapter7/chapter7note.py", "max_issues_repo_name": "HideLakitu/IntroductionToAlgorithm.Python", "max_issues_repo_head_hexsha": "33662f46dc346203b220d7481d1a4439feda05d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter7/chapter7note.py", "max_forks_repo_name": "HideLakitu/IntroductionToAlgorithm.Python", "max_forks_repo_head_hexsha": "33662f46dc346203b220d7481d1a4439feda05d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-03T04:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T10:18:58.000Z", "avg_line_length": 34.7782426778, "max_line_length": 97, "alphanum_fraction": 0.5973291627, "include": true, "reason": "from numpy", "num_tokens": 4220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.25683198001082097, "lm_q1q2_score": 0.08954322042895793}} {"text": "# coding=utf-8\nimport numpy as np\nimport torch\nimport os\nimport torch.nn.functional as F\nimport cv2\nimport random\n\n\ndef class_weights():\n \"\"\"\n COCO train2014每个样本类的频率\n 是用于处理样本不均衡.\n “样本偏斜是指数据集中正负类样本数量不均,比如正类样本有10000个,负类样本只有100个,\n 这就可能使得超平面被“推向”负类(因为负类数量少,分布得不够广),影响结果的准确性。\n \"\"\"\n weights = 1 / torch.FloatTensor(\n [187437, 4955, 30920, 6033, 3838, 4332, 3160, 7051, 7677, 9167, 1316, 1372, 833, 6757, 7355, 3302, 3776, 4671,\n 6769, 5706, 3908, 903, 3686, 3596, 6200, 7920, 8779, 4505, 4272, 1862, 4698, 1962, 4403, 6659, 2402, 2689,\n 4012, 4175, 3411, 17048, 5637, 14553, 3923, 5539, 4289, 10084, 7018, 4314, 3099, 4638, 4939, 5543, 2038, 4004,\n 5053, 4578, 27292, 4113, 5931, 2905, 11174, 2873, 4036, 3415, 1517, 4122, 1980, 4464, 1190, 2302, 156, 3933,\n 1877, 17630, 4337, 4624, 1075, 3468, 135, 1380])\n weights /= weights.sum()\n # tensor([1.4458e-04, 5.4690e-03, 8.7642e-04, 4.4918e-03, 7.0606e-03, 6.2555e-03,\n # 8.5756e-03, 3.8433e-03, 3.5299e-03, 2.9561e-03, 2.0592e-02, 1.9751e-02,\n # 3.2532e-02, 4.0105e-03, 3.6844e-03, 8.2068e-03, 7.1766e-03, 5.8015e-03,\n # 4.0034e-03, 4.7492e-03, 6.9342e-03, 3.0010e-02, 7.3518e-03, 7.5358e-03,\n # 4.3708e-03, 3.4216e-03, 3.0868e-03, 6.0153e-03, 6.3433e-03, 1.4554e-02,\n # 5.7682e-03, 1.3812e-02, 6.1546e-03, 4.0695e-03, 1.1282e-02, 1.0078e-02,\n # 6.7544e-03, 6.4907e-03, 7.9445e-03, 1.5896e-03, 4.8073e-03, 1.8621e-03,\n # 6.9077e-03, 4.8924e-03, 6.3182e-03, 2.6873e-03, 3.8613e-03, 6.2816e-03,\n # 8.7444e-03, 5.8428e-03, 5.4867e-03, 4.8888e-03, 1.3297e-02, 6.7679e-03,\n # 5.3629e-03, 5.9193e-03, 9.9292e-04, 6.5886e-03, 4.5690e-03, 9.3283e-03,\n # 2.4252e-03, 9.4322e-03, 6.7143e-03, 7.9352e-03, 1.7863e-02, 6.5742e-03,\n # 1.3686e-02, 6.0705e-03, 2.2772e-02, 1.1772e-02, 1.7371e-01, 6.8901e-03,\n # 1.4437e-02, 1.5371e-03, 6.2483e-03, 5.8605e-03, 2.5208e-02, 7.8139e-03,\n # 2.0073e-01, 1.9637e-02])\n\n return weights\n\n\ndef xyxy2xywh(x): # Convert bounding box format from [x1, y1, x2, y2] to [x, y, w, h]\n y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)\n y[:, 0] = (x[:, 0] + x[:, 2]) / 2\n y[:, 1] = (x[:, 1] + x[:, 3]) / 2\n y[:, 2] = x[:, 2] - x[:, 0]\n y[:, 3] = x[:, 3] - x[:, 1]\n return y\n\n\ndef xywh2xyxy(x): # Convert bounding box format from [x, y, w, h] to [x1, y1, x2, y2]\n y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)\n y[:, 0] = (x[:, 0] - x[:, 2] / 2)\n y[:, 1] = (x[:, 1] - x[:, 3] / 2)\n y[:, 2] = (x[:, 0] + x[:, 2] / 2)\n y[:, 3] = (x[:, 1] + x[:, 3] / 2)\n return y\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n \"\"\"\n Returns the IoU of two bounding boxes\n \"\"\"\n if x1y1x2y2:\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n else:\n # Transform from center and width to exact coordinates\n b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n\n # get the coordinates of the intersection rectangle\n inter_rect_x1 = torch.max(b1_x1, b2_x1)\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n # Intersection area\n inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1, 0) * torch.clamp(inter_rect_y2 - inter_rect_y1, 0)\n # Union Area\n b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)\n b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)\n\n return inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n\ndef build_targets(pred_boxes, pred_conf, pred_cls, target, anchor_wh, nA, nC, nG, batch_report):\n \"\"\"return tx, ty, tw, th, tconf, tcls, nCorrect, nT:number of targets \"\"\"\n nB = len(target) # number of images in batch\n nT = [len(x) for x in target] # targets per image\n tx = torch.zeros(nB, nA, nG, nG) # nB:batch size(4)\n ty = torch.zeros(nB, nA, nG, nG) # nA:number of anchors(3),\n tw = torch.zeros(nB, nA, nG, nG) # nG:number of grid points(13) = img_dim/stride\n th = torch.zeros(nB, nA, nG, nG)\n tconf = torch.ByteTensor(nB, nA, nG, nG).fill_(0) # 在函数后面加 _ 是改变自身的意思\n tcls = torch.ByteTensor(nB, nA, nG, nG, nC).fill_(0) # nC = number of classes\n TP = torch.ByteTensor(nB, max(nT)).fill_(0)\n FP = torch.ByteTensor(nB, max(nT)).fill_(0)\n FN = torch.ByteTensor(nB, max(nT)).fill_(0)\n\n TC = torch.ShortTensor(nB, max(nT)).fill_(-1) # target category 目标类别\n\n for b in range(nB):\n nTb = nT[b] # number of targets\n if nTb == 0:\n continue\n t = target[b]\n if batch_report:\n FN[b, :nTb] = 1\n\n # 转换为相对于框的位置\n TC[b, :nTb], gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG\n # 获取网格框索引并防止溢出(即13个锚点上的13.01)\n '''\n clamp表示夹紧,夹住的意思,torch.clamp(input,min,max,out=None)-> Tensor\n 将input中的元素限制在[min,max]范围内并返回一个Tensor\n '''\n gi = torch.clamp(gx.long(), min=0, max=nG - 1)\n gj = torch.clamp(gy.long(), min=0, max=nG - 1)\n\n # iou of targets-anchors (using wh only)\n box1 = t[:, 3:5] * nG\n # box2 = anchor_grid_wh[:, gj, gi]\n box2 = anchor_wh.unsqueeze(1).repeat(1, nTb, 1)\n\n # torch.prod(input): 返回所有元素的乘积\n inter_area = torch.min(box1, box2).prod(2)\n iou_anch = inter_area / (gw * gh + box2.prod(2) - inter_area + 1e-16)\n\n # Sekect best iou_pred and anchor\n iou_anch_best, a = iou_anch.max(0) # best anchor [0-2] for each target\n\n # Select best unique target-anchor combinations\n if nTb > 1:\n iou_order = np.argsort(-iou_anch_best) # best to worst\n\n # Unique anchor selection(slower but retains original order)\n u = torch.cat((gi, gj, a), 0).view(3, -1).numpy()\n _, first_unique = np.unique(u[:, iou_order], axis=1, return_index=True) # 第一个独特的指数\n\n i = iou_order[first_unique]\n # 最佳anchor必须与目标共享重要的共性(iou)\n i = i[iou_anch_best[i] > 0.10]\n if len(i) == 0:\n continue\n\n a, gj, gi, t = a[i], gj[i], gi[i], t[i]\n if len(t.shape) == 1:\n t = t.view(1, 5)\n else:\n if iou_anch_best < 0.10:\n continue\n i = 0\n\n tc, gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG\n\n # Coordinates 坐标\n # b : number of images in batch\n # a : anchor\n tx[b, a, gj, gi] = gx - gi.float()\n ty[b, a, gj, gi] = gy - gj.float()\n\n # Width and height(yolo method)\n tw[b, a, gj, gi] = torch.log(gw / anchor_wh[a, 0])\n th[b, a, gj, gi] = torch.log(gh / anchor_wh[a, 1])\n\n # One-hot encoding of label\n tcls[b, a, gj, gi, tc] = 1\n tconf[b, a, gj, gi] = 1\n\n if batch_report:\n # predicted classes and confidence\n tb = torch.cat((gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2)).view(4, -1).t() # target boxes\n pcls = torch.argmax(pred_cls[b, a, gj, gi], 1).cpu()\n pconf = torch.sigmoid(pred_conf[b, a, gj, gi]).cpu()\n iou_pred = bbox_iou(tb, pred_boxes[b, a, gj, gi].cpu())\n\n TP[b, i] = (pconf > 0.5) & (iou_pred > 0.5) & (pcls == tc)\n FP[b, i] = (pconf > 0.5) & (TP[b, i] == 0)\n FN[b, i] = pconf <= 0.5\n return tx, ty, tw, th, tconf, tcls, TP, FP, FN, TC\n\n\ndef model_info(model): # Plots a line-by-line description of a PyTorch model\n n_p = sum(x.numel() for x in model.parameters()) # number parameters\n n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients\n print('\\n%5s %50s %9s %12s %20s %12s %12s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))\n for i, (name, p) in enumerate(model.named_parameters()):\n name = name.replace('module_list.', '')\n print('%5g %50s %9s %12g %20s %12.3g %12.3g' % (\n i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))\n print('Model Summary: %g layers, %g parameters, %g gradients\\n' % (i + 1, n_p, n_g))\n\n\ndef load_classes(path):\n \"\"\"\n Loads class labels at 'path'\n \"\"\"\n fp = open(path, 'r')\n names = fp.read().split('\\n')[:-1]\n return names\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.\n # Arguments\n tp: True positives (list).\n conf: Objectness value from 0-1 (list).\n pred_cls: Predicted object classes (list).\n target_cls: True object classes (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # lists/pytorch to numpy\n tp, conf, pred_cls, target_cls = np.array(tp), np.array(conf), np.array(pred_cls), np.array(target_cls)\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n # Find unique classes\n unique_classes = np.unique(np.concatenate((pred_cls, target_cls), 0))\n\n # Create Precision-Recall curve and compute AP for each class\n ap, p, r = [], [], []\n for c in unique_classes:\n i = pred_cls == c\n n_gt = sum(target_cls == c) # Number of ground truth objects\n n_p = sum(i) # Number of predicted objects\n\n if (n_p == 0) and (n_gt == 0):\n continue\n elif (n_p == 0) or (n_gt == 0):\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n # Accumulate FPs and TPs\n fpc = np.cumsum(1 - tp[i])\n tpc = np.cumsum(tp[i])\n\n # Recall\n recall_curve = tpc / (n_gt + 1e-16)\n r.append(tpc[-1] / (n_gt + 1e-16))\n\n # Precision\n precision_curve = tpc / (tpc + fpc)\n p.append(tpc[-1] / (tpc[-1] + fpc[-1]))\n\n # AP from recall-precision curve\n ap.append(compute_ap(recall_curve, precision_curve))\n\n return np.array(ap), unique_classes.astype('int32'), np.array(r), np.array(p)\n\n\ndef compute_ap(recall, precision):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n # Arguments\n recall: The recall curve (list).\n precision: The precision curve (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n\n mrec = np.concatenate(([0.], recall, [1.]))\n mpre = np.concatenate(([0.], precision, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4):\n \"\"\"\n Removes detections with lower object confidence score than 'conf_thres' and performs\n Non-Maximum Suppression to further filter detections.\n Returns detections with shape:\n (x1, y1, x2, y2, object_conf, class_score, class_pred)\n \"\"\"\n\n output = [None for _ in range(len(prediction))]\n for image_i, pred in enumerate(prediction):\n # Filter out confidence scores below threshold\n # Get score and class with highest confidence\n\n # cross-class NMS (experimental)\n cross_class_nms = False\n if cross_class_nms:\n # thresh = 0.85\n thresh = nms_thres\n a = pred.clone()\n _, indices = torch.sort(-a[:, 4], 0) # sort best to worst\n a = a[indices]\n radius = 30 # area to search for cross-class ious\n for i in range(len(a)):\n if i >= len(a) - 1:\n break\n\n close = (torch.abs(a[i, 0] - a[i + 1:, 0]) < radius) & (torch.abs(a[i, 1] - a[i + 1:, 1]) < radius)\n close = close.nonzero()\n\n if len(close) > 0:\n close = close + i + 1\n iou = bbox_iou(a[i:i + 1, :4], a[close.squeeze(), :4].reshape(-1, 4), x1y1x2y2=False)\n bad = close[iou > thresh]\n\n if len(bad) > 0:\n mask = torch.ones(len(a)).type(torch.ByteTensor)\n mask[bad] = 0\n a = a[mask]\n pred = a\n\n x, y, w, h = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]\n a = w * h # area\n ar = w / (h + 1e-16) # aspect ratio\n\n log_w, log_h, log_a, log_ar = torch.log(w), torch.log(h), torch.log(a), torch.log(ar)\n\n # n = len(w)\n # shape_likelihood = np.zeros((n, 60), dtype=np.float32)\n # x = np.concatenate((log_w.reshape(-1, 1), log_h.reshape(-1, 1)), 1)\n # from scipy.stats import multivariate_normal\n # for c in range(60):\n # shape_likelihood[:, c] = multivariate_normal.pdf(x, mean=mat['class_mu'][c, :2], cov=mat['class_cov'][c, :2, :2])\n\n class_prob, class_pred = torch.max(F.softmax(pred[:, 5:], 1), 1)\n\n v = ((pred[:, 4] > conf_thres) & (class_prob > .3))\n v = v.nonzero().squeeze()\n if len(v.shape) == 0:\n v = v.unsqueeze(0)\n\n pred = pred[v]\n class_prob = class_prob[v]\n class_pred = class_pred[v]\n\n # If none are remaining => process next image\n nP = pred.shape[0]\n if not nP:\n continue\n\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n box_corner = pred.new(nP, 4)\n xy = pred[:, 0:2]\n wh = pred[:, 2:4] / 2\n box_corner[:, 0:2] = xy - wh\n box_corner[:, 2:4] = xy + wh\n pred[:, :4] = box_corner\n\n # Detections ordered as (x1, y1, x2, y2, obj_conf, class_prob, class_pred)\n detections = torch.cat((pred[:, :5], class_prob.float().unsqueeze(1), class_pred.float().unsqueeze(1)), 1)\n # Iterate through all predicted classes\n unique_labels = detections[:, -1].cpu().unique()\n if prediction.is_cuda:\n unique_labels = unique_labels.cuda(prediction.device)\n\n nms_style = 'OR' # 'AND' or 'OR' (classical)\n for c in unique_labels:\n # Get the detections with the particular class\n detections_class = detections[detections[:, -1] == c]\n # Sort the detections by maximum objectness confidence\n _, conf_sort_index = torch.sort(detections_class[:, 4], descending=True)\n detections_class = detections_class[conf_sort_index]\n # Perform non-maximum suppression\n max_detections = []\n\n if nms_style == 'OR': # Classical NMS\n while detections_class.shape[0]:\n # Get detection with highest confidence and save as max detection\n max_detections.append(detections_class[0].unsqueeze(0))\n # Stop if we're at the last detection\n if len(detections_class) == 1:\n break\n # Get the IOUs for all boxes with lower confidence\n ious = bbox_iou(max_detections[-1], detections_class[1:])\n\n # Remove detections with IoU >= NMS threshold\n detections_class = detections_class[1:][ious < nms_thres]\n\n elif nms_style == 'AND': # 'AND'-style NMS, at least two boxes must share commonality to pass, single boxes erased\n while detections_class.shape[0]:\n if len(detections_class) == 1:\n break\n\n ious = bbox_iou(detections_class[:1], detections_class[1:])\n\n if ious.max() > 0.5:\n max_detections.append(detections_class[0].unsqueeze(0))\n\n # Remove detections with IoU >= NMS threshold\n detections_class = detections_class[1:][ious < nms_thres]\n\n if len(max_detections) > 0:\n max_detections = torch.cat(max_detections).data\n # Add max detections to outputs\n output[image_i] = max_detections if output[image_i] is None else torch.cat(\n (output[image_i], max_detections))\n\n return output\n\n\ndef write_cfg(cfgfile, cfg, precent):\n with open(cfgfile, 'r') as f:\n lines = f.read().split('\\n') # store the lines in a list\n lines = [x for x in lines if len(x) > 0] # get read of the empty lines\n lines = [x for x in lines if x[0] != '#'] # get rid of comments\n # lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces\\\n\n block = {}\n blocks = []\n # D:/yolotest/cfg/yolov3.cfg\n # prunedcfg = os.path.join('./'.join(cfgfile.split(\"/\")[0:-1]), \"prune_\" + cfgfile.split(\"/\")[-1])\n if not os.path.exists('sparsity_2_prune_cfg'):\n os.mkdir('sparsity_2_prune_cfg')\n prunedcfg = os.path.join(\"sparsity_2_prune_cfg/prune_{}_\".format(precent) + cfgfile.split(\"/\")[-1])\n for line in lines:\n if line[0] == \"[\": # This marks the start of a new block\n if len(block) != 0: # If block is not empty, implies it is storing values of previous block.\n blocks.append(block) # add it the blocks list\n block = {} # re-init the block\n block[\"type\"] = line[1:-1].rstrip()\n else:\n key, value = line.split(\"=\")\n block[key.rstrip()] = value.lstrip()\n blocks.append(block)\n x = 0\n # print(blocks[1])\n for block in blocks:\n if 'batch_normalize' in block:\n block['filters'] = cfg[x]\n x = x + 1\n ##\n with open(prunedcfg, 'w') as f:\n for block in blocks:\n for i in block:\n if i == \"type\":\n f.write('\\n')\n f.write(\"[\" + block[i] + \"]\\n\")\n for j in block:\n if j != \"type\":\n f.write(j + \"=\" + str(block[j]) + '\\n')\n print('save pruned cfg file in %s' % prunedcfg)\n return prunedcfg\n\n\ndef route_problem(model, ind):\n ds = list(model.children())\n dsas = list(ds[0].children())\n\n # print('-----------',dsas[90])\n sum1 = 0\n # print(dsas[90].named_children())\n for k in range(ind + 1):\n # print('k:',k)\n for i in dsas[k].named_children():\n # print('i:',i)\n if \"_\".join(i[0].split(\"_\")[0:-1]) == 'conv_with_bn':\n sum1 = sum1 + 1\n # print(sum1)\n return sum1 - 1\n\n\ndef dontprune(model):\n dontprune = []\n nnlist = model.module_list\n for i in range(len(nnlist)):\n for name in nnlist[i].named_children():\n if name[0].split(\"_\")[0] == 'shortcut':\n if 'conv' in list(nnlist[name[1].froms + i].named_children())[0][0]:\n dontprune.append(name[1].froms + i)\n else:\n dontprune.append(name[1].froms + i - 1)\n dontprune.append(i - 1)\n return dontprune\n\n\ndef coco_class_count(path='../coco/labels/train2014/'):\n import glob\n\n nC = 80 # number classes\n x = np.zeros(nC, dtype='int32')\n files = sorted(glob.glob('%s/*.*' % path))\n for i, file in enumerate(files):\n labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)\n x += np.bincount(labels[:, 0].astype('int32'), minlength=nC)\n print(i, len(files))\n\n\ndef plot_results():\n # Plot YOLO training results file 'results.txt'\n import glob\n import numpy as np\n import matplotlib.pyplot as plt\n plt.figure(figsize=(16, 8))\n s = ['X', 'Y', 'Width', 'Height', 'Objectness', 'Classification', 'Total Loss', 'Precision', 'Recall', 'mAP']\n files = sorted(glob.glob('results*.txt'))\n for f in files:\n results = np.loadtxt(f, usecols=[2, 3, 4, 5, 6, 7, 8, 17, 18, 16]).T # column 16 is mAP\n n = results.shape[1]\n for i in range(10):\n plt.subplot(2, 5, i + 1)\n plt.plot(range(1, n), results[i, 1:], marker='.', label=f)\n plt.title(s[i])\n if i == 0:\n plt.legend()\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None): # Plots one bounding box on image img\n tl = line_thickness or round(0.002 * max(img.shape[0:2])) + 1 # line thickness\n color = color or [random.randint(0, 255) for _ in range(3)]\n c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n cv2.rectangle(img, c1, c2, color, thickness=tl)\n if label:\n tf = max(tl - 1, 1) # font thickness\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n cv2.rectangle(img, c1, c2, color, -1) # filled\n cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\n# def model_info(model, report='full'):\n# # Plots a line-by-line description of a PyTorch model\n# n_p = sum(x.numel() for x in model.parameters()) # number parameters\n# n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients\n# if report is 'full':\n# print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))\n# for i, (name, p) in enumerate(model.named_parameters()):\n# name = name.replace('module_list.', '')\n# print('%5g %40s %9s %12g %20s %10.3g %10.3g' %\n# (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))\n# print('Model Summary: %g layers, %g parameters, %g gradients' % (len(list(model.parameters())), n_p, n_g))\n", "meta": {"hexsha": "32d84854c6dcd00ae368d503d0daec72b3f8b852", "size": 22363, "ext": "py", "lang": "Python", "max_stars_repo_path": "utils/utils.py", "max_stars_repo_name": "shentanyue/Pytorch-yolov3-trainv3", "max_stars_repo_head_hexsha": "26d85c82fdfc7bef7c2b6e70b56a9e2c254a81bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T10:21:58.000Z", "max_issues_repo_path": "utils/utils.py", "max_issues_repo_name": "shentanyue/Pytorch-yolov3-prune-faster", "max_issues_repo_head_hexsha": "26d85c82fdfc7bef7c2b6e70b56a9e2c254a81bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-13T08:37:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-13T08:37:04.000Z", "max_forks_repo_path": "utils/utils.py", "max_forks_repo_name": "shentanyue/Pytorch-yolov3-prune-faster", "max_forks_repo_head_hexsha": "26d85c82fdfc7bef7c2b6e70b56a9e2c254a81bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9578754579, "max_line_length": 127, "alphanum_fraction": 0.5491660332, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.17328821019878957, "lm_q1q2_score": 0.08935085233849209}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# TODO:\n# -\tget the unit renaming in the columns working with regex in `ac_representation_tool`\n# \n# -\tfigure out why the sym and symbolic all-pass filter diverge from each other\n# \n# -\tcreate a table of low-high pass vs rc & rl\n# \n# -\tlook into ngspice internals and really verify that there are no \n# equivalencies to dc internals with .ac sims\n# \n# Most likely will do this in another section further down the road\n# \n# -\tadd filter design tool and filter circuit generation tool; see isbn 978-0-387-92766-4 and things like cauer network tf implimentation\n# \n# -\tdiscuss L->C passive conversion\n# \n\n# In[1]:\n\n\nfrom skidl.pyspice import *\n#can you say cheeky \nimport PySpice as pspice\n#becouse it's written by a kiwi you know\nimport lcapy as kiwi\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sympy as sym\n\n\nfrom IPython.display import YouTubeVideo, display\n\nimport traceback\nimport warnings\n\n\n# In[2]:\n\n\n#import dc code from parral folder\nimport sys\nsys.path.insert(1, '../DC_1/')\nfrom DC_1_Codes import get_skidl_spice_ref\n#from AC_2_Codes import \n\nsym.init_printing()\n\n#notebook specific loading control statements \nget_ipython().run_line_magic('matplotlib', 'inline')\n#tool to log notebook internals\n#https://github.com/jrjohansson/version_information\nget_ipython().run_line_magic('load_ext', 'version_information')\nget_ipython().run_line_magic('version_information', 'skidl, PySpice,lcapy, sympy, numpy, matplotlib, pandas, scipy')\n\n\n# # Basic Passive Filters\n# \n# In this section, we will construct and look at the basic passive analog filters constructed of RLC elements only. For now, we will just develop an ac equivalent tool to `dc_ease` that was in the last chapter. As well as some basic data manipulation, plotting tool, and classes for the RLC primitive filters. For advanced tools filter analysis will be developed later in this chapter in section asdlkjfaljdfkj where then we can compare not only the SPICE simulation data but also the SPICE generated Pole-Zero Transfer function and the theoretical transfer function to each other in greater detail.\n# \n\n# ## The RC Low Pass Filter¶\n# \n# The RC filter is a first-order single-pole filter. Where the pole is realized physically by a shunt capacitor. For more technical details about an RC low pass filter consult the YT video by ALL ABOUT ELECTRONICS \"RC Low Pass Filter Explained\" that serves as the example source below\n# \n\n# ### The low pass RC filter from ALL ABOUT ELECTRONICS \"RC Low Pass Filter Explained\" @~ 8:35min\n\n# In[3]:\n\n\nYouTubeVideo('_2L0l-E1Wx0', width=500, height=400, start=515)\n\n\n# ### RC Low Pass Filter Subcircuit container class\n# \n# The class below is the first in a series of classes developed in this section to create and store information about the filter primitive under test. For each of these primitives we will create a class that does three things:\n# \n# -\tstores the filter element values in the class initiation method\n# \n# -\tgenerates the filter and its elements inside a SKiDl subcircuit to then included in the circuit under design\n# \n# -\tprovides a schematic representation method of the filter being constructed by this class via lcapy\n# \n# -\tprovides the transfer function and two-port representation of the filter in sympy via its own methods by using the lcapy schematic \n# \n# We see how this is done with the RC Low Pass filter first below\n# \n\n# In[4]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rc_lowpass filter class\n#class with lcapy and skidl subcircuit to create an RC lowpass filter\n\nclass rc_lowpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n lowpass RC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RC_Lowpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RC lowpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Cref={}\n Rref={}\n \n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, self.c['p']\n self.c['p', 'n']+=term_2, term_3\n \n if return_elements:\n return self.c, self.r\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract simply variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n self.with_values=with_values\n \n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 1 1_1; right=2')\n self.schematic.add('W 0 0_1; right')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add('R 0_1 2_1; right')\n self.schematic.add('C 2_1 1_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n \n \n \n \n\n\n# In the method for the subcircuit `SKiDl` above we referenced a port-terminal convention from a library **scikit-rf**. This is the main python library for S-parameter analysis and primitive rf circuit design in the Python scientific ecosystem. Where we will interact with it at length in the following sections but for now let's just get in the habit of using their port-terminal convention since we are coding all this up in python\n\n# Below we instantiate the filter to the values found in the reference example above and draw it\n\n# In[5]:\n\n\n#instatate the rc_lowpass filter to \nlowpassF=rc_lowpass(C_value=.1@u_uF, R_value=1@u_kOhm)\nlowpassF.lcapy_self()\n\n\n# Nest using `lcapy` we can use the circuit we created in `rc_lowpass.lcapy_self` to then extract the voltage transfer function coming from the Port 0 & 1 Terminals to the Port 2 & 3 Terminals. Where the method has been abstracted such that it can be called to just get the symbolic equation or get the symbolic equation with the values of this particular instance substituted into the symbolic expression.\n\n# In[6]:\n\n\n#get this filters abstract transfer function\nlowpassF.get_tf(with_values=False)\n\n\n# In[7]:\n\n\n#get this filters transfer function\nlowpassF.get_tf(with_values=True)\n\n\n# and finally, we will now use the lowpass filter in its primary utilization as part of a circuit to be simulated with SPICE.\n\n# In[8]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nlowpassF.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# ### making ac_ease¶\n# \n# In the last chapter, we developed a class `dc_ease` to make running the .dc SPICE simulation more automated. Here we will develop an analogies class `ac_ease` to automate the .ac simulation. There are some differences thou. For one with .dc simulation, we could sweep over any variable (I still need to fix pyspice to do that); whereas we learned in the last section that .ac simulation only allows us to sweep the operating frequency of all our sources simultaneously and observe the response of the circuit to each frequency in terms of Fourier transform terms. The second thing is that .dc simulations allowed us to access a plethora of circuit elements' internal parameters to record things such as current and power without having to add SPICE ammeter all over the place. While .ac does not have quite that support in ngspice (see typically chapter 31 \"Model and Device Parameters\" in the ngspice manual). So we are going to forgo do internal parameters in `ac_ease`.\n# \n# \n\n# Also, in the last section, we just used the \"linear\" sweep capability of an ac simulation. However, AC simulations are more commonly done via logarithm sweeps. This is akin to `np.logspace`, however, unlike NumPy's logspace, we till .ac what the starting and stop are and how many samples we want per decade. And then there is the less used \" octave \" sampling scheme where there is no numpy kin. Octave takes the starting frequency, say 1kHz, and then computes the doubles of it (think octaves in music) and then samples within that doubling. So 1kHz doubles to 2kHz and so on till the stop frequency is reached while getting n samples within each double via the \"number_of_points\" argument in the .ac simulation control.\n\n# In[9]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 ac_ease class\n#class to perform .ac simulations with a bit more grace\n\nclass ac_ease():\n \"\"\"\n Class to perform AC (.ac) SPICE simulation with some grace; \n currently limited to what pyspice and ngspice support\n \n TODO:\n - independent current sources can have their AC current measured via \n `@I[acreal]` & `@I[acrimag]` not shure if this is usefull\n also trying via the sensitivity \n - do some serious testing with ngspice directly to verify that internal\n parameters are as limited as they appear to be with .ac\n \n \"\"\"\n def __init__(self, circ_netlist_obj):\n \"\"\"\n Class to perform AC (.ac) SPICE simulation with some grace\n \n Args:\n circ_netlist_obj (pyspice.Spice.Netlist.Circuit): the Netlist circuit produced \n from SKiDl's `generate_netlist()`\n \n Returns: \n creates a table to control the ac sweep `self.fsweep_DF`\n this table will still need to be filled out before a simulation can be run with `self.do_ac_sim`\n can be filled out manually or with the helper method `self.ac_sweep_setup`\n \"\"\"\n self.circ_netlist_obj=circ_netlist_obj\n self._build_table()\n \n #dic of allowed AC sweep types\n self.allowed_steptypes_map={'linear':'lin', 'decade':'dec', 'octave': 'oct'}\n\n \n def _build_table(self):\n \"\"\"\n protected method to create `self.fsweep_DF` dataframe that stores the controls for the ac simulation\n \n TODO:\n -when pyspice accepts more things to sweep add them below\n \"\"\"\n self.fsweep_DF=pd.DataFrame(columns=['Start_freq', 'Stop_Freq', 'SamplingInc', 'StepType'])\n self.fsweep_DF.at[len(self.fsweep_DF)]=[.1@u_Hz, 120@u_GHz, 10, 'decade']\n\n def ac_sweep_setup(self, Start_freq, Stop_Freq, SamplingInc, StepType, display_table=False):\n \"\"\"\n Helper method to create the `self.fsweep_DF` to control the ac simulation\n \n Args:\n Start_freq (Hertz): starting frequency in Hertz of the ac simulation, must be less than `Stop_Freq` and can\n only be zero if `StepType='linear'`\n \n Stop_Freq (Hertz): stoping frequency in Hertz of the ac simulation, must be greater than `Start_freq` \n \n SamplingInc (int): number of samples per StepType interval\n \n StepType (string): string control for the ac simulation Step type.\n must be 'linear' (self-explanatory), 'decade' (log base 10 sampling interval), \n or 'octave' (starting frequency times 2**n to create sample space a double of the starting frequency\n so that samples are pulled from 2**(n-1) and 2**(n) times the starting frequency)\n \n display_table (bool; False): when true will display the generated `self.fsweep_DF` below\n this method call in a jupyter notebook like environment\n \n TODO:\n -add display action\n \"\"\"\n #check for allowed step types\n assert StepType in self.allowed_steptypes_map.keys(), f\"{StepType} is not allowed\"\n #force start to non zero if sweep not linear\n if StepType != 'linear':\n if float(Start_freq)==0:\n warnings.warn('\"linear\" is only sweep type that can start at 0Hz,\\n setting starting frequancy to 1e-1Hz')\n Start_freq=1e-1@u_Hz\n \n \n #check that stop frequency is greater than start\n assert Stop_Freq>Start_freq, 'Stop frequency must be greater then starting frequency'\n \n self.fsweep_DF.at[0]=[Start_freq, Stop_Freq, SamplingInc, StepType]\n \n if display_table:\n display(self.fsweep_DF)\n \n def _make_sim_control(self):\n \"\"\"\n Internal method to extract the row information to the .ac pyspice call arguments\n Will raise a warning if the simulation start frequency is 0Hz for non-linear frequency sampling and \n then set the start frequency to .1Hz\n \n Args:\n NONE\n \n Returns:\n `self.ac_control` what is feed into the .ac to do the simulation over a frequency\n \n \"\"\"\n \n #check the control table struct\n assert (self.fsweep_DF.columns==['Start_freq', 'Stop_Freq', 'SamplingInc', 'StepType']).all(), 'Contorl Table Column structer has been altered'\n \n #will probably change this down the road\n assert len(self.fsweep_DF)==1, 'there should only be one entry in the control table'\n \n #check the sweep type\n self.fsweep_DF['StepType'][0] in self.allowed_steptypes_map.keys(), f\"{self.fsweep_DF['StepType'][0]} is not allowed\"\n \n #check that stop frequency is greater than start\n assert self.fsweep_DF.at[0, 'Stop_Freq']>self.fsweep_DF.at[0, 'Start_freq'], 'Stop freqauncy must be grater then starting freauncy'\n \n #force start to non zero if sweep not linear\n if self.fsweep_DF['StepType'][0] != 'linear':\n if float(self.fsweep_DF['Start_freq'][0])==0:\n warnings.warn('\"linear\" is only sweep type that can start at 0Hz,\\n setting starting frequancy to 1e-1Hz')\n self.fsweep_DF.at[0, 'Start_freq']=1e-1@u_Hz\n \n self.ac_control={\n 'start_frequency':self.fsweep_DF.at[0, 'Start_freq'], \n 'stop_frequency':self.fsweep_DF.at[0, 'Stop_Freq'], \n 'number_of_points':self.fsweep_DF.at[0, 'SamplingInc'],\n 'variation': self.allowed_steptypes_map[self.fsweep_DF.at[0, 'StepType']]\n }\n \n \n \n \n def do_ac_sim(self):\n \"\"\"\n Does a standard Branch and Node .ac simulation for the single filled out row in `self.fsweep_DF`\n \n Args:\n None\n \n Returns: \n raw results are stored in `self.ac_vals`, processed results are automatically stored in \n `self.ac_resultsNB_DF` via `self.record_ac_nodebranch`\n \"\"\"\n self._make_sim_control()\n self.sim=self.circ_netlist_obj.simulator()\n self.ac_vals=self.sim.ac(**self.ac_control)\n \n self.record_ac_nodebranch()\n\n \n def record_ac_nodebranch(self):\n \"\"\" \n Helper method to put .ac node branch results into a dataframe where the index is the \n sweep frequency used in the simulation\n \n Args:\n None\n \n Returns:\n `self.ac_resultsNB_DF` which is a pandas dataframe with the index being the sweep frequency\n and the columns being the node voltages and branch currents from any available voltage sources \n \n TODO:\n look into getting the current in any current sources\n \n \"\"\"\n self.ac_resultsNB_DF=pd.DataFrame(index=self.ac_vals.frequency.as_ndarray())\n self.ac_resultsNB_DF.index.name='freq[Hz]'\n \n #get the node voltages\n for n in self.circ_netlist_obj.node_names:\n if n=='0':\n continue\n self.ac_resultsNB_DF[n+'_[V]']=self.ac_vals[n].as_ndarray()\n \n #get the current from any voltage source\n for cm in self.circ_netlist_obj.element_names:\n if 'V'==cm[0]:\n self.ac_resultsNB_DF[cm+'_[A]']=-self.ac_vals[cm].as_ndarray()\n \n\n\n# In[10]:\n\n\n#instainte the simulation from the circuit\nac_sweep=ac_ease(circ)\n#setup the simulation parameter with the helper method\nac_sweep.ac_sweep_setup(0, 100@u_MHz, 10, 'decade', True)\n\n\n# In[11]:\n\n\nac_sweep.do_ac_sim()\nac_sweep.ac_resultsNB_DF\n\n\n# ### making a basic ac data conversion tool\n# \n# As we learned in the last section since the returns of an AC simulation are complex values we have to represent the values in order to just plot the values. The following class has methods that will allow us to pass in the raw results of the AC simulation and then perform reinterpretation of the values as needed\n# \n\n# In[12]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 ac_representation_tool class\n#class that converts dataframe of raw ac complex data to veries complex\n#repsentations \n\nclass ac_representation_tool:\n \"\"\"\n Class to take a dataframe with AC simulation complex value data and\n represent it in various ways. raw data should come from `ac_ease.ac_resultsNB_DF`\n \n TODO:\n -get the unit renaming in the columns working with regex\n \"\"\"\n \n def __init__(self, ac_sim_raw_DF):\n \"\"\"\n pull in the data\n Args:\n ac_sim_raw_DF (pandas dataframe): pandas dataframe of raw data from AC simulation \n preferbyly from `ac_ease.ac_resultsNB_DF`, index must be the simulation\n frequency and columns must be the complex data\n \n Returns: \n None\n \n TODO:\n broaden complex assertin to include np.complex128\n \"\"\"\n #write asserts for ac_sim_DF\n assert repr(type(ac_sim_raw_DF))==\"\", '`ac_sim_raw_DF` must be a dataframe'\n #check that all columns from raw data are complex\n assert (ac_sim_raw_DF.dtypes==np.complex64).all() or (ac_sim_raw_DF.dtypes==np.complex128).all(), 'Raw data must be complex from AC sim'\n self.ac_sim_raw_DF=ac_sim_raw_DF\n \n def make_real_imag(self):\n \"\"\"\n Method to create a real and image version of the raw data\n\n Args: None\n \n Returns:\n real values are stored in `self.ac_sim_real_DF`; and \n imaginary values are stored in `self.ac_sim_imag_DF`\n \n \"\"\"\n \n self.ac_sim_real_DF=self.ac_sim_raw_DF.apply(np.real, axis=0)\n \n self.ac_sim_imag_DF=self.ac_sim_raw_DF.apply(np.imag, axis=0)\n \n \n def make_mag_phase(self, mag='dB', char_res=50, deg=True, phase_unwrap=True):\n \"\"\"\n Method to make generate the various magnitude and phase representation of the complex data\n \n Args:\n mag (string, \"dB\"): control statement to specify the representation of the generated \n magnitude data; right now only 'dB' and 'abs' are supported\n \n char_res (float; 50; ohms): the characteristic impedance for magnitude representation calculations; not \n implemented at the moment\n \n deg (bool; True): bool control statement to represent the phase data in degrees if True; else in radians\n \n phase_unwrap (bool; True): when True and `deg` is True will represent the degrees in phased unwrapped\n \n Returns:\n magnitude data is stored in `self.ac_sim_mag_DF` and phase data is stored in `self.ac_sim_phase_DF`\n \n TODO: \n -complete all of the magnitude conversions\n \"\"\"\n #deal with the cacophony of magnitudes\n mag_conversions={\n 'dB': lambda x: 10*np.log10(np.abs(x)) if x.name in ['[W]', '[VAR]', '[VA]'] else 20*np.log10(np.abs(x)), \n 'abs': lambda x: np.abs(x)\n }\n \n #check the input\n assert mag in mag_conversions.keys(), f'{mag} is not a known magnitude repsentation'\n \n self.ac_sim_mag_DF=self.ac_sim_raw_DF.apply(mag_conversions[mag], axis=0)\n \n #redo the column name units\n #get down with the regex to really do this\n if mag in ['dB']:\n self.ac_sim_mag_DF.rename(columns={i:i+'[dB]' for i in self.ac_sim_mag_DF.columns}, inplace=True)\n \n #deal with the phase\n \n if (deg==True) and (phase_unwrap==True):\n #phase unwrapped lambda function\n angle_phase_unwrap= lambda x: np.rad2deg(np.unwrap(np.angle(x)))\n\n self.ac_sim_phase_DF=self.ac_sim_raw_DF.apply(angle_phase_unwrap, axis=0)\n \n else:\n self.ac_sim_phase_DF=self.ac_sim_raw_DF.apply(np.angle, axis=0, deg=deg)\n\n #realy need that stupid regex working\n \n if deg:\n self.ac_sim_phase_DF.rename(columns={i:i+'[deg]' for i in self.ac_sim_phase_DF.columns}, inplace=True)\n else:\n self.ac_sim_phase_DF.rename(columns={i:i+'[rads]' for i in self.ac_sim_phase_DF.columns}, inplace=True)\n\n\n# In[13]:\n\n\nac_rep_tool=ac_representation_tool(ac_sweep.ac_resultsNB_DF)\nac_rep_tool.make_real_imag()\nac_rep_tool.ac_sim_real_DF\n\n\n# In[14]:\n\n\nac_rep_tool.make_mag_phase()\nac_rep_tool.ac_sim_mag_DF\n\n\n# ### Making a complex representation plotting templet¶\n# \n# Here we are going to make a class the store plot templets for the 3+1 major representations of complex values:\n# \n# -\tBode Plot with Magnitude and Phase on the same plot: The Bode plot is the most widely used plot of complex data that is parametric to the frequency which we use as the x-axis. This is one of two standard variations of the Bode plot where the Magnitude and Phase is plotted on the same graph using twin axis\n# \n# -\tBode Plot with Magnitude and Phase on the separate plots: In this version of the Bode plot the x-axis is still the frequency and there are two subplots sharing the same x-axis with the top plot being the magnitude plot and the bottom being the phase\n# \n# -\tNichols Plot: This is a parametric plot where the x-axis and the phase and the y-axis is the magnitude and direction is indicated by an arrow along the line showing the direction of frequency increase. This plot is used more in Feedback and Control system design.\n# \n# -\tNyquist Plot: This is a parametric plot where the x-axis and the real part and the y-axis is the imaginary part and direction is indicated by an arrow along the line showing the direction of frequency increase. This plot is used more in Feedback and Control system design.\n# \n# This class contains templets since an existing matplotlib axis can be passed through them to then include them in more advanced plots with additional information being able to be added to the axis. Or these plot methods can be called without any axis passed to them to then generate a basic plot\n# \n# \n\n# In[15]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 eecomplex_plot_templets class\n#class that stores templets plots for most common complex rep plots\n\nclass eecomplex_plot_templets():\n \"\"\"\n Class that stores basic/common Electrical Engineering Complex value\n representation plots that may be used stand-alone or as templets in other plots \n with refinements\n \"\"\"\n def __init__(self):\n pass\n \n def bode_plot_one_templet(self, freq_data, mag_data, phase_data, ax=None, title=''):\n \"\"\"\n Templet plot to make a Bode plot with Magnitude and Phase all in one\n graph using a twinx. \n \n Args:\n freq_data (numpy array or pandas series; Hz): the sampling frequency\n \n mag_data (numpy array or pandas seres; dB): the magnitude data in decibels\n \n phase_data (numpy array or pandas series; deg unwrapped): the phase data in degrees unwrapped\n \n ax (matplotlib axis; None): If left None will create a new plot, else must\n be a matplotlib subplot axis to be added to\n \n title (str; ''): Subplot title string\n \n Returns:\n Returns a bode plot, and if an axis was passed to `ax` will be modified\n with how to plot the magnitude\n \n \n TODO:\n - figure out how to return the `ax_phase` generated internally\n - add x,y scale control\n \"\"\"\n assert len(freq_data)==len(mag_data)==len(phase_data), 'freq_data, mag_data, phase_data, must all be the same length'\n \n if ax!=None:\n assert repr(type(ax))==\"\", 'ax must be a matplotlib axis'\n\n ax_mag=ax or plt.gca()\n\n\n #fig, ax_mag=plt.subplots()\n\n ax_phase=ax_mag.twinx()\n\n ax_mag.semilogx(freq_data, mag_data, label='mag')\n ax_phase.semilogx(freq_data, phase_data, color='green', linestyle='--', label='phase')\n \n\n ax_mag.set_xlabel('frequancy [Hz]')\n ax_mag.set_ylabel('[dB]')\n ax_phase.set_ylabel('[deg]')\n ax_mag.grid()\n \n #make a single legend \n handles, labels = [(a + b) for a, b in zip(ax_mag.get_legend_handles_labels(), ax_phase.get_legend_handles_labels())]\n ax_phase.legend(handles, labels)\n\n if title!='':\n title=' of '+title\n ax_mag.set_title(f'Bode Plot{title}')\n \n \n \n def bode_plot_two_templet(self, freq_data, mag_data, phase_data, \n axs=None, title=''):\n \"\"\"\n Templet plot to make a Bode plot with Magnitude and Phase in two separate subplots\n with shared x-axis\n \n Args:\n freq_data (numpy array or pandas series; Hz): the sampling frequency\n \n mag_data (numpy array or pandas seres; dB): the magnitude data in decibels\n \n phase_data (numpy array or pandas series; deg unwrapped): the phase data in degrees unwrapped\n \n axs (list of matplotlib axis; None): If left None will create a new plot, else must \n be a list of matplotlib subplots axis to be added to where the first entry\n will be the magnitude axis, and the second will be the phase axis\n \n title (str; ''): Subplot title string\n \n Returns:\n Returns a bode plot, and if an axis was passed to `ax` will be modified\n with how to plot the magnitude\n \n \n TODO:\n - add x,y scale control\n \"\"\"\n \n assert len(freq_data)==len(mag_data)==len(phase_data), 'freq_data, mag_data, phase_data, must all be the same length'\n \n \n if axs==None:\n fig, [ax_mag, ax_phase]=plt.subplots(nrows=2, sharex=True)\n else:\n assert len(axs)==2, 'there should only be two elements in axs'\n \n for i, ax in enumerate(axs):\n assert repr(type(ax))==\"\", f\"element {i} in axs was not a matplotlib axis\"\n ax_mag=axs[0]; ax_phase=axs[1]\n ax_mag.get_shared_x_axes().join(ax_mag, ax_phase)\n \n #fore the two axes to share x\n ax_mag.xaxis.set_tick_params(which='both', labelbottom=True)\n\n\n\n\n ax_mag.semilogx(freq_data, mag_data, label='mag')\n ax_phase.semilogx(freq_data, phase_data, color='green', linestyle='--', label='phase')\n\n\n\n ax_mag.set_ylabel('[dB]')\n ax_phase.set_ylabel('[deg]')\n ax_mag.grid()\n ax_phase.grid()\n \n #style the x-axis for both subplots so it's between the two\n ax_phase.set_xlabel('frequancy [Hz]')\n ax_phase.xaxis.set_label_position('top') \n ax_phase.xaxis.set_ticks_position('top') \n ax_phase.tick_params(labelbottom=False,labeltop=True)\n\n if title!='':\n title=' of '+title\n ax_mag.set_title(f'Bode Plot{title}');\n plt.tight_layout()\n \n \n def nichols_plot_templet(self, mag_data, phase_data, ax=None, title=''):\n \n \"\"\"\n Templet plot to make a Nichols plot with magnitude in the y-axis and\n phase in the x-axis, with a counter arrow showing the parametric direction\n \n Args:\n \n mag_data (numpy array or pandas seres; dB): the magnitude data in decibels\n \n phase_data (numpy array or pandas series; deg unwrapped): the phase data in degrees unwrapped\n \n ax (matplotlib axis; None): If left None will create a new plot, else must\n be a matplotlib subplot axis to be added to\n \n title (str; ''): Subplot title string\n \n Returns:\n Returns a Nichols plot, and if an axis was passed to `ax` will be modified\n with the Nichols plot\n \n \n TODO:\n - add x,y scale control\n \"\"\"\n \n assert len(mag_data)==len(phase_data), 'mag_data and phase_data, must all be the same length'\n\n if ax!=None:\n assert repr(type(ax))==\"\", 'ax must be a matplotlib axis'\n\n ax=ax or plt.gca()\n\n ax.plot(phase_data, mag_data)\n line=ax.get_lines()[0]\n eecomplex_plot_templets.add_arrow(line)\n\n \n #xlim\n xmin=phase_data.min()*1.1; xmax=phase_data.max()*1.1\n \n if -1*xmaxxmax:\n xmax=-1*xmin\n \n ax.set_xlim(xmin, xmax)\n \n\n ax.set_xlabel('[deg]'); ax.set_ylabel('[dB]')\n\n ax.grid()\n #ax.axhline(0, linestyle='--', linewidth=2.0, color='black')\n ax.axvline(0, linestyle='--', linewidth=2.0, color='black')\n if title!='':\n title=' of '+title\n ax.set_title(f'Nichols Plot{title}');\n \n\n def nyquist_plot_templet(self, real_data, imag_data, ax=None, title=''):\n \"\"\"\n Templet plot to make a Nyquist plot with imaginary in the y-axis and\n real in the x-axis, with a counter arrow showing the parametric direction\n \n Args:\n \n real_data (numpy array or pandas series): the real data \n \n imag_data (numpy array or pandas series): the imaginary data\n \n ax (matplotlib axis; None): If left None will create a new plot, else must\n be a matplotlib subplot axis to be added to\n \n title (str; ''): Subplot title string\n \n Returns:\n Returns a Nyquist plot, and if an axis was passed to `ax` will be modified\n with the Nyquist plot\n \n \n TODO:\n - add x,y scale control\n \"\"\"\n assert len(real_data)==len(imag_data), 'real_data and imag_data, must all be the same length'\n\n if ax!=None:\n assert repr(type(ax))==\"\", 'ax must be a matplotlib axis'\n\n ax=ax or plt.gca()\n\n ax.plot(real_data, imag_data)\n line=ax.get_lines()[0]\n eecomplex_plot_templets.add_arrow(line)\n\n #xlim\n xmin=real_data.min()*1.1; xmax=real_data.max()*1.1\n\n if -1*xmaxxmax:\n xmax=-1*xmin\n ax.set_xlim(xmin, xmax)\n\n #ylim\n ymin=imag_data.min()*1.1; ymax=imag_data.max()*1.1\n\n if -1*ymaxymax:\n ymax=-1*ymin\n ax.set_ylim(ymin, ymax)\n\n ax.set_xlabel('Real'); ax.set_ylabel('Imag')\n\n ax.grid()\n ax.axhline(0, linestyle='--', linewidth=2.0, color='black')\n ax.axvline(0, linestyle='--', linewidth=2.0, color='black')\n if title!='':\n title=' of '+title\n ax.set_title(f'Nyquist Plot{title}');\n \n @staticmethod\n def add_arrow(line, positions=None, num_positions=4, direction='right', size=15, color=None):\n \"\"\"\n add an arrow to a line axis in the direction of the parametric data.\n\n line: Line2D object\n positions: list or array of index positions to draw an arrow(s) at; if None will draw at least one arrow\n num_positions: int; then number arrows to draw along the length of the line; if 1 will draw at the mean\n direction: 'left' or 'right'\n size: the size of the arrow in font-size points\n color: if None, line color is taken.\n\n from: https://stackoverflow.com/questions/34017866/arrow-on-a-line-plot-with-matplotlib\n and also use:https://stackoverflow.com/questions/52042183/matplotlib-get-color-for-subplot\n\n \n \"\"\"\n #if color is None:\n # color = line.get_color()\n\n xdata = line.get_xdata()\n ydata = line.get_ydata()\n \n \n if (positions is None) and (num_positions==1):\n positions=[]\n positions[0] = xdata.mean()\n elif (positions is None) and (num_positions!=1):\n line_len=len(xdata)\n if num_positions>=line_len:\n num_positions==line_len\n positions=[xdata[int(np.ceil(i*line_len/num_positions))] for i in range(num_positions)]\n else:\n assert all(isinstance(i, int) for i in positions), 'positions must be int index positions'\n \n for pos in positions:\n # find the closest index\n start_ind = np.argmin(np.absolute(xdata - pos))\n if direction == 'right':\n end_ind = start_ind + 1\n else:\n end_ind = start_ind - 1\n\n line.axes.annotate('',\n xytext=(xdata[start_ind], ydata[start_ind]),\n xy=(xdata[end_ind], ydata[end_ind]),\n arrowprops=dict(arrowstyle=\"->\", color=color),\n size=size\n )\n\n\n# Here we invoke the class and start by creating the single graph Bode plot with twinx axis so that magnitude and phase are overlapping on one plot\n\n# In[16]:\n\n\nac_p=eecomplex_plot_templets()\n\nac_p.bode_plot_one_templet(ac_rep_tool.ac_sim_mag_DF.index, ac_rep_tool.ac_sim_mag_DF['Out_[V][dB]'], ac_rep_tool.ac_sim_phase_DF['Out_[V][deg]'], \n title='Out_[V]')\n\n\n# And here we use the seconed Bode plot method to make the graph with the joined subplots but each subplot has the magnitude and phase respectivly\n\n# In[17]:\n\n\nac_p.bode_plot_two_templet(ac_rep_tool.ac_sim_mag_DF.index, ac_rep_tool.ac_sim_mag_DF['Out_[V][dB]'], ac_rep_tool.ac_sim_phase_DF['Out_[V][deg]'], \n title='Out_[V]')\n\n\n# Here is the Nichols plot pf out data with parmteriztion arrows showing the direction of increasing frequancy. Note that since that data was aquared logrimgly and the space inside `eecomplex_plot_templets.add_arrow` uses linear supdivsion the spacing on the arrows is going to follow logrithmicly as well\n\n# In[18]:\n\n\nac_p.nichols_plot_templet(ac_rep_tool.ac_sim_mag_DF['Out_[V][dB]'], ac_rep_tool.ac_sim_phase_DF['Out_[V][deg]'], \n title='Out_[V]')\n\n\n# And finally, we create the Nyquist plot again with the same parametricness shown by the arrows and with the same linear to log issue in their spacing.\n\n# In[19]:\n\n\nac_p.nyquist_plot_templet(ac_rep_tool.ac_sim_real_DF['Out_[V]'], ac_rep_tool.ac_sim_imag_DF['Out_[V]'], \n title='Out_[V]')\n\n\n# ### A quick filter exploration tool for the rest of this notebook¶\n# \n# Here we create an easy use tool using mutable inheritance of our three ac tools wherein the `__init__` method it performs the AC simulation, makes the representation transformations, and plot. And in the second method, we get grab the symbolic transfer function for the filter and pass it the same frequencies as the SPICE simulation and plot it on top of the SPICE simulation to examine any mild to gross divergence from the SPICE simulation and the symbolic.\n# \n\n# In[20]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 qfilter_explorer class\n#class to perform the anylsis of the filtes in Ch2 sec 2\n\nclass qfilter_explorer(ac_ease, ac_representation_tool, eecomplex_plot_templets):\n \n def __init__(self, circ, title, start_freq=.1@u_Hz, stop_freq=1@u_GHz):\n \n #do what ac_ease is supposed to do at startup\n #instainte the simulation from the circuit\n ac_ease.__init__(self, circ)\n #setup the simulation parameter with the helper method\n self.ac_sweep_setup(start_freq, stop_freq, 20, 'decade', True)\n #do the simulation\n self.do_ac_sim()\n \n \n #do what ac_representation_tool is supposed to do at startup\n #and pass in the selfs from `ac_ease`'s ac_resultsNB_DF\n ac_representation_tool.__init__(self, self.ac_resultsNB_DF)\n #generate the representations\n self.make_real_imag()\n self.make_mag_phase()\n \n \n eecomplex_plot_templets.__init__(self)\n\n\n fig=plt.figure(constrained_layout=True, figsize=(8,8))\n spec=fig.add_gridspec(2,2)\n\n ax_bode=fig.add_subplot(spec[0, :])\n self.bode_plot_one_templet(self.ac_sim_mag_DF.index, self.ac_sim_mag_DF['Out_[V][dB]'], self.ac_sim_phase_DF['Out_[V][deg]'], \n title='Out_[V]', ax=ax_bode)\n\n ax_nichols=fig.add_subplot(spec[1, 0])\n self.nichols_plot_templet(self.ac_sim_mag_DF['Out_[V][dB]'], self.ac_sim_phase_DF['Out_[V][deg]'], \n title='Out_[V]', ax=ax_nichols)\n\n ax_nyquist=fig.add_subplot(spec[1, 1])\n self.nyquist_plot_templet(self.ac_sim_real_DF['Out_[V]'], self.ac_sim_imag_DF['Out_[V]'], \n title='Out_[V]', ax=ax_nyquist)\n \n fig.suptitle(title)\n \n def symbolic_tf(self, filter_obj):\n self.symbolic_data=pd.DataFrame(index=self.ac_resultsNB_DF.index)\n \n f=self.symbolic_data.index.values\n \n #get the tf and get the data\n tf=filter_obj.get_tf()\n symbolic_data=tf.frequency_response(self.symbolic_data.index.values).astype('complex')\n \n self.symbolic_data['Out_sym_[V][dB]']=20*np.log10(np.abs(symbolic_data))\n self.symbolic_data['Out_sym_[V][deg]']=np.angle(symbolic_data, deg=True)\n\n fig, [ax_mag, ax_ph]=plt.subplots(nrows=2, ncols=1)\n \n self.bode_plot_two_templet(self.ac_sim_mag_DF.index, self.ac_sim_mag_DF['Out_[V][dB]'], self.ac_sim_phase_DF['Out_[V][deg]'], \n title='Simulated vs Symbolic Out_[V]', axs=[ax_mag, ax_ph])\n \n #add the symbolic data\n ax_mag.semilogx(f, self.symbolic_data['Out_sym_[V][dB]'], linestyle='-.' , alpha=0.5, label='symbolic')\n ax_mag.legend()\n \n ax_ph.semilogx(f, self.symbolic_data['Out_sym_[V][deg]'], color='orange' , alpha=0.75, label='symbolic')\n ax_ph.legend() \n\n\n# In[21]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RC Low Pass Filter Responce');\n\n\n# In[22]:\n\n\nfilter_responce.symbolic_tf(lowpassF)\n\n\n# ##Equivalent Low Pass RL filter\n# \n# Besides RC filters, there are of course RL dual filters. Where the equivalent RL filter values to any RC filter may be found via the equivalent time constant of the RC and RL implementation such that time constants must match ie: $$RC=\\tau_{RC}=\\tau_{RL}=L/R$$\n\n# In[23]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rl_lowpass filter class\n#class with lcapy and skidl subcircuit to create an RL lowpass filter\n\nclass rl_lowpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n lowpass RL filter primitive\n \"\"\"\n def __init__(self, subcirc_ref=None, L_value=1@u_H, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_H; Henery): the inductance in henrys for the RL inductive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RL resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RL_Lowpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RL lowpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n \n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.r=R(value=self.R_value, **Rref)\n \n self.l['p', 'n']+=term_0, term_2\n self.r[1, 2]+=self.l['n'], term_1\n \n if return_elements:\n return self.l, self.r\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 1 1_1; right=2')\n self.schematic.add('W 0 0_1; right')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'L 0_1 2_1; right, l=L{str(self.L_value)}')\n self.schematic.add(f'R 2_1 1_1; down, l=R{str(self.R_value)}')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value})\n \n if draw_me:\n self.schematic.draw()\n\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n \n\n\n# In[24]:\n\n\n#instatate the rl_lowpass filter to \nrl_l=rl_lowpass(L_value=(1e3)**2 *.1e-9 @u_H, R_value=1e3)\nrl_l.lcapy_self()\n\n\n# In[25]:\n\n\n#get this filters abstract transfer function\nrl_l.get_tf(with_values=False)\n\n\n# In[26]:\n\n\n#get this filters transfer function\nrl_l.get_tf(with_values=True)\n\n\n# In[27]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nrl_l.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[28]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RL Low Pass Filter Responce');\n\n\n# In[29]:\n\n\nfilter_responce.symbolic_tf(rl_l)\n\n\n# ## The high pass filter from ALL ABOUT ELECTRONICS \"RC High Pass Filter Explained\" @~ 7:57min\n# \n# As we saw with the RC and RL \"Lowpass\" filters they are named by the typical convention of how there implemented followed by some characteristic description of their magnitude response. Thus, lowpass filters minimally attenuate any single whose frequency content is less than the frequency of their 3dB knee. Whereas Highpass filters are the complement to that where they will highly attenuate any single whose frequency content is less than there 3dB knee as shown below using the example from ALL ABOUT ELELECTROINC YT video on “RC High Pass Filters”\n\n# In[30]:\n\n\nYouTubeVideo('9Dx0b0ukNAM', width=500, height=400, start=477)\n\n\n# In[31]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rc_highpass filter class\n#class with lcapy and skidl subcircuit to create an RC highpass filter\n\nclass rc_highpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n highpass RC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RC_highpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RC highpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Cref={}\n Rref={}\n \n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.c['p', 'n']+=term_0, term_2\n self.r[1, 2]+=self.c['n'], term_1\n \n if return_elements:\n return self.c, self.r\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 1 1_1; right=2')\n self.schematic.add('W 0 0_1; right')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add('C 0_1 2_1; right')\n self.schematic.add('R 2_1 1_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n\n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n \n \n\n\n# In[32]:\n\n\nhighpassF=rc_highpass(C_value=1.5@u_nF, R_value=10@u_kOhm)\nhighpassF.lcapy_self()\n\n\n# In[33]:\n\n\n#get this filters abstract transfer function\nhighpassF.get_tf(with_values=False)\n\n\n# In[34]:\n\n\n#get this filters transfer function\nhighpassF.get_tf(with_values=True)\n\n\n# In[35]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nhighpassF.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[36]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RC High Pass Filter Responce');\n\n\n# In[37]:\n\n\nfilter_responce.symbolic_tf(highpassF)\n\n\n# ## RL Highpass\n\n# In[38]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rl_highpass filter class\n#class with lcapy and skidl subcircuit to create an RL highpass filter\n\nclass rl_highpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n highpass RL filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RL inductive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RL resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RL_highpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RL highpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, self.l['p']\n self.l['p', 'n']+=term_2, term_3\n \n \n \n \n if return_elements:\n return self.l, self.r\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 1 1_1; right=2')\n self.schematic.add('W 0 0_1; right')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'R 0_1 2_1; right')\n self.schematic.add(f'L 2_1 1_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n \n \n\n\n# In[39]:\n\n\nrl_h=rl_highpass(L_value=(10e3)**2 *1.5e-9 @u_H, R_value=10@u_kOhm)\nrl_h.lcapy_self()\n\n\n# In[40]:\n\n\n#get this filters abstract transfer function\nrl_h.get_tf(with_values=False)\n\n\n# In[41]:\n\n\n#get this filters transfer function\nrl_h.get_tf(with_values=True)\n\n\n# In[42]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nrl_h.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[43]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RL High Pass Filter Responce');\n\n\n# In[44]:\n\n\nfilter_responce.symbolic_tf(rl_h)\n\n\n# # First Order Cascade filter\n\n# Though as we will see there are more complex single filter designs that can implement a needed filter profile the other way to implement the needed filter profile is by cascading primitive filter sections as shown by ALL ABOUT ELELECTOINCS where here we will just implement the passive version of the cascaded bandpass filter shown below.\n\n# ## The band pass filter from ALL ABOUT ELECTRONICS \"Band Pass Filter and Band Stop Filter Explained\" @~ 4:03min\n\n# In[45]:\n\n\nYouTubeVideo('dmPIydL0lyM', width=500, height=400, start=243)\n\n\n# In[46]:\n\n\nreset()\nnet_in=Net('In'); net_inter=Net('Inter'); net_out=Net('Out')\n\nvs=SINEV(amplitude=10@u_V, frequency=10@u_kHz)\nvs['p', 'n']+=net_in, gnd\n\nhighpassFsection=rc_highpass(C_value=1.5@u_nF, R_value=10@u_kOhm)\nhighpassFsection.SKiDl(net_in, gnd, net_inter, gnd)\n\nlowpassFsection=rc_lowpass(C_value=1.5@u_nF, R_value=1@u_kOhm)\nlowpassFsection.SKiDl(net_inter, gnd, net_out, gnd)\n\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[47]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RC Band pass Filter Responce');\n\n\n# Becouse this is a cascaded filter to get the symbolic filter we need to casade them where for a recap of how to cascade filters in all the varies toplogies see https://x-engineer.org/graduate-engineering/signals-systems/control-systems/transfer-function-algebra/\n\n# In[48]:\n\n\ncascade_tf=highpassFsection.get_tf() * lowpassFsection.get_tf() \nsym.sympify(cascade_tf)\n\n\n# And so for the sake of simplicity we will just reimpliment `qfilter_explorer.symbolic_tf` manulay here to compare the casdacded symbolic trnasfer fuction to the SPICE simulated results\n\n# In[49]:\n\n\nsymbolic_data=pd.DataFrame(index=filter_responce.ac_resultsNB_DF.index)\nf=symbolic_data.index.values\n\n##bring the f through the sausage filter\nsymbolic_data_raw=cascade_tf.frequency_response(f).astype('complex')\n\nsymbolic_data['Out_sym_[V][dB]']=20*np.log10(np.abs(symbolic_data_raw))\nsymbolic_data['Out_sym_[V][deg]']=np.angle(symbolic_data_raw, deg=True)\n\nfig, [ax_mag, ax_ph]=plt.subplots(nrows=2, ncols=1)\n\nacplot=eecomplex_plot_templets()\nacplot.bode_plot_two_templet(filter_responce.ac_sim_mag_DF.index, filter_responce.ac_sim_mag_DF['Out_[V][dB]'], filter_responce.ac_sim_phase_DF['Out_[V][deg]'], \n title='Simulated vs Symbolic Out_[V]', axs=[ax_mag, ax_ph])\n\n#add the symbolic data\nax_mag.semilogx(f, symbolic_data['Out_sym_[V][dB]'], linestyle='-.' , alpha=0.5, label='symbolic')\nax_mag.legend()\n\nax_ph.semilogx(f, symbolic_data['Out_sym_[V][deg]'], color='orange' , alpha=0.75, label='symbolic')\nax_ph.legend();\n\n\n# # Second-Order Filters and resonators\n# Second-order filters are mostly designed around the following equations in their circuit implementation \n# \n# - Bandwidth ($B$):$B=\\omega_2-\\omega_1$\n# - Center Frequncy ($\\omega_0$): $\\omega_0=\\dfrac{1}{\\sqrt{LC}}=\\sqrt{\\omega_1 \\omega_2}$\n# - The Q Factor in general: $Q=\\dfrac{\\omega_0}{B}$\n# - Q for a series RLC is: $Q=\\dfrac{1}{\\omega_0 RC}$\n# - Q for a parrel RLC is: $Q=\\omega_0 RC$\n# \n# \tAnd are called second-order since with having both a Capacitor and Inductor the differential equations in the time domain become second order. Below we will implement the four main second-order filter types: Lowpass, Highpass, Bandpass, Bandstop, in both their series and parral configurations. Where the templet around the values for the RLC elements used for these filters is the bandwidth frequencies of the ALL ABOUT CIRCUITS example of a passive cascaded filter above using a 50Ohm resistor, because.\n\n# ## Series Based¶\n\n# In[50]:\n\n\nV_out, V_in, angfreq_1, angfreq_2, angfreq_0, R_sym, C_sym, L_sym, Q_sym, f_sym, f0_sym, B_sym=sym.symbols('V_{out}, V_{in}, omega_1, omega_2, omega_0, R, C, L, Q, f, f_0, B' )\nV_out, V_in, angfreq_1, angfreq_2, angfreq_0, R_sym, C_sym, L_sym, Q_sym, f_sym, f0_sym, B_sym\n\n\n# In[51]:\n\n\nf1=10.61e3; f2=106.1e3\nsubs={R_sym:50}\nsubs[angfreq_1]=2*np.pi*f1; subs[angfreq_2]=2*np.pi*f2\nsubs[angfreq_0]=np.sqrt(subs[angfreq_1]*subs[angfreq_2])\nsubs[B_sym]=subs[angfreq_2]-subs[angfreq_1]\nsubs[Q_sym]=subs[angfreq_0]/subs[B_sym]\nsubs\n\n\n# In[52]:\n\n\nQs_eq=sym.Eq(Q_sym, 1/(angfreq_0*R_sym*C_sym)); Qs_eq\n\n\n# In[53]:\n\n\nsubs[C_sym]=sym.solve(Qs_eq, C_sym)[0].subs(subs); subs\n\n\n# In[54]:\n\n\nangfreq_0_eq=sym.Eq(angfreq_0, 1/sym.sqrt(L_sym*C_sym)); angfreq_0_eq\n\n\n# In[55]:\n\n\nsubs[L_sym]=sym.solve(angfreq_0_eq, L_sym)[0].subs(subs); subs\n\n\n# ### RLC series lowpass\n\n# In[56]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_series_lowpass filter class\n#class with lcapy and skidl subcircuit to create an RLC series lowpass filter\n\nclass rlc_series_lowpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n lowpass series RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_Lowpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC series lowpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, self.l[1]\n self.l[2]+=term_2, self.c['p']\n self.c['n']+=term_1, term_3\n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=3')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add('R 0_1 N1; right')\n self.schematic.add('L N1 2_1; right')\n self.schematic.add('C 2_1 1_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[57]:\n\n\n#instatate the rlc_lowpass filter \nlowpassRLC_s=rlc_series_lowpass(L_value=8.33e-5@u_H, C_value=2.7e-7@u_F, R_value=50@u_Ohm)\nlowpassRLC_s.lcapy_self()\n\n\n# In[58]:\n\n\n#get this filters abstract transfer function\nlowpassRLC_s.get_tf(with_values=False)\n\n\n# In[59]:\n\n\n#get this filters transfer function\nlowpassRLC_s.get_tf(with_values=True)\n\n\n# In[60]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nlowpassRLC_s.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[61]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Series Lowpass Filter Responce');\n\n\n# In[62]:\n\n\nfilter_responce.symbolic_tf(lowpassRLC_s)\n\n\n# ### RLC series highpass\n\n# In[63]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_series_highpass filter class\n#class with lcapy and skidl subcircuit to create an RLC series highpass filter\n\nclass rlc_series_highpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n highpass series RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_highpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC series highpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, self.c['p']\n self.c['n']+=term_2, self.l[1]\n self.l[2]+=term_1, term_3\n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=3')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'R 0_1 N1; right')\n self.schematic.add(f'C N1 2_1; right')\n self.schematic.add(f'L 2_1 1_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[64]:\n\n\n#instatate the rlc_highpass filter \nhighpassRLC_s=rlc_series_highpass(L_value=8.33e-5@u_H, C_value=2.7e-7@u_F, R_value=50@u_Ohm)\nhighpassRLC_s.lcapy_self()\n\n\n# In[65]:\n\n\n#get this filters abstract transfer function\nhighpassRLC_s.get_tf(with_values=False)\n\n\n# In[66]:\n\n\n#get this filters transfer function\nhighpassRLC_s.get_tf(with_values=True)\n\n\n# In[67]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nhighpassRLC_s.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[68]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Series Lowpass Filter Responce');\n\n\n# In[69]:\n\n\nfilter_responce.symbolic_tf(highpassRLC_s)\n\n\n# ### RLC series bandpass\n\n# In[70]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_series_bandpass filter class\n#class with lcapy and skidl subcircuit to create an RLC series bandpass filter\n\nclass rlc_series_bandpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n bandpass series RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_bandpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC series bandpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.l[1, 2]+=term_0, self.c['p']\n self.c['n']+=term_2, self.r[1]\n self.r[2]+=term_1, term_3\n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=3')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'L 0_1 N1; right')\n self.schematic.add(f'C N1 2_1; right')\n self.schematic.add(f'R 2_1 1_1; down')\n \n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[71]:\n\n\n#instatate the rlc_bandpass filter \nbandpassRLC_s=rlc_series_bandpass(L_value=8.33e-5@u_H, C_value=2.7e-7@u_F, R_value=50@u_Ohm)\nbandpassRLC_s.lcapy_self()\n\n\n# In[72]:\n\n\n#get this filters abstract transfer function\nbandpassRLC_s.get_tf(with_values=False)\n\n\n# In[73]:\n\n\n#get this filters transfer function\nbandpassRLC_s.get_tf(with_values=True)\n\n\n# In[74]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nbandpassRLC_s.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[75]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Series Bandpass Filter Responce');\n\n\n# In[76]:\n\n\nfilter_responce.symbolic_tf(bandpassRLC_s)\n\n\n# ### RLC series bandstop\n\n# In[77]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_series_bandstop filter class\n#class with lcapy and skidl subcircuit to create an RLC series bandstop filter\n\nclass rlc_series_bandstop():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n bandstop series RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_bandstop - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC series bandstop filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, term_2\n self.l[1, 2]+=self.r[2], self.c['p']\n self.c['n']+=term_1, term_3\n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=2')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'R 0_1 2_1; right')\n self.schematic.add(f'L 2_1 N1; down')\n self.schematic.add(f'C N1 1_1; down')\n \n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 1_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[78]:\n\n\n#instatate the rlc_bandstop filter\nbandstopRLC_s=rlc_series_bandstop(L_value=8.33e-5@u_H, C_value=2.7e-7@u_F, R_value=50@u_Ohm)\nbandstopRLC_s.lcapy_self()\n\n\n# In[79]:\n\n\n#get this filters abstract transfer function\nbandstopRLC_s.get_tf(with_values=False)\n\n\n# In[80]:\n\n\n#get this filters transfer function\nbandstopRLC_s.get_tf(with_values=True)\n\n\n# In[81]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nbandstopRLC_s.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[82]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Series Bandstop Filter Responce');\n\n\n# In[83]:\n\n\nfilter_responce.symbolic_tf(bandstopRLC_s)\n\n\n# ## Parallel Based¶\n\n# In[84]:\n\n\nV_out, V_in, angfreq_1, angfreq_2, angfreq_0, R_sym, C_sym, L_sym, Q_sym, f_sym, f0_sym, B_sym=sym.symbols('V_{out}, V_{in}, omega_1, omega_2, omega_0, R, C, L, Q, f, f_0, B' )\nV_out, V_in, angfreq_1, angfreq_2, angfreq_0, R_sym, C_sym, L_sym, Q_sym, f_sym, f0_sym, B_sym\n\n\n# In[85]:\n\n\nf1=10.61e3; f2=106.1e3\nsubs={R_sym:50}\nsubs[angfreq_1]=2*np.pi*f1; subs[angfreq_2]=2*np.pi*f2\nsubs[angfreq_0]=np.sqrt(subs[angfreq_1]*subs[angfreq_2])\nsubs[B_sym]=subs[angfreq_2]-subs[angfreq_1]\nsubs[Q_sym]=subs[angfreq_0]/subs[B_sym]\nsubs\n\n\n# In[86]:\n\n\nQp_eq=sym.Eq(Q_sym, angfreq_0*R_sym*C_sym); Qp_eq\n\n\n# In[87]:\n\n\nsubs[C_sym]=sym.solve(Qp_eq, C_sym)[0].subs(subs); subs\n\n\n# In[88]:\n\n\nangfreq_0_eq=sym.Eq(angfreq_0, 1/sym.sqrt(L_sym*C_sym)); angfreq_0_eq\n\n\n# In[89]:\n\n\nsubs[L_sym]=sym.solve(angfreq_0_eq, L_sym)[0].subs(subs); subs\n\n\n# ### RLC parallel lowpass \n\n# In[90]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_parallel_lowpass filter class\n#class with lcapy and skidl subcircuit to create an RLC parallel lowpass filter\n\nclass rlc_parallel_lowpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n lowpass parallel RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_Lowpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC parallel lowpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.l[1, 2]+=term_0, term_2\n self.c['p', 'n']+=term_2, term_1\n self.r[1, 2]+=term_2, term_3\n self.c['n']+=self.r[2]\n \n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=2')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'L 0_1 2_2; right')\n self.schematic.add(f'C 2_2 1_1; down')\n self.schematic.add('W 2_2 2_1; right')\n self.schematic.add('W 1_1 3_1; right')\n self.schematic.add(f'R 2_1 3_1; down')\n\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 3_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[91]:\n\n\n#instatate the rlc_lowpass filter \nlowpassRLC_p=rlc_parallel_lowpass(L_value=.0006750@u_H, C_value=3.33e-8@u_F, R_value=50@u_Ohm)\nlowpassRLC_p.lcapy_self()\n\n\n# In[92]:\n\n\n#get this filters abstract transfer function\nlowpassRLC_p.get_tf(with_values=False)\n\n\n# In[93]:\n\n\n#get this filters transfer function\nlowpassRLC_p.get_tf(with_values=True)\n\n\n# In[94]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nlowpassRLC_p.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[95]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Parallel Lowpass Filter Responce');\n\n\n# In[96]:\n\n\nfilter_responce.symbolic_tf(lowpassRLC_p)\n\n\n# ### RLC parallel highpass \n\n# In[97]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_parallel_highpass filter class\n#class with lcapy and skidl subcircuit to create an RLC parallel highpass filter\n\nclass rlc_parallel_highpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n highpass parallel RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_highpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC parallel highpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.c['p', 'n']+=term_0, term_2\n self.r[1, 2]+=term_2, term_1\n self.l[1, 2]+=term_2, term_3\n self.l[2]+=self.r[2]\n \n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=2')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'C 0_1 2_2; right')\n self.schematic.add(f'R 2_2 1_1; down')\n self.schematic.add('W 2_2 2_1; right')\n self.schematic.add('W 1_1 3_1; right')\n self.schematic.add(f'L 2_1 3_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 3_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[98]:\n\n\n#instatate the rlc_highpass filter\nhighpassRLC_p=rlc_parallel_highpass(L_value=.0006750@u_H, C_value=3.33e-8@u_F, R_value=50@u_Ohm)\nhighpassRLC_p.lcapy_self()\n\n\n# In[99]:\n\n\n#get this filters abstract transfer function\nhighpassRLC_p.get_tf(with_values=False)\n\n\n# In[100]:\n\n\n#get this filters transfer function\nhighpassRLC_p.get_tf(with_values=True)\n\n\n# In[101]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nhighpassRLC_p.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[102]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Parallel Highpass Filter Responce');\n\n\n# In[103]:\n\n\nfilter_responce.symbolic_tf(highpassRLC_p)\n\n\n# ### RLC parallel bandpass \n\n# In[104]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_parallel_bandpass filter class\n#class with lcapy and skidl subcircuit to create an RLC parallel bandpass filter\n\nclass rlc_parallel_bandpass():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n bandpass parallel RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_bandpass - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC parallel bandpass filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.r[1, 2]+=term_0, term_2\n self.c['p', 'n']+=term_2, term_1\n self.l[1, 2]+=term_2, term_3\n self.l[2]+=self.c['n']\n \n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 1_1; right=2')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add(f'R 0_1 2_2; right')\n self.schematic.add(f'C 2_2 1_1; down')\n self.schematic.add('W 2_2 2_1; right')\n self.schematic.add('W 1_1 3_1; right')\n self.schematic.add(f'L 2_1 3_1; down')\n \n self.schematic.add('W 2_1 2; right=1.5')\n self.schematic.add('W 3_1 3; right=1.5')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[105]:\n\n\n#instatate the rlc_bandpass filter\nbandpassRLC_p=rlc_parallel_bandpass(L_value=.0006750@u_H, C_value=3.33e-8@u_F, R_value=50@u_Ohm)\nbandpassRLC_p.lcapy_self()\n\n\n# In[106]:\n\n\n#get this filters abstract transfer function\nbandpassRLC_p.get_tf(with_values=False)\n\n\n# In[107]:\n\n\n#get this filters transfer function\nbandpassRLC_p.get_tf(with_values=True)\n\n\n# In[108]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nbandpassRLC_p.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[109]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Parallel Bandpass Filter Responce');\n\n\n# In[110]:\n\n\nfilter_responce.symbolic_tf(bandpassRLC_p)\n\n\n# ### RLC parallel bandstop\n\n# In[111]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 rlc_parallel_bandstop filter class\n#class with lcapy and skidl subcircuit to create an RLC parallel bandstop filter\n\nclass rlc_parallel_bandstop():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n bandstop parallel RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L_value=1@u_H, C_value=1@u_F, R_value=1@u_Ohm):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L_value (float; 1@u_F; Henerys): the inductance in farads for the RLC inductive element\n C_value (float; 1@u_F; Farads): the capacitance in farads for the RLC capacitive element\n R_value (float; 1@u_Ohm; Ohms): the resistance in ohms for the RLC resistive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L_value=L_value\n self.C_value=C_value\n self.R_value=R_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_bandstop - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC parallel bandstop filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n Lref={'ref':f'L_{self.subcirc_ref}'}\n Cref={'ref':f'C_{self.subcirc_ref}'}\n Rref={'ref':f'R_{self.subcirc_ref}'}\n else:\n Lref={}\n Cref={}\n Rref={}\n \n self.l=L(value=self.L_value, **Lref)\n self.c=C(value=self.C_value, **Cref)\n self.r=R(value=self.R_value, **Rref)\n \n self.c['p', 'n']+=term_0, term_2\n self.l[1, 2]+=term_0, term_2\n self.r[1, 2]+=term_2, term_3\n self.r[2]+=term_1\n \n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - get the Vin statement into the schematic\n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n self.schematic.add('W 0 0_1; right')\n self.schematic.add('W 1 3_1; right=3.5')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n self.schematic.add('W 0_1, 0_2; up=.3')\n self.schematic.add(f'L 0_2 2_3; right')\n self.schematic.add('W 2_3 2_2; down=.3')\n \n self.schematic.add('W 0_1, 0_3; down=.3')\n self.schematic.add(f'C 0_3 2_4; right')\n self.schematic.add('W 2_4 2_2; up=.3')\n\n self.schematic.add(f'R 2_1 3_1; down')\n\n \n self.schematic.add('W 2_2 2_1; right')\n self.schematic.add('W 2_1 2; right')\n self.schematic.add('W 3_1 3; right')\n self.schematic.add('P2 2 3; down, v=V_o')\n \n if with_values:\n self.schematic=self.schematic.subs({'R':self.R_value, 'L':self.L_value, 'C':self.C_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# In[112]:\n\n\n#instatate the rc_bandpass filter to \nbandstopRLC_p=rlc_parallel_bandstop(L_value=.0006750@u_H, C_value=3.33e-8@u_F, R_value=50@u_Ohm)\nbandstopRLC_p.lcapy_self()\n\n\n# In[113]:\n\n\n#get this filters abstract transfer function\nbandstopRLC_p.get_tf(with_values=False)\n\n\n# In[114]:\n\n\n#get this filters transfer function\nbandstopRLC_p.get_tf(with_values=True)\n\n\n# In[115]:\n\n\nreset()\n#create the nets\nnet_in=Net('In'); net_out=Net('Out'); \n\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\nbandstopRLC_p.SKiDl(net_in, gnd, net_out, gnd)\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# In[116]:\n\n\nfilter_responce=qfilter_explorer(circ, 'RLC Parallel Bandstop Filter Responce');\n\n\n# In[117]:\n\n\nfilter_responce.symbolic_tf(bandstopRLC_p)\n\n\n# # All Pass filters\n\n# The naming of filters as has been seen is based on the shape of the Bode Magnitude Plot and for the most part, Phase has kind of been a ride along part of the filter design. Stating that, the name for an All-Pass filter is misleading; the better name is a Phase Shaping filter. These Filters ideally do not affect the magnitude of the signal passed through them and instead affect the phase. Here we will look at the lattice All-Pass filter for the low-frequency phase from the following Wikipedia article \n# \n# https://en.wikipedia.org/wiki/Lattice_phase_equaliser\n# \n\n# In[118]:\n\n\n#%%writefile -a AC_2_Codes.py\n#chapteer 2 section 2 lc_balanced_allpass_lowfreq_lattice_filt filter class\n#class with lcapy and skidl subcircuit to create an lc all-pass filter\n\nclass lc_balanced_allpass_lowfreq_lattice_filt():\n \"\"\"\n holding class for SkiDl subcircuit and lcapy schematic of a\n bandstop parallel RLC filter primitive\n \"\"\"\n \n def __init__(self, subcirc_ref=None, L1_value=1@u_H, L2_value=1@u_H, C1_value=1@u_F, C2_value=1@u_F):\n \"\"\"\n Args:\n subcirc_ref (str): reference to use for the base of the internal elements\n L1_value (float; 1@u_F; Henerys): the inductance in farads for the top inductive element\n L2_value (float; 1@u_F; Henerys): the inductance in farads for the bottom inductive element\n C1_value (float; 1@u_F; Farads): the capacitance in farads for the term 2 to term 1 capacitive element\n C2_value (float; 1@u_F; Farads): the capacitance in farads for the term 0 to term 2 capacitive element\n\n Returns:\n None\n TODO:\n -add assertions\n \"\"\"\n #add assertions\n self.subcirc_ref=subcirc_ref\n self.L1_value=L1_value\n self.L2_value=L2_value\n self.C1_value=C1_value\n self.C2_value=C2_value\n \n\n @subcircuit\n def SKiDl(self, term_0, term_1, term_2, term_3, return_elements=False):\n \"\"\"\n Terminals:\n term_0, term_1, term_2, term_3\n \n Terminals are defined via:\n ```\n Left_Termanals - RLC_s_bandstop - Right_Termanals\n +----+ \n Postive V_i term_0-|0 2|-term_2 Postive V_o\n Negtive V_i term_1-|1 3|-term_3 Negtive V_o\n +----+\n ```\n \n Args:\n return_internls (bool; False): If True return out the internal Voltage Source,\n and Resistance objects in this package\n Returns:\n Returns elements to circuit RLC parallel bandstop filter part element object and if `return_internls`\n is True will return the internal voltage and resistance objects in that order \n \"\"\"\n if self.subcirc_ref!=None:\n L1ref={'ref':f'L_{self.subcirc_ref}1'}\n L2ref={'ref':f'L_{self.subcirc_ref}2'}\n\n C1ref={'ref':f'C_{self.subcirc_ref}1'}\n C2ref={'ref':f'C_{self.subcirc_ref}2'}\n else:\n L1ref={}\n L2ref={}\n \n C1ref={}\n C2ref={}\n \n self.l1=L(value=self.L1_value, **L1ref)\n self.l2=L(value=self.L2_value, **L2ref)\n\n self.c1=C(value=self.C1_value, **C1ref)\n self.c2=C(value=self.C2_value, **C2ref)\n \n \n term_0+=self.l1[1], self.c2['p']\n term_1+=self.l2[1], self.c1['n']\n term_2+=self.l1[2], self.c1['p']\n term_3+=self.l2[2], self.c2['n'] \n \n \n \n \n if return_elements:\n return self.c, self.r, self.l\n \n def lcapy_self(self, draw_me=True, with_values=True):\n \"\"\"\n Creates a lcapy schematic of this classes filter that\n can be used for amongst other things: draw a basic schematic\n of this class filter, extract the transfer function, \n exstract the 2Port Repersntation\n \n Args:\n draw_me (bool): will draw a schematic of this classes filter schematic\n \n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n Return:\n the lcapys circuit object is stored in `self.schematic` and will\n have abstract sympy variable for the elements if `with_values` is False\n and will draw the schematic of just this classes filter if `draw_me` is True\n \n TODO:\n - must draw this better\n - get the Vin statement into the schematic\n \n \n \"\"\"\n \n self.schematic=kiwi.Circuit()\n \n self.schematic=kiwi.Circuit()\n #self.schematic.add('W 0 0; right')\n #self.schematic.add('W 1 3; right=3.5')\n #self.schematic.add('P1 0 1; down, v=V_i')\n \n #It ant pretty but it works\n self.schematic.add('W 0 0_3; right')\n self.schematic.add(f'L1 0_3 2_2; right')\n self.schematic.add('W 2_2 2; right')\n\n self.schematic.add('W 0 0_2; rotate=-45')\n self.schematic.add(f'C2 0_2 3; rotate=-45')\n \n self.schematic.add(f'C1 2 1_2; rotate=225')\n self.schematic.add(f'W 1_2 1; rotate=225')\n \n self.schematic.add('W 1 1_3; right')\n self.schematic.add(f'L2 1_3 3_2; right=2')\n self.schematic.add('W 3_2 3; right')\n\n \n if with_values:\n self.schematic=self.schematic.subs({'L1':self.L1_value, 'L2':self.L2_value, \n 'C1':self.C1_value, 'C2':self.C2_value})\n \n if draw_me:\n self.schematic.draw()\n \n def get_tf(self, with_values=True, ZPK=True):\n \"\"\"\n will extract the symbolic transfer function for this filter\n \n Args:\n with_values (bool): will push the filters element values into\n the resulting lcapy circuit object in place of abstract sympy variables\n \n ZPK (bool): if True will try to return the TF in zero-pole-gain form\n else will try to return the TF in canonical form \n where the unity coefficient is the highest power of the denominator\n \n \"\"\"\n self.lcapy_self(draw_me=False, with_values=with_values)\n self.tf=self.schematic.transfer(0, 1, 2, 3)\n \n if ZPK:\n return self.tf.ZPK()\n else:\n return self.tf.canonical()\n \n def get_twoPort(self, network_rep='Y', with_values=True):\n \"\"\"\n Gets the 2Port network representation of this filter.\n The 2Port representation can be controlled\n \n Args:\n network_rep (str; 'Y'): control string for what\n representation is used to choose from:\n \n 'Z': two-port Z-parameters matrix\n 'Y': two-port Y-parameters matrix\n 'H': two-port H-parameters matrix\n 'G': two-port G-parameters matrix\n 'ABCD': two-port A-parameters matrix\n 'invABCD': two-port B-parameters matrix\n 'S': two-port S-parameters matrix\n 'T': two-port T-parameters matrix\n \n \n \"\"\"\n \n self.lcapy_self(draw_me=False, with_values=with_values)\n \n #create an action dict to get the 2P rep\n rep_actions={\n 'Z':lambda x: x.Zparams(0, 1, 2, 1),\n 'Y':lambda x: x.Yparams(0, 1, 2, 1), \n 'H':lambda x: x.Hparams(0, 1, 2, 1),\n 'G':lambda x: x.Gparams(0, 1, 2, 1),\n 'ABCD':lambda x: x.Aparams(0, 1, 2, 1),\n 'invABCD':lambda x: x.Bparams(0, 1, 2, 1),\n 'S':lambda x: x.Sparams(0, 1, 2, 1),\n 'T':lambda x: x.Tparams(0, 1, 2, 1),\n }\n \n assert network_rep in rep_actions.keys(), f'`{network_rep}` is not 2Port rep'\n \n return rep_actions[network_rep](self.schematic)\n\n\n# If you're wondering what a lattice filter is, the fact of the matter is that you have seen them before in terms of bridge circuits. See the following Wikipedia article on Lattice Networks \n# \n# https://www.eeeguide.com/wp-content/uploads/2019/11/Lattice-Network.jpg\n# \n\n# In[119]:\n\n\n#instatate the allpass latice filter to \nallpasslat_lf=lc_balanced_allpass_lowfreq_lattice_filt()\nallpasslat_lf.lcapy_self()\n\n\n# In[120]:\n\n\n#get this filters abstract transfer function\nallpasslat_lf.get_tf(with_values=False)\n\n\n# In[121]:\n\n\n#get this filters transfer function\nallpasslat_lf.get_tf(with_values=True)\n\n\n# In[122]:\n\n\nreset()\n#create the nets; the last one is needed to deal with singularity issues when dealing with lattice circuits and ground\nnet_in=Net('In'); net_out=Net('Out'); net_outlower=Net('Out2')\n#create a 1V AC test source and attache to nets\nvs=SINEV(ac_magnitude=1@u_V); vs['p', 'n']+=net_in, gnd\n#net_in+=dummy_1[2]\n\n#attaceh term_0 to net_in and term_2 to net_out per scikit-rf convention all \n#other terminals are grounded\n#but need to add dummy resistors to deal with singular issues and get solvable matric\ndummy_botin=R(value=0, ref='dummy')\ndummy_botin[1]+=gnd\n\ndummy_botout=R(value=0, ref='dummy')\ndummy_botout[2]+=gnd\nallpasslat_lf.SKiDl(net_in, dummy_botin[2], net_out, dummy_botout[1])\n\ncirc=generate_netlist()\nprint(circ)\n\n\n# The `dummy_bot*` resistors that are in the simulation are needed in order for SPICE to no longer throw a singular matrix error. Where the test circuit is drawn below. This might not be needed if the output (terminal 3) of the lattice filter was allowed to float. Floating circuits will be discussed in the next section on transformers in detail. Here all inputs and outputs will be referenced to ground.\n\n# In[123]:\n\n\nlat_testcir=kiwi.Circuit()\n\nlat_testcir.add('Vs In 0; down')\nlat_testcir.add('W 0 0_1; down=0.2, sground')\n\nlat_testcir.add('W In U1.l1; right')\nlat_testcir.add('Rdummy 0 U1.l2; right, l=0Ohm')\n\nlat_testcir.add('U1 chip2121; right, l={latice}, pinlabels={l1=0,l2=1, r1=2,r2=3}')\n\nlat_testcir.add('W U1.r1 Out; right')\nlat_testcir.add('Rdummy_1 U1.r2 Out2; right, l=0Ohm')\nlat_testcir.add('W Out2 Out2_1; down=0.2, sground')\n\n\n\nlat_testcir.draw()\n\n\n# In[124]:\n\n\nfilter_responce=qfilter_explorer(circ, 'LC All-Pass Low Frequcy Lattice Filter');\n\n\n# In[125]:\n\n\nfilter_responce.symbolic_tf(allpasslat_lf)\n\n\n# The reason it's diverging and more specifically flipped in phase might be due to how lcapy is treating the `0` as ground when it formulates the modified nodal analysis. As seen below with the lack of a `V_3` term. Going to pass on fixing this right now but it is top of the TODO list for this section\n\n# In[126]:\n\n\nallpasslat_lf.lcapy_self(False, False)\n#also wont convert to laplace\nn=kiwi.NodalAnalysis(allpasslat_lf.schematic)\nn.nodal_equations()\n\n\n# ## Citations:\n# \n# [1] ALL ABOUT ELECTRONICS. \"RC Low Pass Filter Explained,\" YouTube, Aug 20, 2017. [Video file]. Available: https://youtu.be/_2L0l-E1Wx0. [Accessed: Nov 30, 2020].\n# \n# [2] ALL ABOUT ELECTRONICS. \"RC High Pass Filter Explained,\" YouTube, Aug 23, 2017. [Video file]. Available: https://youtu.be/9Dx0b0ukNAM. [Accessed: Nov 30, 2020].\n# \n# [3] ALL ABOUT ELECTRONICS. \"Band Pass Filter and Band Stop Filter Explained,\" YouTube, Sep 2, 2017. [Video file]. Available: https://youtu.be/dmPIydL0lyM. [Accessed: Nov 30, 2020].\n# \n# [4] S. Makarov, R. Ludwig and S. Bitar, Practical electrical engineering. Cham: Springer International Publishing, 2016, pp. 514-515.\n# \n# [5] \"Lattice phase equaliser\", En.wikipedia.org, 2021. [Online]. Available: https://en.wikipedia.org/wiki/Lattice_phase_equaliser. [Accessed: 10- Jan- 2021]. \n# \n# [6] \"Lattice network\", En.wikipedia.org, 2021. [Online]. Available: https://en.wikipedia.org/wiki/Lattice_network. [Accessed: 10- Jan- 2021]. \n# \n# \n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "22f5c013af101afadcce74c233960283f134f022", "size": 143581, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/AC_2/AC_2_RCL_filters.py", "max_stars_repo_name": "PyLCARS/Python-and-SPICE-Book", "max_stars_repo_head_hexsha": "0bf02aa16d97115cea955d33a7aab7e02f8d3453", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-04T23:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T13:22:30.000Z", "max_issues_repo_path": "_build/jupyter_execute/AC_2/AC_2_RCL_filters.py", "max_issues_repo_name": "PyLCARS/Python-and-SPICE-Book", "max_issues_repo_head_hexsha": "0bf02aa16d97115cea955d33a7aab7e02f8d3453", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/AC_2/AC_2_RCL_filters.py", "max_forks_repo_name": "PyLCARS/Python-and-SPICE-Book", "max_forks_repo_head_hexsha": "0bf02aa16d97115cea955d33a7aab7e02f8d3453", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1371849738, "max_line_length": 974, "alphanum_fraction": 0.6081375669, "include": true, "reason": "import numpy,import sympy", "num_tokens": 37186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.18713268216242657, "lm_q1q2_score": 0.08918362836757904}} {"text": "# 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-scheduling matrix multiplication for CPU\n=============================================\n**Author**: `Lianmin Zheng `_, \\\n `Chengfan Jia `_\n\nDifferent from the existing :ref:`autotvm ` which relies on \nmanual templates to define the search space, the auto-scheduler does not require any templates.\nThe auto-scheduler is template-free, so users only need to write the computation declaration without\nany schedule commands or templates.\nThe auto-scheduler can automatically generate a large\nsearch space and find a good schedule in the space.\n\nWe use matrix multiplication as an example in this tutorial.\n\"\"\"\n\nimport numpy as np\nimport tvm\nfrom tvm import te, testing, auto_scheduler\n\n######################################################################\n# Define the computation\n# ^^^^^^^^^^^^^^^^^^^^^^\n# To begin with, let us define the computation of a matmul with bias add.\n# The function should return the list of input/output tensors.\n# From these tensors, the auto-scheduler can get the whole computational graph.\n\n\n@auto_scheduler.register_workload\ndef matmul_add(N, L, M, dtype):\n A = te.placeholder((N, L), name=\"A\", dtype=dtype)\n B = te.placeholder((L, M), name=\"B\", dtype=dtype)\n C = te.placeholder((N, M), name=\"C\", dtype=dtype)\n\n k = te.reduce_axis((0, L), name=\"k\")\n matmul = te.compute((N, M), lambda i, j: te.sum(A[i, k] * B[k, j], axis=k), name=\"matmul\")\n out = te.compute((N, M), lambda i, j: matmul[i, j] + C[i, j], name=\"out\")\n\n return [A, B, C, out]\n\n\n######################################################################\n# Create the search task\n# ^^^^^^^^^^^^^^^^^^^^^^\n# We then create a search task with N=L=M=128 and dtype=\"float32\"\n# If your machine supports avx instructions, you can\n# - replace \"llvm\" below with \"llvm -mcpu=core-avx2\" to enable AVX2\n# - replace \"llvm\" below with \"llvm -mcpu=skylake-avx512\" to enable AVX-512\n\ntarget = tvm.target.Target(\"llvm\")\ntask = auto_scheduler.create_task(matmul_add, (128, 128, 128, \"float32\"), target)\n\n# Inspect the computational graph\nprint(task.compute_dag)\n\n######################################################################\n# Next, we set parameters for the auto-scheduler.\n#\n# * `num_measure_trials` is the number of measurement trials we can use during the search.\n# We only make 10 trials in this tutorial for a fast demonstration. In practice, 1000 is a\n# good value for the search to converge. You can do more trials according to your time budget.\n# * In addition, we use `RecordToFile` to dump measurement records into a file `matmul.json`.\n# The measurement records can be used to query the history best, resume the search,\n# and do more analyses later.\n# * see :any:`auto_scheduler.auto_schedule.TuningOptions`: for more parameters\n\ntune_option = auto_scheduler.TuningOptions(\n num_measure_trials=10, measure_callbacks=[auto_scheduler.RecordToFile(\"matmul.json\")]\n)\n\n######################################################################\n# Run the search\n# ^^^^^^^^^^^^^^\n# Now we get all inputs ready. Pretty simple, isn't it?\n# We can kick off the search and let the auto-scheduler do its magic.\n# After some measurement trials, it will return the best schedule it found.\n\nsch, args = auto_scheduler.auto_schedule(task, tuning_options=tune_option)\n\n######################################################################\n# We can lower the schedule to see the IR after auto-scheduling.\n# The auto-scheduler correctly performs optimizations including multi-level tiling,\n# parallelization, vectorization, unrolling and operator fusion.\n\nprint(tvm.lower(sch, args, simple_mode=True))\n\n######################################################################\n# Check correctness and evaluate performance\n# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# We build the binary and check its correctness and performance.\n\nfunc = tvm.build(sch, args)\na_np = np.random.uniform(size=(128, 128)).astype(np.float32)\nb_np = np.random.uniform(size=(128, 128)).astype(np.float32)\nc_np = np.random.uniform(size=(128, 128)).astype(np.float32)\nout_np = a_np.dot(b_np) + c_np\n\nctx = tvm.cpu()\na_tvm = tvm.nd.array(a_np, ctx=ctx)\nb_tvm = tvm.nd.array(b_np, ctx=ctx)\nc_tvm = tvm.nd.array(c_np, ctx=ctx)\nout_tvm = tvm.nd.empty(out_np.shape, ctx=ctx)\nfunc(a_tvm, b_tvm, c_tvm, out_tvm)\n\n# Check results\ntvm.testing.assert_allclose(out_np, out_tvm.asnumpy(), rtol=1e-3)\n\n# Evaluate execution time.\nevaluator = func.time_evaluator(func.entry_name, ctx, min_repeat_ms=500)\nprint(\n \"Execution time of this operator: %.3f ms\"\n % (np.median(evaluator(a_tvm, b_tvm, c_tvm, out_tvm).results) * 1000)\n)\n\n\n######################################################################\n# Using the record file\n# ^^^^^^^^^^^^^^^^^^^^^\n# During the search, all measuremnt records are dumpped into the record\n# file \"matmul.json\". The measurement records can be used to re-apply search results,\n# resume the search, and perform other analyses.\n\n######################################################################\n# Here is an example where we load the best schedule from a file,\n# print the equivalent python schedule API, and build the binary again.\n\n# Load the measuremnt record for the best schedule\ninp, res = auto_scheduler.load_best(\"matmul.json\", task.workload_key)\n\n# Print equivalent python schedule API. This can be used for debugging and\n# learning the behavior of the auto-scheduler.\nprint(\"Equivalent python schedule:\")\nprint(task.compute_dag.print_python_code_from_state(inp.state))\n\n# Rebuild the binary. This shows how you can apply the best schedule from a\n# log file without reruning the search again.\nsch, args = task.compute_dag.apply_steps_from_state(inp.state)\nfunc = tvm.build(sch, args)\n\n######################################################################\n# A more complicated example is to resume the search.\n# In this case, we need to create the search policy and cost model by ourselves\n# and resume the status of search policy and cost model with the log file.\n# In the example below we resume the status and do more 5 trials.\n\n\ndef resume_search(task, log_file):\n cost_model = auto_scheduler.XGBModel()\n cost_model.update_from_file(log_file)\n search_policy = auto_scheduler.SketchPolicy(\n task, cost_model, init_search_callbacks=[auto_scheduler.PreloadMeasuredStates(log_file)]\n )\n tune_option = auto_scheduler.TuningOptions(\n num_measure_trials=5, measure_callbacks=[auto_scheduler.RecordToFile(log_file)]\n )\n sch, args = auto_scheduler.auto_schedule(task, search_policy, tuning_options=tune_option)\n\n\n# resume_search(task, \"matmul.json\")\n\n######################################################################\n# .. note::\n# We cannot run the line above because of the conflict between\n# python's multiprocessing and tvm's thread pool.\n# After running a tvm generated binary the python's multiprocessing library\n# will hang forever. You have to make sure that you don't run any tvm\n# generated binaries before calling auot-scheduler's search.\n# To run the function above, you should comment out all code in\n# \"Check correctness and evaluate performance\" section.\n#\n# You should be careful about this problem in your applications.\n# There are other workarounds for this problem.\n# For example, you can start a new thread/process (with the builtin python library\n# threading or multiprocessing) and run the tvm binaries in the new thread/process.\n# This provides an isolation and avoids the conflict in the main thread/process.\n# You can also use :any:`auto_scheduler.measure.LocalRPCMeasureContext` for auto-scheduler,\n# as shown in the GPU tutorial (:ref:`auto-scheduler-conv-gpu`).\n", "meta": {"hexsha": "918030d21e54c95897a493609612cd0f9e0d0352", "size": 8546, "ext": "py", "lang": "Python", "max_stars_repo_path": "tutorials/auto_scheduler/tune_matmul_x86.py", "max_stars_repo_name": "ThunderDboss/incubator-tvm", "max_stars_repo_head_hexsha": "8de10e328e8480b55c140ee818a4e6c7df814bdd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/auto_scheduler/tune_matmul_x86.py", "max_issues_repo_name": "ThunderDboss/incubator-tvm", "max_issues_repo_head_hexsha": "8de10e328e8480b55c140ee818a4e6c7df814bdd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/auto_scheduler/tune_matmul_x86.py", "max_forks_repo_name": "ThunderDboss/incubator-tvm", "max_forks_repo_head_hexsha": "8de10e328e8480b55c140ee818a4e6c7df814bdd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-08T07:08:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T07:08:04.000Z", "avg_line_length": 44.0515463918, "max_line_length": 100, "alphanum_fraction": 0.6748186286, "include": true, "reason": "import numpy", "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.1801066618860355, "lm_q1q2_score": 0.08794309238111231}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport scipy.special as sci\nimport matplotlib.pyplot as plt\nfrom scipy import stats # linregress\nimport pandas as pd\nfrom IPython.display import Latex\n\n\n# # Lecture 11: Background of Groundwater Modeling\n# \n# \n# _(The contents presented in this section were re-developed principally by Dr. P. K. Yadav. The original contents are from Prof. Rudolf Liedl)_\n# \n# ---\n# \n# ## Motivation ### \n# \n# This lecture introduces the realm of mathematical modeling realm in groundwater studies. In the previous lectures the fundamental quantities, their properties and approach to quantify them were discussed. Those information were then used to develop system equations for varieties of groundwater problems. It was discussed then that these system equations require mathematical approaches the theory for which have to be systematically discussed and understood. Groundwater modeling can then be described as the systematic use of mathematical approaches leading to solution of the groundwater problem.\n# \n# \n# Groundwater modeling is often the first step towards understanding and solving groundwater problems/issues. Groundwater modeling is a very broad topic, this and the following lectures only introduces fundamental part of groundwater modeling. In this course we focus on groundwater flow problems.\n\n# ## Introduction ##\n# \n# ### What is a Model? ###\n# \n# Very succinctly a **model** is a representation, which may be an image or a description of a real system. The description can be of different form (e.g., scales), of different level of detail (e.g., conceptual versus mathematical). The **system** to be modeled can be a **real** or also **conceptual**. A very relevant example of a real system for this course is the Darcy's experiment (see figure below), in which water is made to flow through the porous media.\n# \n# \n# ```{figure} images/M11_f1.png\n# ---\n# scale: 60%\n# align: center\n# name: Darcy\n# ---\n# Darcy's experimental setup[^Darcy(1856)]\n# ```\n# With Darcy's experiment, one could set-up a mathematical model to relate flow rate and hydraulic gradient ($h$). As model is _only an image_ of the real system, several assumptions have to be made in it's development. At many instances the model can not be set without these assumptions. In other cases solution of the model may not be possible without these assumptions being part of the model development. Darcy‘s Law, for instance, does not provide an exact representation of flow through individual pore channels. Rather, **average** flow behaviour through **many** pore channels is represented.\n# \n# \n# [^Darcy(1856)]: Darcy, H., Les Fontaines Publiques de la Ville de Dijon, Dalmont, Paris, 1856.\n# \n\n# ### Model Types: Process-Based and Empirical Models ### \n# \n# Model can be classified in many ways. The following two types of classification are a more general way to classify models:\n# \n# > 1. **Conceptual models**\n# \n# > 2. **Process-Based and Empirical Models**\n# \n# > 3. **Mathematical models**\n# \n# #### Conceptual models ####\n# \n# The **conceptual models** is classification of models that distinguishes the qualitative from the quantitative description of a real system. A **conceptual model** provides a qualitative representation of the relevant system components, processes, and impacts in the area of investigation. This representation is usually shown graphically, e.g., as block models (see figure {ref}`Cmodel`). It will be shown later that conceptual model in fact is the first block in the development of a mathematical model. \n# \n# ```{figure} images/M11_f3.png\n# ---\n# scale: 20%\n# align: center\n# name: Cmodel\n# ---\n# A conceptual model showing different components of a hydrological system that can impact groundwater.\n# ```\n# \n# \n# #### Physically based models and Empirical models ####\n# \n# The **physically based models** also referred to as **process-based** models are models that exclusively relies on the fundamental physical laws - e.g., law of conservation of mass, energy, volume. _Compartment_ based models are example of physically based models.\n# \n# Contrary to use of fundamental physical laws, **empirical models** are developed on the basis on experimental/collected data. Sorption isotherms that were developed in lecture [(10)](/contents/transport/lecture_10/22_reactive_transport) are types of emperical models. As was with the isotherms, these types of models are often based on regression analysis. Figure below show a prediction (blue) line as a predictor of data.\n# \n\n# In[2]:\n\n\nfrom myst_nb import glue\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n# x from 0 to 30\nx = 30 * np.random.random((20, 1))\n\n# y = a*x + b with noise\ny = 0.2 * x + 3.0 + np.random.normal(size=x.shape)\n\n# create a linear regression model\nmodel = LinearRegression()\nmodel.fit(x, y)\n\n# predict y from the data\nx_new = np.linspace(0, 30, 100)\ny_new = model.predict(x_new[:, np.newaxis])\n\n# plot the results\nfig, ax = plt.subplots(figsize=(6, 4))\nax.scatter(x, y, c=\"red\", label = \"data\")\nax.plot(x_new, y_new, label = \"prediction\")\n\nax.set_ylabel(r'Discharge (m$^3$/s)')\nax.set_xlabel('Hydraulic Head (m)')\n\nax.axis('tight')\nax.legend()\n\nplt.close(fig)\nglue(\"em_fit\", fig, display=False ) \n\n\n# ```{glue:figure} em_fit\n# :figwidth: 600px\n# :name: \"empirical\"\n# \n# Empirical relation between hydraulic head and discharge.\n# ```\n# \n# In certain cases **hybrid models**, e.g. **semi-empirical** models can also occur. These models combines the components of empirical/numerical and analytical models. Darcy's law in fact is a semi-empirical model. On the one hand, it is based on the momentum conservation. On the other hand, it is not possible to _strictly_ deduce the direct proportionality between flow rate and hydraulic gradient by averaging the flow behaviour over all pores.\n# \n\n# #### Mathematical models ####\n# \n# A **mathematical model** provides a quantitative representation of the relevant system components (described by for e.g., conceptual model),processes (e.g., described by physical model) and impacts in the area of investigation. The quantitative representation is based on mathematical equations. The system equations, that were developed and discussed in Lecture [(7)](/contents/flow/lecture_07/17_quantify_flow) are mathematical models. \n# \n# System equation or mathematical models can in certain cases be solved directly resulting to an _exact solution_ called **analytical solution**. Theis equation that was developed in Lecture [(8)](/contents/flow/lecture_08/18_wells) to quantify aquifer drawdown resulting from pumping of groundwater is an example of an analytical solution. \n# \n# For more complex problems, often a more natural groundwater conditions, only _approximate_ (or non-exact) solution called **numerical solution** can be obtained. Numerical solutions are obtained after converting the system equation to so called **numerical models**. \n# \n# Our focus in this introductory modeling lecture is to understand the development and solution of _numerical model_ of simple groundwater flow problems. \n# \n# \n\n# ### Example of an Analytical Solution ###\n# \n# Consider a conceptual model presented in the Figure {ref}`Ditch`. The unconfined aquifer separates two surface exposed water bodies. The water body in the left has a higher hydraulic head ($h_0$, [L]) compared to that on the right ($h_u$). Thus the flow of water is from left water body to the right one along the separating aquifer. In this scenario one of the problem to address will be to understand how the aquifer reacts to change in heads of water bodies. Additionally, how additional water, e.g., from precipitation/recharge ($N$, [L/T]), will effect the aquifer water.\n# \n# ```{figure} images/M11_f4.png\n# ---\n# scale: 20%\n# align: center\n# name: Ditch\n# ---\n# Conceptual model of a flow between two water bodies separated by unconfined aquifer\n# ```\n# The conceptual problem can be addressed when assumptions such as steady condition prevails, Darcy's law in aquifer is valid, recharge rate are relatively low. Based on the these assumptions, one of the **mathematical model** of this conceptual problem is:\n# \n# $$\n# \\frac{\\textrm{d}}{\\textrm{d}x}\\bigg(-h \\cdot K\\cdot \\frac{\\textrm{d}h}{\\textrm{d}x} \\bigg) = N\n# $$\n# \n# and the 2 boundary conditions:\n# \n# $$\n# h(0) = h_0 \\:\\: \\text{and} \\:\\: h(L) = h_L\n# $$\n# \n# Note that a complete formulation of mathematical model requires accompanying boundary conditions. The boundary conditions are used to uniquely define the problem. An _analytical solution_ for this mathematical model and accompanying boundary condition is:\n# \n# $$\n# h(x) = \\sqrt{h_o^2 - (h_o^2 - h_L^2)\\cdot \\frac{x}{L} + \\frac{N}{K}\\cdot x \\cdot (L-x) }\n# $$\n# \n# The solution can be used to quantify change in aquifer head $h$ with different system quantities, e.g., conductivity $K$ [L/T], recharge $N$ [L/T] water body heights $h_0,\\, h_L$ [L] along the flow direction. \n# \n# The additional tool: _Conservative Transport_ ([TOOLS](/contents/tools/1D_ditchflow)) interactively simulates the ditch flow concept in more details.\n\n# ### Example problem ###\n# \n# ```{admonition} Ditch flow\n# Explore the effect of recharge ($N= 0$ and $N= 0.1$ mm/d) on the aquifer level for the conceptual problem provided above. Other required data are provided below. \n# The effect are to be explored at mid of the aquifer\n# ``` \n# \n# \n\n# In[3]:\n\n\nprint(\"Provided are:\\n\")\n\nK = 2E-4 # hydraulic conductivity [m/s]\nHo = 10 # head at the origin [m]\nHu = 7.5 # head at L [m]\nL = 175 #flow length [m]\nN1 = 0 # no recharge [m/s]\nN2 = 1000 # recharge [mm/a]\n\n# intermediate calculation \nx = L/2 # mid of the aquifer [m]\nN_ = N2/1000/365/86400 # recharge, [m/s]\n\n#solution\nh1=(Ho**2-(Ho**2-Hu**2)/L*x+(N1/K*x*(L-x)))**0.5\nh2=(Ho**2-(Ho**2-Hu**2)/L*x+(N_/K*x*(L-x)))**0.5\n\nprint(\"hydraulic conductivity = {} m\\nhead at origin = {} m\\nhead at L = {} m\\nflow length = {} m\\nRecharge = {} mm/a\".format(K, Ho, Hu, L, N2 ),\"\\n\")\nprint(\"The resulting head without head is {:0.2f} m \\n\".format(h1))\nprint(\"The resulting head with head is {:0.2f} m \\n\".format(h2))\n\n\n# ### Example for a Model without Analytical Solution ###\n# \n# Analytical solutions are rather an exception. Natural aquifer or groundwater system are more complex (see figure below) and therefore analytical solution are not possible. The complexity in natural system are due to parameter heterogeneity and irregular model domain boundaries, and these must be included in underlying model equation. \n# \n# \n# ```{figure} images/M11_f5.png\n# ---\n# scale: 60%\n# align: center\n# name: nummodel\n# ---\n# The numerical model of a natural aquifer\n# ```\n# \n# \n# \n\n# ## Conceptual Model to Numerical Approach ##\n# \n# The first step in modeling is to establish the purpose of the model. With that established, the development of conceptual model begins the set-up of the numerical model. This is a step-wise process that includes:\n# \n# > 1. **Conceptual model** - providing hydrogeological units within the model domain\n# \n# > 2. **Water budgeting** - identifying water containing units and characterizing it\n# \n# > 3. **Numerical model** - Combining the units of conceptual model, water budgeting components and imposing _boundary conditions._ \n# \n# ```{figure} images/M11_f6.png\n# ---\n# scale: 60%\n# align: center\n# name: nummodel\n# ---\n# The numerical model of a natural aquifer\n# ```\n# \n# The water budgeting part should include the sources of water inflowing to the system including the expected flow directions and exiting water. Estimate of Groundwater recharge, overland flow etc, are few examples of inflows. Likewise, estimate of baseflow to streams, evapotranspiration, abstraction wells etc. are outflows. Field data are required to prepare water budget.\n# \n# The type of numerical model, depending on the modeling goal and required/available data, is then decided. The model type is mostly time-related (transient, steady) and dimension-related (1D,2D, 3D). \n\n# ### Data Requirements ###\n# \n# Numerical model are often very data intensive. Several types of data of different origin are required in the development of a numerical model. These data come from site data records/maps, field works, lab works and the ancillary mathematical analysis of the field and lab data. Overall, the required data can be:\n# \n# + topographical maps (with surface waters and water divides)\n# + geological maps, geological profiles (see figure {ref}`nummodel` example)\n# + maps with isolines of aquifer bottoms / thicknesses , aquitard bottoms / thicknesses\n# + maps indicating vertical extensions of sediments under rivers and lakes\n# + hydrogeological maps (hydraulic head isolines)\n# + water level time series in observation wells and rivers\n# + time series of spring discharges\n# + maps and profiles of hydraulic conductivity or transmissivity (also for river / lake sediments mentioned above)\n# + maps and profiles of storage coefficients\n# + information on spatial and temporal variability of inflow / outflow due to \n# - groundwater recharge \n# - evapotranspiration \n# - interaction between groundwater and surface water \n# - groundwater abstraction \n# - natural groundwater flow\n# \n\n# ## Example of a Groundwater Model ##\n# \n# Let us now develop an example flow model. To begin with we set-up an overly simplified model that still will require a numerical solution. \n# \n# **Step 1** - Spatial Extension\n# + Horizontal extension along $x-$direction: 4000 m\n# + Horizontal extension along $y-$direction: 2500 m\n# + vertical extension along $z$-direction: from $z = 250$ m a.s.l. at the aquifer bottom to $z= 265$ m at the aquifer top.\n# + aquifer thickness is uniform = 15 m.\n# \n# Putting these information graphically, we get the following schematic:\n# \n# ```{figure} images/M11_f7.png\n# ---\n# scale: 40%\n# align: center\n# name: nummodel_ex\n# ---\n# Spatial extension of an example numerical model\n# ```\n# The example model is 2D and we _assume_ that vertical flow components can be neglected despite the recharge vertically entering the groundwater. These kinds of simplification are quite common in the development of the numerical model. These simplifications have to be justified when presenting model results. \n# \n# **Step 2** - Hydraulic Properties \n# \n# For our example model we consider the following:\n# \n# + effective porosity ($\\eta_e$) in the model domain: 0.2 or 20%\n# + two zones with different hydraulic conductivities ($K$)\n# + two zones with different groundwater recharge\n# + A section of a river (_river reach_) is in hydraulic contact with the aquifer. i.e. there may be water transfer from the river to the aquifer (_influent conditions_) or vice versa (_effluent conditions_).\n# + inflow boundary with prescribed hydraulic heads\n# + outflow boundary with prescribed hydraulic heads\n# + two impermeable boundaries\n# \n# **Step 3** - The model purpose and conceptual model\n# \n# From our example model we intend to:\n# \n# + Abstraction of groundwater through wells is planned in the area with an overall pumping rate of 7000 m$^3$/d.\n# \n# + Water extraction is to be distributed between two wells located at $(x,y) =$ (3050 m, 1550 m) and $(x,y)$ = (3050 m, 1450 m), resp.\n# \n# + The model purpose is to outline the 50-days isochrone for both wells. \n# \n# With these information available, our conceptual model takes the following form:\n# \n# ```{figure} images/M11_f8.png\n# ---\n# scale: 25%\n# align: center\n# name: Concept_model\n# ---\n# The conceptual model of the example model\n# ```\n# **Step 4** - The numerical approach \n# \n# This is discussed in the next lecture.\n\n# \n", "meta": {"hexsha": "3de72442cda25924813af0b9ee00d60898292a2a", "size": 15852, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/modeling/lecture_11/31_intro_modeling.py", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/contents/modeling/lecture_11/31_intro_modeling.py", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/contents/modeling/lecture_11/31_intro_modeling.py", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3292682927, "max_line_length": 601, "alphanum_fraction": 0.7293716881, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 3911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.20181322226037884, "lm_q1q2_score": 0.08680942541342448}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd \nimport ipysheet as ips\nimport panel as pn\nfrom scipy import stats \npn.extension(\"katex\") \n\n\n# # Tutorial 4 #\n# \n# + **solutions for homework problems 1 – 4**\n# \n# + **tutorial problems on effective conductivity and flow nets**\n# \n# + **homework problems on effective conductivity and flow nets**\n# \n# \n# \n# \n# \n# \n# \n# ### Solutions for Homework Problems 1 – 2 ###\n# \n# \n# \n\n# In[2]:\n\n\n#\nr1_1 = pn.pane.Markdown(\"\"\"\n\n### Homework Problem 1 ###\n\nThe pressure head in an aquifer extending over 200 km2 is decreased by 1.60 m.\nDetermine the loss of groundwater in the aquifer for two scenarios:\nA. The aquifer is unconfined (storage coefficient 0.13).\nB. The aquifer is confined (storage coefficient 0.0005).\n\n\"\"\",width = 800, style={'font-size': '13pt'}) \n\nr1_2= pn.pane.PNG(\"images/T03_H1.png\", width=350)\n#r1_2 = pn.pane.PNG(\"images/T03_H1.PNG\") \n\n### Tutorial Problem 7 – Solution ###\n\n#\"Grosser\n\nr1_3 = pn.pane.Markdown(\"\"\" \n### Solution - Homework Problem 1 ###\n
\nRelevant information can be found in Lecture L03, Slides- 28-30\n\n\"\"\",width = 800, style={'font-size': '13pt'}) \n\nr1_3b = pn.pane.LaTeX(r\"\"\" \n
\nThe relevant equations is:
\n$$\nS = \\Delta V_w/(A\\cdot \\Delta H)\n$$\n\n\"\"\",width = 800, style={'font-size': '13pt'}) \npn.Column(r1_1, r1_2, r1_3, r1_3b) \n\n\n# In[3]:\n\n\n# Given \nA = 200 # km^2, aquifer area\nD_h = 1.6 # m, head decrease\nS_u = 0.13 # (-), Storativity unconfined aquifer\nS_c = 0.0005 # (-) Storage coefficient, confined aquifer\n\n# Solution\nDV_wu = A*S_u*D_h * 10**6 # m^3 change in water volume unconfined aquifer\nDV_wc = A*S_c*D_h* 10**6 # m^3 change in water volume unconfined aquifer\n\n# output\n\nprint(\"Change in water volume in unconfined aquifer is: {0:1.1e}\".format(DV_wu),\"m\\u00b3 \\n\")\nprint(\"Change in water volume in confined aquifer is: {0:1.1e}\".format(DV_wc),\"m\\u00b3\")\n\n\n# ## Homework Problem 2\n# \n# Conduct a sieve analysis for a dried soil sample (see data in the table below)\n# \n# 1. Draw the granulometric curve (cumulative mass distribution) and briefly characterise the sediment with regard to its major constituent(s).\n# 2. What is the coefficient of uniformity? \n# \n\n# In[4]:\n\n\n#\ntitle = [\"mesh size [mm] \", \"residue in the sieve [g] \", \"∑Retained %\", \"Commulative Passed %\"]\nSize = [6.3, 2, 0.63, 0.2, 0.063, \"< 0.063 /cup\"]\npassed = [11, 62, 288, 189, 42, 10]\ns2 = ips.sheet(rows=6, columns=4, row_headers=False, column_headers=title)\nips.column(0, Size, row_start=0) \nips.column(1, passed, row_start=0); s2 \n\n\n# In[5]:\n\n\n# Solution of problem 2\n\nt_sample = np.sum(passed) # g, add the residue column to get total mass\nretained_per = passed/t_sample *100 # %, # retain percentage residue/total mass\nretain_per_cumsum =np.cumsum(retained_per) # get the cummulative sum of the reatined\npassing_cumper = 100 - retain_per_cumsum # substract 100-cummsum to get passing % - the last column\n\n#Output\ns3 = ips.sheet(rows=6, columns=4, row_headers=False, column_headers=title)\nips.column(0, Size, row_start=0) \nips.column(1, passed, row_start=0); \nips.column(2, retained_per, row_start=0); \nips.column(3, passing_cumper, row_start=0); s3 \n\n\n# In[6]:\n\n\n# Plotting granulometric curve\n\nplt.rcParams['axes.linewidth']=2\nplt.rcParams['grid.linestyle']='--'\nplt.rcParams['grid.linewidth']=1\nx = np.append([20], Size[:5]) # adding for all left over.\ny = np.append([100],passing_cumper[:5])\nfig = plt.figure(figsize=(9,6));\nplt.plot(x, y, 'x-', color='red', lw=2.5); \ntics=x.tolist()\nplt.xscale('log');lw=2.5\nplt.grid(which='major', color='k', alpha=0.7) \nplt.grid(which='minor', color='k', alpha=0.3)\nplt.xticks(x, tics); \nplt.yticks(np.arange(0,110,10));\n#plt.title('grain size distribution (combined wet sieving and sedimentation analysis)');\nplt.xlabel('grain size d [mm]');\nplt.ylabel('Cummulative Passed fraction %');\n\nplt.annotate('', xy=(0.20, 10), xycoords='data', xytext=(0.045, 10), arrowprops=dict(arrowstyle='->', color=\"b\", lw=2.5),ha='right', va='top',)\nplt.annotate('', xy=(1.1, 60), xycoords='data', xytext=(0.045, 60), arrowprops=dict(arrowstyle='->', color=\"b\", lw=2.5),ha='right', va='top',)\nplt.annotate(r'$d_{60}$', xy=(1, 60), xycoords=\"data\", xytext=(0.85, -3),color='red',size=12, arrowprops=dict(arrowstyle='<-', color=\"b\", lw=2.5),ha='left', va='bottom',)\nplt.annotate(r'$d_{10}$', xy=(0.20, 10), xycoords='data', xytext=(0.235, 1.5),color='red',size=12, arrowprops=dict(arrowstyle='<-', color=\"b\", lw=2.5),ha='right', va='top',)\nplt.rcParams[\"font.weight\"] = \"bold\" \n\nplt.savefig(\"fig6.png\")\n\nmpl_pane = pn.pane.Matplotlib(fig, dpi=144)\n\n\n# In[7]:\n\n\n# From the figure\nd_10 = 0.22 # mm,approx, diameter 10% passing, see the arrow bottom in x-axis\nd_60 = 1.0 # mm, approx diameter 10% passing, see the arrow bottom in x-axis\n\nc_u = d_60/d_10 # [], coefficient of uniformity\n\n#Output\nprint(\"The coefficient of uniformity is: {0:1.1f}\".format(c_u)) \nr2_1 = pn.pane.Markdown(\"\"\"\n**Major constituents: coarse sand/medium sand** \"\"\", width=600, style={'font-size': '13pt', 'color': 'blue'} )\npn.Row(r2_1) \n\n\n# In[8]:\n\n\n# Tutorial Problem 11- Effective Conductivity and flow nets\nr5_1 = pn.pane.Markdown(\"\"\"\n#Tutorial Problems on Effective Conductivity and Flow Nets\n\"\"\", width = 900) \n\nr5_2 = pn.pane.Markdown(\"\"\"\n###Tutorial Problem 11: Effective Hydraulic Conductivity\nA sandy layer with a thickness of 2.5 m is embedded between two gravel layers. B\noth gravel layers have a thickness of 1.5 m and a hydraulic conductivity of 3.7·10-3 m/s. \nSteady-state groundwater flow is in parallel to the layering. \nA hydraulic gradient of 0.001 and an overall discharge of 1 m³/d per unit width have been determined.\n

\na. Determine the effective hydraulic conductivity.

\nb. What is the hydraulic conductivity of the sand layer?

\nc. Which effective hydraulic conductivity would be obtained if flow was assumed perpendicular to the layering?

\nd. Calculate effective hydraulic conductivity if the angle between the flow direction and the layering equals 45°.\n\"\"\", style={'font-size': '13pt'})\n\npn.Column(r5_1, r5_2) \n\n\n# In[9]:\n\n\n# Solution of Problem 11\nr5_3 = pn.pane.PNG(\"images/T03_TP11_a.png\", width=400)\nr5_4 = pn.pane.LaTeX(r\"\"\"\nKnown relationships are (see Lecture 05, Slides 8-13, 22):\n$$\nQ = WmK\\frac{\\Delta H}{L}\n$$\n$$\nK = \\frac{Q/W}{m\\cdot \\Delta H \\cdot L}\n$$\nWeighted arithmetic mean to determine hydraulic conductivity for sand:\n\n$$\nK = \\frac{1}{m}\\sum_{i=1}^n m_i\\cdot K_i\n$$\nwhere $i$ is different layers\n\"\"\", width = 500, style={'font-size': '13pt'})\nspacer2 = pn.Spacer(width=100)\n\npn.Row(r5_3, spacer2, r5_4) \n\n\n# In[10]:\n\n\n#Given Solution of 11 a, b\n\nQ = 2 # m^3/d, discharge\nW = 1 # m, per unit width\nK_g = 3.7*1E-3# m/s, conductivity of gravel layer \nm_g = 1.5 # m, thickness of gravel layer\nm_s = 2.5 # m, thickness of sand layer\nm = 2*m_g + m_s # m. total thickness of aquifer\nDh_L = 0.001 # (-), hydraulic gradient\n\n\n#Solution of 11a\nKeff_h = (Q/W)/(m*Dh_L) # m/d, conductivity\nKeff_hs = Keff_h/(24*3600)# m/s, conductivity unit changed\n\n#Solution of 11b\n# K_eff = (2*m_g*K_g + m_s*K_g)/m\n\nK_s = ((m*Keff_hs - 2*m_g*K_g))/m_s \n\nprint(\"Effective horizontal hydraulic conductivity (Keff_h) = {0:1.2f}\".format(Keff_h), \"m/d\\n\" ) \nprint(\"Effective horizontal hydraulic conductivity (Keff_hs) = {0:1.3E}\".format(Keff_hs), \"m/s\\n\" )\nprint(\"Hydraulic conductivity of sand layer (K_s) = {0:1.1E}\".format(K_s), \"m/s\" ) \n\n\n# In[11]:\n\n\n#Given Solution of 11 c, d\n\nr5_5 = pn.pane.PNG(\"images/T03_TP11_b.png\", width=200) \nr5_6 = pn.pane.PNG(\"images/T03_TP11_c.png\", width=200) \n\nr5_7 = pn.Column(r5_5, r5_6) \n\nr5_8 = pn.pane.LaTeX(r\"\"\"\nVertical effective conductivity is given by weighted harmoninc mean\n$$\nK = \\frac{m}{2\\cdot \\frac{m_g}{K_g} + \\frac{m_s}{K_s} }\n$$\n
\nFor inclined aquider the effective conductivity is:\n\n$$\nK = \\frac{1}{\\frac{\\cos^2\\theta}{K_h} + \\frac{\\sin^2\\theta}{K_v}}\n$$\n\n\"\"\", style={'font-size': '13pt'})\n\npn.Row(r5_7,spacer2, r5_8) \n\n\n# In[12]:\n\n\n# Solution of 11c\n\nKeff_v = m/(2*(m_g/K_g)+ (m_s/K_s))\n\n#Given \ntheta = 45 # theta \ntheta_r = 45*(np.pi)/180 # degree to radian conversion\nK_h = Keff_hs # m/s, solution from 11a\nK_v = Keff_v # m/s, solution from 11c\n\n# solution from 11d\nKeff_i = 1/((np.cos(theta_r)**2/K_h)+(np.sin(theta_r)**2/K_v))\n\n\nprint(\"Effective vertical hydraulic conductivity (Keff_v) = {0:1.2E}\".format(Keff_v), \"m/s\\n\" ) \nprint(\"Effective inclined hydraulic conductivity (Keff_i) = {0:1.2E}\".format(Keff_i), \"m/s\" ) \n\n\n# In[13]:\n\n\n#\nr6_1 = pn.pane.Markdown(\"\"\"\n### Tutorial Problem 12: Hydrologic Triangle\nThe figure below shows the position of four groundwater observation wells with measured hydraulic heads in m a.s.l. \n

\n**a.** Sketch head isolines for intervals of 1 m by applying the hydrologic triangle method.

\n**b.** Indicate the flow direction.\n\n\"\"\",width = 400, style={'font-size': '13pt'})\n\nr6_2 = pn.pane.PNG(\"images/T03_TP12_a.png\", width=400) \n\npn.Row(r6_1,spacer2, r6_2) \n\n\n# In[14]:\n\n\n# \nr6_3 = pn.pane.Markdown(\"\"\"\n### Solution of Tutotrial Problem 12\n\nStep 1. Connects all the points\n\"\"\", width=600)\n\nr6_2.object = \"images/T03_TP12_b.png\"\nr6_3\n\n\n# In[15]:\n\n\n#\nr6_4 = pn.pane.Markdown(\"\"\"\n### Solution of Tutotrial Problem 12\nStep 2. Divide the connected lines at equal head-level (here = 1 m)\n\"\"\", width=600)\nr6_2.object = \"images/T03_TP12_c.png\"\n\n\n# In[16]:\n\n\n#\nr6_4 = pn.pane.Markdown(\"\"\"\n### Solution of Tutotrial Problem 12\nStep 3. Join all the equal head lines \n\"\"\", width=600)\nr6_2.object = \"images/T03_TP12_d.png\"\n\n\n# In[17]:\n\n\nr6_4 = pn.pane.Markdown(\"\"\"\n### Solution of Tutotrial Problem 12\nStep 4. Mark the flow direction from higher head towards lower head\n\"\"\", width=600)\nr6_2.object = \"images/T03_TP12_e.png\"\n\n\n# In[18]:\n\n\n#\nr7_1 = pn.pane.Markdown(\"\"\"\n##Tutorial Problem 13: Flow Nets##\n\nSketch head isolines and streamlines for the two configurations a) and b) of a well doublette shown below. In both cases flow nets should be sketched without and with the uniform flow component.\n\n\"\"\",width=800, style={'font-size': '13pt'})\n\nr7_2 = pn.pane.Markdown(\"\"\"\n a) withdrawal at both wells:


\n\"\"\",width=400, style={'font-size': '13pt'})\n\nr7_3 = pn.pane.PNG(\"images/T03_TP13_a.png\", width=200) \n\nr7_4 = pn.Column(r7_2,r7_3)\n\nr7_5 = pn.pane.Markdown(\"\"\"\n b) Injection and withdrawl wells:


\n\"\"\",width=400, style={'font-size': '13pt'})\n\nr7_6 = pn.pane.PNG(\"images/T03_TP13_b.png\", width=200) \n\nr7_7 = pn.Column(r7_5,r7_6)\nr7_8 = pn.Row(r7_4, r7_7) \npn.Column(r7_1, r7_8) \n\n\n# In[19]:\n\n\nr8_1= pn.pane.Markdown(\"\"\"\n#Homework Problems on Effective Conductivity and Flow Nets


\n\"\"\", width = 800, style={'font-size': '13pt'})\n\n\nr8_2= pn.pane.Markdown(\"\"\"\n#There is no obligation to solve homework problems!\n\"\"\", width = 800, style={'font-size': '13pt', 'color':'red'})\n\npn.Column(r8_1,r8_2) \n\n\n# In[20]:\n\n\n#\nr9_1= pn.pane.Markdown(\"\"\"\n###Homework Problem 5: Effective Hydraulic Conductivity\nA gravel layer with a thickness of 2.5 m is embedded between two sand layers. Both sand layers have a thickness of \n1.5 m and a hydraulic conductivity of 3.7·10-4 m/s. Steady-state groundwater flow is perpendicular to the layering. \nAn overall head difference of 5.5 cm and a discharge of 500 l/d per unit area have been determined

\n\n**a.** Determine the effective hydraulic conductivity.

\n**b.** What is the hydraulic conductivity of the gravel layer?

\n**c.** Which effective hydraulic conductivity would be obtained if flow was assumed to be in parallel with the layering?

\n**d.** Calculate effective hydraulic conductivity if the angle between the flow direction and the layering equals 30°.
\n\n\"\"\", width = 900, style={'font-size': '13pt'})\nr9_1\n\n\n# In[21]:\n\n\n#\nr10_1= pn.pane.Markdown(\"\"\"\n###Homework Problem 6: Hydrologic Triangle\nThe figure below shows the position of five groundwater observation wells with measured hydraulic heads in m a.s.l. \n

\n\n**a.** Sketch head isolines for intervals of 1 m by applying the hydrologic triangle method.\n

\n**b.** Indicate the flow direction.

\n\"\"\", width = 500, style={'font-size': '13pt'})\nr10_2 = pn.pane.PNG(\"images/T03_TH6.png\", width=400) \n\npn.Row(r10_1, r10_2)\n\n\n# In[22]:\n\n\n#\nr11_1= pn.pane.Markdown(\"\"\"\n###Homework Problem 7: Flow Nets\nSketch head isolines and streamlines for the well doublette shown below. \nIn this case, injection and withdrawal of groundwater is superimposed to a uniform flow component.\n





\n \"\"\", width = 900, style={'font-size': '13pt'})\n\nr11_2 = pn.pane.PNG(\"images/T03_TH7.png\", width=400) \n\nr11_3= pn.pane.Markdown(\"\"\"\n





\n \"\"\", width = 900, style={'font-size': '13pt'})\npn.Column(r11_1, r11_2, r11_3)\n\n\n# In[ ]:\n\n\n\n\n", "meta": {"hexsha": "ea2d82dc51744293901c04c7e3a034e6caa9d692", "size": 12850, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/contents/tutorials/Tutorial_04.py", "max_stars_repo_name": "prabhasyadav/iGW-I", "max_stars_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/contents/tutorials/Tutorial_04.py", "max_issues_repo_name": "prabhasyadav/iGW-I", "max_issues_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/contents/tutorials/Tutorial_04.py", "max_forks_repo_name": "prabhasyadav/iGW-I", "max_forks_repo_head_hexsha": "eba32830f32f1109a7bee600c65832af0e7183fa", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9957983193, "max_line_length": 194, "alphanum_fraction": 0.6823346304, "include": true, "reason": "import numpy,from scipy", "num_tokens": 4220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.1801066618860355, "lm_q1q2_score": 0.0865374108106237}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Lab 1 Solutions\n# \n# ### Objectives\n# In this lab, we'll \n# - Review the computational infrastructure around our data science environments,\n# - Go through the process of ensuring that we have a Python environment set up for this class with the proper installed packages\n# - Within our environment, we'll review the basic data science operations in Python, and introduce some tips and tricks. \n# \n# \n# ```{admonition} Take a Deep Breath\n# Don't freak out if stuff presented here is brand new to you! Ask a friend, google around (esp. stack overflow) and find a solution. All of these examples can be done in a few lines of code.\n# ```\n# \n# # Part I: Computational Ecosystem \n# \n# In the space below, or in your own assignment, answer the following: \n# \n# ## Question A\n# \n# Describe the following terms, and point out the differences between them. Feel free to look things up.\n# - python:\n# - the terminal:\n# - the file system:\n# - jupyter:\n# - an IDE: \n# - a text editor:\n# - git: \n# - PATH: \n# \n\n# I am writing this lab in a notebook. We'll be discussing the pros and cons of notebooks in class. Below, I'm going to check which python installation on my computer is being pointed to within my PATH. As a reminder, you can see your full path by echoing it from the terminal. Within a notebook, that looks like this:\n\n# In[2]:\n\n\nget_ipython().system('echo $PATH')\n\n\n# ```{note}\n# The \"!\" in my notebook allows me to run terminal commands from a notebook; you don't need this symbol when running commands in an actual terminal.\n# ```\n\n# I can check my python as follows:\n\n# In[3]:\n\n\nget_ipython().system('which python')\n\n\n# We can see that calls to `python` are triggering the python installed in `anaconda3`, which is what we want (see the installation video for more details). If your call to `which python` in the terminal returns something like `usr/bin/python`, then something has likely gone wrong with your installation. There are some troubleshooting steps suggested in the installation video. \n# \n# ## Setting up an Environment. \n# \n# We can think of packages as programs installed on our computer. But what if one of my projects needs Photoshop 14.0, and another needs a feature that was only available in Photoshop 12.5.2? An environment is the system on which your code is being executed. When you fire up a terminal, this is usually your *base* environment, the default one for your *user* on a given computer system. But rather than always installing programs in this base installation, we can create custom environments for each of our projects. We can then install the exact dependencies for those projects within our environments, and we'll know they won't mess with each other. \n# \n# For this class, we're going to be doing a lot of package installations. To ensure we are all on the same page and are working with the same tools, we're going to use a `conda environment` to maintain versioning. Note: there are multiple environment creation tools/methods. Conda environments are the predominant standard in astronomy, hence their use here. \n# \n# In your terminal, type the following:\n# ```{note}\n# If you are on WINDOWS, you NEED to use the ANACONDA TERMINAL. NOT YOUR WINDOWS POWER SHELL/COMMAND PROMPT. Search your pc for anaconda and you'll see an anaconda launcher (if you followed the installation video correctly). From there, you should be able to find an anaconda terminal/prompt. That's where you should do anything whenever I say \"from your terminal\".\n# ```\n# \n# \n\n# In[ ]:\n\n\nconda create -n a330 python=3.8 \n\n\n# Once you run this, answer \"y\" to the prompts, and your new environment will be installed.\n# \n# ```{note}\n# The above command may take several minutes to execute.\n# ```\n# \n# \n# Next, we want to activate this environment (still in our terminal). We do this as follows:\n\n# In[ ]:\n\n\nconda activate a330\n\n\n# When you do so, you should see the left hand edge of your prompt switch from (base) to (a330). \n# \n# Next, let's make an alias so that getting into our a330 environment is a snap. We're going to access a file called `.bash_profile`, which allows us to set aliases and environment variables. This file is located in your home directory, so I can print mine here:\n\n# In[6]:\n\n\nget_ipython().system('more ~/.bash_profile')\n\n\n# Notice above I use the `~` which is a shorthand for home directory. On my computer, the default home directory for my user is `/Users/ipasha/`. \n# \n# \n# \n# This file has some conda stuff in it at the top, as well as some path and python path exports, as well as an alias. \n# \n# Yours should also have the conda init stuff, if you installed anaconda properly. Using your text editor of choice, add a line to this file that reads `alias a330='conda activate a330'`. \n# \n# ```{sidebar} Using Vi/vim\n# Vi/vim is a built-in terminal program that allows for the editing of files. It is helpful to learn, especially when working on remote servers. We'll go into it more later, but here is a step by step for performing the above step with vim. \n# - First: from the terminal, type `vim ~/.bash_profile` and hit enter. This will open the editor. If 'vim' isn't recognized, try 'vi'. \n# - Next: Press the \"I\" key to open insert mode. Move your cursor with the arrow keys to the desired line, then type in the alias command shown to left. \n# - Finally: Press `esc` to get out of insert mode, then type `:wq` and hit enter in order to \"write\" then \"quit\". \n# ```\n# \n# \n# \n# Now, from your terminal, source your profile by typing `source ~/.bash_profile`. You're good to go! Test that you can activate your environment by typing `a330` and hitting enter. \n# \n# ```{note}\n# To deactivate, just type `conda deactivate`. \n# ```\n# \n# \n\n# ## Adding Jupyter\n# \n# You'll be using notebooks during this class, and we need to make sure that we can access our new environment from within Jupyter notebook. To ensure this, we're going to do the following:\n# \n# First, make sure your environment is activated. \n# \n# Then, type:\n\n# In[ ]:\n\n\nconda install -c anaconda ipykernel\n\n\n# This ensures we can select different kernels inside jupyter. A kernel is basically \"the thing that is python\", the root thing being run on your system when you use python. By creating environments, we're creating different unique kernels, and we can now get to them within our notebooks. \n# \n# Now, run the following:\n\n# In[ ]:\n\n\npython -m ipykernel install --user --name=a330\n\n\n# Once you've done this, you should have the ability to access your new environment from within Jupyter. We can test this as follows: \n# - First, open a new terminal window, and activate your environment (if you made the alias, this means typing `a330` in your terminal. \n# - Next, type `jupyter lab` to open jupyter lab. If for some reason you don't have jupyter lab yet, you can install it now with `conda install -c conda-forge jupyterlab`. \n# - Once you have lab open, there should be a 'launcher' page, with one option being to create a new notebook using python -- you *should* see your environment listed there. \n# - If you don't hit refresh on the webpage just in case. \n# - You can also click on the option to open a python3 notebook. Inside, in the top right corner, it should say your current environment (probably Python 3). Clicking that, it should give you the option to choose a different environment, and your environment should be listed there. \n# \n# ```{note}\n# If you already had a lab open, you'll have to hit refresh to get it to show up. \n# ```\n# ## Installing Packages\n# \n# Now that we have our environment, we're going to install the set of packages we need for this class. We may need more of them as the semester goes on, but for now, do the following (in your terminal, within your environment). \n\n# In[ ]:\n\n\nconda install -n a330 numpy scipy astropy matplotlib \n\n\n# (again, hitting \"y\" when prompted). Again, this step might take a minute or so to run.\n# \n# Congrats, you now have an environment set up for this class, and can jump in and out of it at will, either in your terminal, or within a Jupyter notebook.\n# \n# ```{admonition} Hot Tip\n# It's highly recommended you do these steps anytime you start a new research project. Up front, you may not know all the dependencies that will arise, but as you go along, if you keep your work to that environment, you'll be able to carefully control which versions of which packages you're accessing at all times.\n# ```\n# \n# \n\n# # Part II: Python Review\n# \n# In this section, I'll ask you to perform some pythonic operations to get back into the swing of things if it has been a little while. \n# \n# For this assignment, please carry out your work in a Jupyter notebook, with the questions labeled and your output shown. You'll submit this notebook via Github, but we will discuss how to perform this step in class.\n\n# ## Question 1\n# Create a 2D array of dimensions 1000 x 1000, in which the values in each pixel are random-gaussian distributed about a mean of 10, with a sigma of 2, and then use matplotlib to display this image. Make sure (0,0) is in the lower lefthand corner. \n\n# In[145]:\n\n\nimport numpy as np\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\n\n\n# In[146]:\n\n\n# Solution 1\nmu = 10\nsigma = 2\nGauss = stats.norm(loc=mu,scale=sigma)\narray = Gauss.rvs((1000,1000))\nfig, ax = plt.subplots(figsize=(10,10))\nax.imshow(array,origin='lower');\n\n\n# In[147]:\n\n\n#Solution 2:\narray_np = np.random.normal(loc=10,scale=2,size=(1000,1000))\nfig, ax = plt.subplots(figsize=(10,10))\nax.imshow(array_np,origin='lower');\n\n\n# ## Question 2\n# \n# The distribution of pixels in your above image should not have many outliers beyond 3-sigma from the mean, but there will be some. Find the location of any 2 sigma outliers in the image, and highlight them by circling their location. \n# Confirm that the fraction of these out of the total number of pixels agrees with the expectation for a normal distribution.\n\n# In[149]:\n\n\n# Solution \noutliers = np.where((array>mu+3*sigma)|(array 3$\\sigma$ from the image mean are masked. Then, calculate the mean and sigma of the new masked array. \n\n# In[34]:\n\n\n# Solution \nclipped_array = np.ma.masked_where((array>mu+3*sigma)|(arraymu-3.*sigma)\n\nmn = np.mean(array[m])\nst = np.std(array[m])\nprint('Clipped mean; {:0.3f}; Clipped Sigma: {:0.3f}'.format(mn,st))\n\n\n# As expected, clipping the outliers of this distribution does not affect the mean in any strong way, but does noticably decrease $\\sigma$. \n\n# ## Question 4:\n# \n# Using Array indexing, re-plot the same array from above, but zoom in on the inner 20% of the image, such that the full width is 20% of the total. Note: try not to hard code your indexing. You should be able to flexibly change the percentage. For this one, use a white-to-black color map.\n# \n\n# In[150]:\n\n\n# solution \ncent = int(array.shape[0] / 2)\nperc = int(0.2 * array.shape[0]*0.5)\ncropped_array = array[cent-perc:cent+perc,cent-perc:cent+perc]\nfig, ax = plt.subplots(figsize=(10,10))\nax.imshow(cropped_array,origin='lower',cmap='gray_r');\n\n\n# As expected, our image is now 200 by 200 pixels across. Note that our new image has its own indexing. A common \"gotcha\" when working with arrays like this is to index in, but then try to use indices found (e.g., via `where()`) in the larger array on the cropped in version, which can lead to errors.\n\n# ## Question 5\n# \n# Often, we have an expression to calculate of the form \n# \n# $$\n# \\sum_i \\sum_j a_i b_j\n# $$\n\n# Your natural impulse for coding this double sum might look like this:\n\n# In[ ]:\n\n\ntotal = 0\nfor i in a:\n for j in b:\n total+= i*j\n\n\n# which, mathematically, makes sense! But as it turns out, there's a way we can do this without any loops at all --- and when $\\vec{a}$ and $\\vec{b}$ get long, this becomes hugely important in our code.\n# \n# The trick we're going to use here is called [array broadcasting](https://numpy.org/doc/stable/user/basics.broadcasting.html), which you can read about at the link if you're not already familar. I'm going to give you $\\vec{a}$ and $\\vec{b}$ below. For this exercise, calculate the double sum indicated above without the use of a for-loop. \n# \n# ```{admonition} Hint\n# The command `np.newaxis` will be useful here, or for a slightly longer solution, try `np.repeat` and `reshape()`. \n# ```\n\n# In[35]:\n\n\na = np.array([1,5,10,20])\nb = np.array([1,2,4,16])\n\n# Solution\noutput = np.sum(a[:,np.newaxis]*b)\n\n\n# In[37]:\n\n\noutput\n\n\n# We can confirmed the above worked using our slow loop:\n\n# In[40]:\n\n\ntotal = 0\nfor i in a:\n for j in b:\n total+= i*j\ntotal\n\n\n# We can also perform this trick without knowing about `np.newaxis` explicitly. You may have done it this way. \n\n# In[55]:\n\n\nmatrix_a = np.repeat(a,len(b)).reshape(len(a),len(b))\nmatrix_b = np.repeat(b,len(a)).reshape((len(b)),len(a)).T\noutput = np.sum(matrix_a*matrix_b)\noutput\n\n\n# I want to take a moment here and really highlight the difference in speed between these two methods. Let's bump up the length... by a lot: \n\n# In[68]:\n\n\na = np.random.random(5000)\nb = np.random.random(5000)\n\n\n# In[69]:\n\n\nget_ipython().run_cell_magic('timeit', '', '\\ntotal = 0\\nfor i in a:\\n for j in b:\\n total+= i*j')\n\n\n# We can see that above, it took 5 whole seconds to run the cell. That's for only 5000 entries in each list. Many astronomical lists on which we might have to do this are 10,000 or more long! Notice this is an exponential operation. Try running the above on your computer with 10000 long lists. I'll wait... until you get bored and kill the process after many minutes.\n# \n# Now see below:\n\n# In[70]:\n\n\nget_ipython().run_cell_magic('timeit', '', 'output = np.sum(a[:,np.newaxis]*b)')\n\n\n# Wow. 52 ms to do that whole thing. Broadcasting. We love it, we use it, we love it. \n# \n# ```{admonition} Takeaway Point\n# The takeaway from this lesson should be that anytime we can do something without a loop... WE SHOULD.\n# ```\n# \n# \n\n# ## Question 6\n# \n# Often in astronomy we need to work with grids of values. For example, let's say we have a model that describes some data, and the model has 2 parameters, $a$ and $b$.\n# \n# We might choose different combinations of $a$ and $b$, and determine a metric for how well models of such combinations fit our data (e.g., $\\chi^2$). \n# \n# We may then want to plot this $\\chi^2$ value for each point on our grid -- that is, at each grid position corresponding to some $a_i$ and $b_j$. \n# \n# Below, I provide a function, `chi2`, which returns a single number given some singular inputs `a` and `b`. \n# \n# Create some arrays of `a` and `b` to test that range between 1 and 25, and have 10 entries evenly spaced between those values. Then, loop over them and find the $\\chi^2$ using my function. \n# ```{note}\n# We can't get around the double loop in this case, because we are operating under the assumption that the calculation of some single $\\chi^2$ using a unique combination of $a_i$ and $b_j$ cannot be vectorized. If it could, we wouldn't need to do this activity. But often, we can't, because the creation of a model given some inputs is nontrivial.\n# ```\n# \n# Once you've stored the $\\chi^2$ values for each combination of $a$ and $b$, create a plot with $a$ and $b$ as the axes and show using colored circles the $\\chi^2$ value at each location. Add a colorbar to see the values being plotted. \n# \n# To create this grid, use the `np.meshgrid()` function. For your plot, make sure the marker size is big enough to see the colors well. \n# \n# \n# \n# \n\n# In[151]:\n\n\ndef chi2(a,b):\n return ((15-a)**2+(12-b)**2)**0.2 #note, this is nonsense, but should return a different value for each input a,b\n\n# Solution \na = np.linspace(1,25,10)\nb = np.linspace(1,25,10)\nchi2_values = []\nfor i in a:\n for j in b:\n chi2_values.append(chi2(i,j))\n\nchi2_values = np.array(chi2_values)\n\nxx,yy = np.meshgrid(a,b)\n\nfig, ax = plt.subplots(figsize=(12,10))\n\nim = ax.scatter(xx,yy,c=chi2_values,marker='o',s=100)\nplt.colorbar(im);\n\n\n# ## Question 7 \n# \n# Re-show your final plot above, making the following changes:\n# \n# - label your colorbar as $\\chi^2$ using latex notation, with a fontsize>13\n# - Make your ticks point inward and be longer\n# - Make your ticks appear on the top and right hand axes of the plot as well \n# - If you didn't already, label the x and y axes appropriately and with a font size > 13 \n# - Make sure the numbers along the axes have fontsizes > 13\n# \n\n# In[152]:\n\n\nfig, ax = plt.subplots(figsize=(12,10))\n\nim = ax.scatter(xx,yy,c=chi2_values,marker='o',s=100)\nax.tick_params(direction='in',right=True,top=True,length=7,width=1.5,labelsize=14)\nax.set_xlabel(r'parameter $a$',fontsize=15)\nax.set_ylabel(r'parameter $b$',fontsize=15)\ncbar = plt.colorbar(im)\ncbar.set_label(r'model $\\chi^2$',fontsize=14);\n\n\n# ## Question 8\n# \n# Some quick list comprehensions! For any unfamilar, **comprehensions** are pythonic statements that allow you to compress a for-loop (generally) into a single line, and usually runs faster than a full loop (but not by a ton). \n# \n# Take the for-loop below and write it as a list comprehension.\n\n# In[119]:\n\n\nvisited_cities = ['San Diego', 'Boston', 'New York City','Atlanta']\nall_cities = ['San Diego', 'Denver', 'Boston', 'Portland', 'New York City', 'San Francisco', 'Atlanta']\n\nnot_visited = []\nfor city in all_cities:\n if city not in visited_cities:\n not_visited.append(city)\n \nprint(not_visited)\n\n\n# In[121]:\n\n\n# Solution \n\nnot_visited = [i for i in all_cities if i not in visited_cities]\nprint(not_visited)\n\n\n# Next, create an array of integers including 1 through 30, inclusive. Using a comprehension, create a numpy array containing the squared value of only the odd numbers in your original array. (*Hint, remember the modulo operator*)\n\n# In[122]:\n\n\n# Solution \nfull = np.arange(1,31)\nsquared_odds = np.array([i**2 for i in full if i%2!=0])\nprint(squared_odds)\n\n\n# In the next example, you have a list of first names and a list of last names. Use a list comprehension to create an array that is a list of full names (with a space between first and last names). \n\n# In[123]:\n\n\nfirst_names = ['Bob','Samantha','John','Renee']\nlast_names = ['Smith','Bee','Oliver','Carpenter']\n\n# Solution\nfull_names = [i+' '+j for i,j in zip(first_names,last_names)]\nprint(full_names)\n\n\n# ```{admonition} Challenge Problem (worth Extra Credit) \n# I've created new lists that contain strings of the names in the format Lastname,Firstname, with random leading/trailing spaces and terrible capitalizations. Use a list comprehension to make our nice, \"Firstname Lastname\" list again.\n# ```\n\n# In[129]:\n\n\nall_names = ['sMitH,BoB ', ' bee,samanthA',' oLIVER,JOHN ',' caRPENTer,reneE ']\n\n# solution \nfull_names = [i.strip().split(',')[1].upper()[0]\n +i.strip().split(',')[1].lower()[1:]\n +' '\n +i.strip().split(',')[0].upper()[0]\n +i.strip().split(',')[0].lower()[1:]\n for i in all_names]\nprint(full_names)\n\n\n# ```{note}\n# Note that with this last example, we're entering a degree of single-line length and complexity that it almost doesn't make sense to use a comprehension anymore. Just because something CAN be done in one line doesn't mean is has to be, or should be.\n# \n# ```\n# \n# You may be wondering what use case this type of coding has in astronomy -- turns out, quite a lot. Take this example: you read in a data table and the columns have names like \"FLUX HA\", \"FLUX ERR\", etc. \n# \n# If you're trying to make a `pandas DataFrame` of this table, it is advantageous to rename these columns something like `flux_ha` and `flux_err`. This way, commands like `df.flux_ha` can be used. \n# \n# Being able to iterate over the string list of column names and turn caps into lower case, spaces into underscores, etc., is a useful skill that will come in handy when wrangling data. \n# \n# Below, for reference, I show how I myself would do the above example in production code:\n\n# In[133]:\n\n\ndef clean_csv_string(str_in,sep=',',formatting='LastFirst'):\n str_stripped = str_in.strip() # remove trailing/leading spaces\n str_split = str_stripped.split(sep) #split at delimiter\n str_cap_correct = [i.upper()[0]+i.lower()[1:] for i in str_split]\n if formatting=='LastFirst':\n out_string = str_cap_correct[1] + ' ' + str_cap_correct[0]\n return out_string\n elif formmatting=='FirstLast':\n out_string = str_cap_correct[0] + ' ' + str_cap_correct[1]\n return out_string\n else:\n raise ValueError('formatting not set correctly')\n\n\n \nfull_names = [clean_csv_string(i) for i in all_names]\nprint(full_names)\n\n\n# By making the string cleaning steps a function, I could take the time to explain what is going on within the function, as well as control for additional possibilities (like the names being in First,Last formatting). I could make this function more robust and complex, and my final comprehension stays readable and simple, as I loop over the names and run each through my handy functions (with some settings tweaked, potentially). \n\n# ## Question 9 \n# \n# Take the arrays `XX`, `YY`, and `ZZ` below and create one multidimensional array in which they are the columns. Print to confirm this worked.\n\n# In[131]:\n\n\nXX = np.array([1,2,3,4,5,6,7,8,9])\nYY = np.array([5,6,7,8,9,10,11,12,13])\nZZ = np.array([10,11,12,13,14,15,16,17,18])\n\n#solution\ncols = np.column_stack((XX,YY,ZZ))\ncols\n\n\n# ## Question 10 \n# \n# Units, units, units. The bane of every scientists' existence... except theorists that set every constant equal to 1. \n# \n# In the real world, we measure fluxes or magnitudes in astronomical images, infer temperatures and densities from data and simulations, and ultimately have to deal with units one way or another. \n# \n# Thankfully, our friends at `astropy` know this, and they've come to save the day. This next question serves as an introduction to the `units` module in astropy, which can be both a live saver and a pain in the ass, but at the end of the day is absolutely worth learning.\n\n# In[137]:\n\n\nimport astropy.units as u\n\n\n# The standard import for this library is `u`, so be careful not to name any variables that letter. \n# \n# To \"assign\" units to a variable, we multiply by the desired unit as follows. Note that generally the module knows several aliases/common abrreviations for a unit, if it is uniquely identifiable.\n\n# In[138]:\n\n\nstar_temp = 5000*u.K \nstar_radius = 0.89 * u.Rsun \nstar_mass = 0.6 * u.Msun\n\n\n# We can perform trivial conversions using the `.to()` method.\n\n# In[139]:\n\n\nstar_radius.to(u.km)\n\n\n# Once we attach units to something, it is now a `Quantity` object. Quantity objects are great, above, we saw they have built-in methods to facilitate conversion. They can also be annoying -- sometimes another function we've written needs just the raw value or array back out. To get this, we use the `.value` attribute of a quantity object:\n\n# In[140]:\n\n\nstar_mass.to(u.kg).value\n\n\n# This now strips away all `Quantity` stuff and gives us an array or value to use elsewhere in our code. \n# \n# Units are great because they help us combine quantities while tracking units and dimensional analysis. A common operation in astronomy is converting a flux to a luminosity given a distance, using \n# \n# $$\n# F = \\frac{L}{4\\pi D^2}\n# $$\n# where $L$ is the luminosity and $D$ is the distance to the source. \n# \n# What if I've made a flux measurement in astronomical units such as erg/s/cm$^2$, and I want to know the luminosity in solar luminosities, and my distance happens to be in Mpc? Regardless of my input units, I can easily do this:\n\n# In[141]:\n\n\nL = 4 * np.pi * (3.6*u.Mpc)**2 * (7.5e-14 * u.erg/u.s/u.cm**2)\nL.to(u.Lsun)\n\n\n# This conversion worked because the units worked out. If my units of flux weren't correct, I'd get an error:\n\n# In[142]:\n\n\nL = 4 * np.pi * (3.6*u.Mpc)**2 * (7.5e-14 * u.erg/u.s/u.cm**2/u.AA)\nL.to(u.Lsun)\n\n\n# Here, `units` realized that I was putting in units of flux density, but wanted a luminosity out, and ultimately those units don't resolve out. Thus, it can be a great way to catch errors in your inputs. \n# \n# Note: just be careful that sometimes, you throw a constant into an equation but the constant has some units. If you're going to use the unit module to do a calculation, ALL inputs that HAVE units must be assigned them correctly as above for it to work.\n\n# For your exercise, consider the following: \n# \n# The virial temperature of a galaxy halo is given roughly by \n# \n# $$\n# T_{\\rm vir} \\simeq 5.6\\times10^4\\;\\textrm{K}\\left(\\frac{\\mu}{0.59}\\right)\\left(\\frac{M_{\\rm halo}}{10^{10}\\; M_{\\odot}}\\right)^{2/3}\\left(\\frac{1+z}{4}\\right)\n# $$\n\n# where here, we can assume $\\mu$ is 0.59. \n# \n# Write a function that takes as an input a halo mass, redshift, and optionally $\\mu$ (default 0.59), and returns the virial temperature in Kelvin. Your function should take in an astropy quantity with mass units, but should allow for the mass to be input with any appropriate units. \n\n# In[144]:\n\n\n# Solution \n\ndef Tvir(M,z,mu=0.59):\n return ((5.6e4*u.K)*(mu/0.59)*(M/(1e10*u.Msun))**(2/3.)*((1+z)/4)).to(u.K)\n\nTvir(10**11*u.Msun,z=3)\n\n", "meta": {"hexsha": "e5c6d467d49d7d4745dfc25c3cd2112c955c7d4a", "size": 25859, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/Lab1/Lab1_solutions.py", "max_stars_repo_name": "Astro-330/Astro-330.github.io", "max_stars_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-08-28T23:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:35:17.000Z", "max_issues_repo_path": "_build/jupyter_execute/Lab1/Lab1_solutions.py", "max_issues_repo_name": "mgebran/Astro-330.github.io", "max_issues_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/Lab1/Lab1_solutions.py", "max_forks_repo_name": "mgebran/Astro-330.github.io", "max_forks_repo_head_hexsha": "e7ba5d1db0f369a110419e939d9ed2d29c9d7020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-18T00:53:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:53:12.000Z", "avg_line_length": 38.7691154423, "max_line_length": 654, "alphanum_fraction": 0.7136780231, "include": true, "reason": "import numpy,import scipy,import astropy", "num_tokens": 6833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237174, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.08458013316632662}} {"text": "\n## python src/chapter2/chapter2.py\n## python3 src/chapter2/chapter2.py\n\nimport sys\nimport numpy as nm\nfrom numpy import arange\nimport matplotlib as mat\nimport matplotlib.pyplot as plt\n\nclass Chapter2:\n '''\n CLRS 第二章 2.1 2.2 算法函数和笔记\n '''\n def __init__(self, ok = 1, *args, **kwargs): \n '''\n Summary\n =\n These are notes of Peefy CLRS chapter1\n\n Parameters\n =\n *args : a tuple like\n **kwargs : a dict like\n\n Returns\n =\n self\n\n Example\n =\n >>> chapter2 = Chapter2(ok = 1);\n '''\n self.ok = ok\n\n def __hello():\n pass\n\n def insertSortAscending(self, array = []):\n '''\n Summary\n =\n 插入排序的升序排列\n \n Parameter\n =\n array : a list like\n Return\n =\n sortedArray : 排序好的数组\n >>> array = [1, 3, 5, 2, 4, 6]\n >>> Chapter2().insertSortAscending(array)\n >>> [1, 2, 3, 4, 5, 6]\n '''\n A = array\n n = len(A)\n for j in range(1, n):\n ## Insert A[j] into the sorted sequece A[1...j-1] 前n - 1 张牌\n # 下标j指示了待插入到手中的当前牌,所以j的索引从数组的第二个元素开始\n # 后来摸的牌\n key = A[j]\n # 之前手中的已经排序好的牌的最大索引\n i = j - 1\n # 开始寻找插入的位置并且移动牌\n while(i >= 0 and A[i] > key):\n # 向右移动牌\n A[i + 1] = A[i]\n # 遍历之前的牌\n i = i - 1\n # 后来摸的牌插入相应的位置\n A[i + 1] = key\n # 输出升序排序后的牌\n return A\n\n def insertSortDescending(self, array = []):\n '''\n Summary\n =\n 插入排序的降序排列\n\n Parameter\n =\n array : a list like\n\n Return\n =\n sortedArray : 排序好的数组\n >>> array = [1, 3, 5, 2, 4, 6]\n >>> Chapter2().insertSortAscending(array)\n >>> [6, 5, 4, 3, 2, 1]\n '''\n A = array\n n = len(A)\n for j in range(1, n):\n ## Insert A[j] into the sorted sequece A[1...j-1] 前n - 1 张牌\n # 下标j指示了待插入到手中的当前牌,所以j的索引从数组的第二个元素开始\n # 后来摸的牌\n key = A[j]\n # 之前手中的已经排序好的牌的最大索引\n i = j - 1\n # 开始寻找插入的位置并且移动牌\n while(i >= 0 and A[i] < key):\n # 向右移动牌\n A[i + 1] = A[i]\n # 遍历之前的牌\n i = i - 1\n # 后来摸的牌插入相应的位置\n A[i + 1] = key\n # 输出降序排序后的牌\n return A\n\n def arrayContains(self, array = [], v = None):\n '''\n Summary\n =\n * a function\n * *检测一个数组中是否包含一个元素*\n\n Parameter\n =\n *array* : a list like\n v : a element\n\n Return\n =\n index:若找到返回找到的索引,没找到返回None\n\n Example:\n =\n >>> array = [12, 23, 34, 45]\n >>> v = 23\n >>> m = 55\n >>> Chapter2().arrayContains(array, v)\n >>> 1\n >>> Chapter2().arrayContains(array, m)\n >>> None\n '''\n index = None\n length = len(array)\n for i in range(length):\n if v == array[i]:\n index = i\n return index\n\n def twoNBinNumAdd(self, A = [], B = []):\n '''\n Summary\n =\n 两个存放数组A和B中的n位二进制整数相加\n\n Parameter\n ====\n A : a list like and element of the list must be 0 or 1\n B : a list like and element of the list must be 0 or 1\n\n Return\n ======\n returnSum : sum of two numbers\n\n Example:\n =\n >>> A = [1, 1, 0, 0]\n >>> B = [1, 0, 0, 1]\n >>> Chapter2().twoNBinNumAdd(A, B)\n >>> [1, 0, 1, 0, 1]\n '''\n if len(A) != len(B):\n raise Exception('length of A must be equal to length of B')\n length = len(A)\n # 注意:range 函数和 arange 函数都是 左闭右开区间\n '''\n >>> range(0,3) \n >>> [0, 1, 2]\n '''\n returnSum = arange(length + 1)\n bitC = 0\n for i in range(length):\n index = length - 1 - i\n bitSum = A[index] + B[index] + bitC\n if bitSum >= 2:\n bitSum = 0\n bitC = 1\n else:\n bitC = 0\n returnSum[index + 1] = bitSum\n if index == 0:\n returnSum[0] = bitC\n return returnSum\n\n def selectSortAscending(self, array = []):\n '''\n Summary\n =\n 选择排序的升序排列\n \n Parameter\n =\n array : a list like\n Return\n =\n sortedArray : 排序好的数组\n >>> array = [1, 3, 5, 2, 4, 6]\n >>> Chapter2().selectSortAscending(array)\n >>> [1, 2, 3, 4, 5, 6]\n '''\n A = array\n length = len(A)\n for j in range(length):\n minIndex = j\n # 找出A中第j个到最后一个元素中的最小值\n # 仅需要在头n-1个元素上运行\n for i in range(j, length):\n if A[i] <= A[minIndex]:\n minIndex = i\n # 最小元素和最前面的元素交换\n min = A[minIndex]\n A[minIndex] = A[j]\n A[j] = min\n return A\n\n def note(self, *args, **kwargs):\n '''\n Summary\n =\n These are notes of Peefy CLRS chapter1\n\n Parameters\n =\n *args : a tuple like\n **kwargs : a dict like\n\n Returns\n =\n self\n\n Example\n =\n >>> Chapter2().note()\n ''' \n print('排序算法有很多,包括插入排序,冒泡排序,堆排序,归并排序,选择排序,计数排序,基数排序,桶排序,快速排序')\n print('2.1 插入排序')\n print('插入排序(INSERTION-SORT):输入n个数,输出n个数的升序或者降序排列')\n print('插入排序是一个对少量元素进行排序的有效算法,工作做原理与打牌摸牌整理手中的牌差不多')\n print('以下是Python的插入排序(升序)算法(模拟打牌)')\n print('书中的伪代码数组索引从1开始,python数组索引从0开始')\n A = [4, 4.5, 2, 5, 1.2, 3.5]\n print(\"待排序的序列:\", A)\n print(\"插入排序后的序列:\", self.insertSortAscending(A))\n print('循环不变式主要用来帮助理解插入算法的正确性。证明循环不变式的三个性质')\n print(' 1.初始化:在循环的第一轮迭代开始前,应该是正确的')\n print(' 2.保持:如果在循环的某一次迭代开始之前它是正确的,那么在下一次迭代开始前,它也应该保持正确')\n print(' 3.终止:当循环结束时,不变式给了我们一个有用的性质,有助于表明算法是正确的')\n print('数学归纳法中,要证明某一性质是成立的,必须首先证明其基本情况和一个归纳步骤都是成立的')\n print('插入排序的循环不变式证明:')\n print(' 1.初始化:插入排序第一步首相将数组中第二个元素当做待插入的元素,被插入的元素只有数组中第一元素,显然一个元素是已经排序好的')\n print(' 2.保持:证明每一轮循环都能时循环不变式保持成立,同时证明外层for循环和内层while循环同时满足循环不变式')\n print(' 3.终止:当j大于n时,外层循环结束,新的数组包含了原来数组中的元素,并且是排序好的,算法正确')\n print('布尔运算符and和or都具有短路运算能力')\n print('练习2.1-1:对于序列[31, 41, 59, 26, 41, 58]首先选出序列中第二个元素41向前插入(升序),接下来选出59向前插入,依次类推')\n print('练习2.1-2:只要把书中插入排序中的伪代码的不等号方向更换即可')\n A = [31, 41, 59, 26, 21, 58]\n print(' 排序好的降序序列为:', self.insertSortDescending(A))\n print('练习2.1-3:结果如下:')\n print(' 32在序列A中的索引为(索引从0开始):', self.arrayContains(A, 32))\n print(' 21在序列A中的索引为(索引从0开始):', self.arrayContains(A, 21)) \n print('练习2.1-4:两个n位二进制数相加的算法(适用于FPGA中。参考一位加法器的逻辑表达式或者数学表达式):')\n print(' 两个n位二进制数的和为:', self.twoNBinNumAdd([1, 1, 0, 1], [1, 0, 0, 0]))\n # range函数和np.arange函数都是左闭右开区间\n print('range(0,4)的值为:', [i for i in range(0,4)])\n print('2.2 算法分析')\n print('算法分析即指对一个算法所需要的资源进行预测')\n print('内存,通信带宽或者计算机硬件等资源是关心的资源, 通常资源指我们希望测度的计算时间')\n print('采用单处理器、随机存取机RAM计算模型')\n print('RAM模型包含了真实计算机中常见的指令:算数指令(加法,减法,除法,取余,向下取整,向上取整指令),数据移动指令(装入、存储、复制)和控制指令(条件和非条件转移、子程序调用和返回指令)')\n print('RAM模型中的数据类型有整数类型和浮点实数类型')\n print('算法分析所需要的数学工具包括组合数学、概率论、代数') \n print('需要对\"运行时间\"和\"输入规模\"更仔细地加以定义')\n print('插入排序算法的分析')\n print('插入排序INSERTION=SORT过程的时间开销与输入有关,排序1000个数的事件比排序三个数的时间要长')\n print('插入算法即使对给定规模的输入,运行时间也有可能依赖于给定的是该规模下的哪种输入')\n print('插入排序当输入是最好情况(即输入的序列已经按顺序排好),插入排序所需要的时间随输入规模是线性的O(n)')\n print('插入排序当输入是按照逆序排序的(降序排列输入后输出升序排列),就会出现最坏情况,所需要时间是输入规模的二次函数O(n^2)')\n print('一般考察算法的最坏情况运行时间')\n print('当然对于一些\"随机化\"算法,其行为即使对于固定的输入,运行时间也是可以变化的')\n print('做进一步的抽象:即运行时间的增长率,只考虑算法运行时间公式中的最高次项,并且忽略最高次项的常数系数,时间复杂度')\n print('练习题2.2-1: n^3/1000 - 100n^2 - 100n + 3 的时间复杂度:O(n^3)')\n print('练习题2.2-2:选择排序如下:')\n A = [21, 11, 9, 66, 51, 48]\n print(' 选择排序排列前的元素:', A)\n print(' 选择排序排列后的元素:', self.selectSortAscending(A))\n print(' 选择排序最好情况o(n^2),最坏情况o(n^2)')\n print(' 因为在第n-1次比较选择的时候已经比较出了最大元素和次大元素并选择,所以这时选择完之后第n个元素已经是最大值,没有必要再比较下去了')\n print('练习题2.2-3:线性查找最好情况是o(1),最坏情况是o(n),平均情况是(n)')\n print('要使算法具有较好的最佳情况运行时间就一定要对输入进行控制,使之偏向能够使得算法具有最佳运行情况的排列。')\n\n #python src/chapter2/chapter2.py\n #python3 src/chapter2/chapter2.py\n return self\n\nif __name__ == '__main__':\n print('Run main : single chapter two!')\n Chapter2().note()\nelse:\n pass\n\n## python src/chapter2/chapter2.py\n## python3 src/chapter2/chapter2.py\n\n", "meta": {"hexsha": "13030ab6af2e5ca96937fc6f17193f6ee01c0fdb", "size": 8684, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/chapter2/chapter2.py", "max_stars_repo_name": "DuGuPeefy/CLRS_dugu_code-master", "max_stars_repo_head_hexsha": "cc0b44f76c1306915e11c744f7f10aa20c98ac0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chapter2/chapter2.py", "max_issues_repo_name": "DuGuPeefy/CLRS_dugu_code-master", "max_issues_repo_head_hexsha": "cc0b44f76c1306915e11c744f7f10aa20c98ac0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chapter2/chapter2.py", "max_forks_repo_name": "DuGuPeefy/CLRS_dugu_code-master", "max_forks_repo_head_hexsha": "cc0b44f76c1306915e11c744f7f10aa20c98ac0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1035598706, "max_line_length": 109, "alphanum_fraction": 0.5038000921, "include": true, "reason": "import numpy,from numpy", "num_tokens": 3884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.1688569605068544, "lm_q1q2_score": 0.08376889617066521}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # ETHZ: 227-0966-00L\n# # Quantitative Big Imaging\n# # March 14, 2019\n#\n# ## Basic Segmentation and Discrete Binary Structures\n# ### Part 1\n\n# # Lesson Outline\n# - Motivation\n# - Qualitative Approaches\n# - Thresholding\n# - Other types of images\n# - Selecting a good threshold\n# - Implementation\n# - Morphology\n# - Contouring / Mask Creation\n\n# ### Applications\n#\n# - Simple two-phase materials (bone, cells, etc)\n# - Beyond 1 channel of depth\n# - Multiple phase materials\n# - Filling holes in materials\n# - Segmenting Fossils\n# - Attempting to segment the cortex in brain imaging\n# ![Cortex Image](ext-figures/cortex.png)\n\n# # Literature / Useful References\n#\n# - John C. Russ, “The Image Processing Handbook”,(Boca Raton, CRC Press)\n# - Available [online](http://dx.doi.org/10.1201/9780203881095) within domain ethz.ch (or proxy.ethz.ch / public VPN)\n#\n# ### Models / ROC Curves\n#\n# - [Julia Evans - Recalling with Precision](https://www.youtube.com/watch?v=ryZL4XNUmwo)\n# - [Stripe's Next Top Model](https://github.com/stripe/topmodel)\n\n# # Motivation: Why do we do imaging experiments?\n#\n#\n# - Exploratory\n# - To visually, qualitatively examine samples and differences between them\n# - No prior knowledge or expectations\n# - To test a hypothesis\n# - Quantitative assessment coupled with statistical analysis\n# - Does temperature affect bubble size?\n# - Is this gene important for cell shape and thus mechanosensation in bone?\n# - Does higher canal volume make bones weaker?\n# - Does the granule shape affect battery life expectancy?\n#\n\n# - What we are looking at\n# ![Standard Cell, http://en.wikipedia.org/wiki/File:Average_prokaryote_cell-_en.svg](ext-figures/Average_prokaryote_cell.svg)\n# - What we get from the imaging modality\n\n# In[1]:\n\n\nfrom skimage.io import imread\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\n\ndkimg = imread(\"../common/figures/Average_prokaryote_cell.jpg\")\nplt.matshow(rgb2gray(dkimg), cmap=\"bone\")\n\n\n# # To test a hypothesis\n# - We perform an experiment bone to see how big the cells are inside the tissue\n# $$\\downarrow$$ ![Bone Measurement](ext-figures/tomoimage.png)\n#\n# ### 2560 x 2560 x 2160 x 32 bit = 56GB / sample\n# - Filtering and Preprocessing!\n# $$\\downarrow$$\n# - 20h of computer time later ...\n# - 56GB of less noisy data\n# - Way too much data, we need to reduce\n#\n\n# # What did we want in the first place\n#\n#\n# ### _Single number_:\n# * volume fraction,\n# * cell count,\n# * average cell stretch,\n# * cell volume variability\n\n# # Why do we perform segmentation?\n#\n# - In model-based analysis every step we peform, simple or complicated is related to an underlying model of the system we are dealing with\n# - [_Occam's Razor_](http://en.wikipedia.org/wiki/Occams_Razor) is very important here : The simplest solution is usually the right one\n# - Bayesian, neural networks optimized using genetic algorithms with Fuzzy logic has a much larger parameter space to explore, establish sensitivity in, and must perform much better and be tested much more thoroughly than thresholding to be justified.\n# - We will cover some of these techniques in the next 2 lectures since they can be very powerful particularly with unknown data\n\n# # Review: Filtering and Image Enhancement\n#\n#\n# - This was a noise process which was added to otherwise clean imaging data\n# - $$ I_{measured}(x,y) = I_{sample}(x,y) + \\text{Noise}(x,y) $$\n# - What would the perfect filter be\n# - $$ \\textit{Filter} \\ast I_{sample}(x,y) = I_{sample}(x,y) $$\n# - $$ \\textit{Filter} \\ast \\text{Noise}(x,y) = 0 $$\n# - $$ \\textit{Filter} \\ast I_{measured}(x,y) = \\textit{Filter} \\ast I_{real}(x,y) + \\textit{Filter}\\ast \\text{Noise}(x,y) \\rightarrow \\bf I_{sample}(x,y) $$\n# - What most filters end up doing\n# $$ \\textit{Filter} \\ast I_{measured}(x,y) = 90\\% I_{real}(x,y) + 10\\% \\text{Noise}(x,y) $$\n# - What bad filters do\n# $$ \\textit{Filter} \\ast I_{measured}(x,y) = 10\\% I_{real}(x,y) + 90\\% \\text{Noise}(x,y) $$\n\n# # Qualitative Metrics: What did people used to do?\n#\n# - What comes out of our detector / enhancement process\n\n# In[2]:\n\n\nfrom skimage.io import imread\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\n\ndkimg = rgb2gray(imread(\"../common/figures/Average_prokaryote_cell.jpg\"))\nfig, (ax_hist, ax_img) = plt.subplots(1, 2, figsize=(12, 6))\n\nax_hist.hist(dkimg.ravel())\nax_hist.set_xlabel(\"Absorption Coefficient\")\nax_hist.set_ylabel(\"Pixel Count\")\n\nm_show_obj = ax_img.matshow(dkimg, cmap=\"bone\")\ncb_obj = plt.colorbar(m_show_obj)\ncb_obj.set_label(\"Absorption Coefficient\")\n\n\n# - Identify objects by eye\n# - Count, describe qualitatively: \"many little cilia on surface\", \"long curly flaggelum\", \"elongated nuclear structure\"\n# - Morphometrics\n# - Trace the outline of the object (or sub-structures)\n# - Can calculate the area by using equal-weight-paper\n# - Employing the \"[cut-and-weigh](http://ion.chem.usu.edu/~sbialkow/Classes/361/GC/GC.html)\" method\n#\n\n# # Segmentation Approaches\n#\n#\n# They match up well to the world view / perspective\n#\n# ![Approaches](../common/figures/approaches.png)\n\n# ### Model-Based\n#\n# - $\\rightarrow$ Experimentalist\n# - Problem-driven\n# - Top-down\n# - _Reality_ Model-based\n#\n#\n# ### Machine Learning Approach\n#\n# - $\\rightarrow$ Computer Vision / Deep Learning\n# - Results-driven\n\n# # Model-based Analysis\n#\n# ![Traditional Imaging](../common/figures/image-formation.png)\n#\n# - Many different imaging modalities ( $\\mu \\textrm{CT}$ to MRI to Confocal to Light-field to AFM).\n# - Similarities in underlying equations\n# - different coefficients, units, and mechanism\n#\n# $$ I_{measured}(\\vec{x}) = F_{system}(I_{stimulus}(\\vec{x}),S_{sample}(\\vec{x})) $$\n\n# # Direct Imaging (simple)\n#\n# In many setups there is un-even illumination caused by incorrectly adjusted equipment and fluctations in power and setups\n#\n# - $F_{system}(a,b) = a*b$\n# - $I_{stimulus} = \\textrm{Beam}_{profile}$\n# - $S_{system} = \\alpha(\\vec{x})$\n#\n# $\\longrightarrow \\alpha(\\vec{x})=\\frac{I_{measured}(\\vec{x})}{\\textrm{Beam}_{profile}(\\vec{x})}$\n#\n#\n\n# In[3]:\n\n\nfrom skimage.io import imread\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\nfrom skimage.morphology import disk\nfrom scipy.ndimage import zoom\nimport numpy as np\n\ncell_img = 1 - rgb2gray(imread(\"../common/figures/Average_prokaryote_cell.jpg\"))\ns_beam_img = np.pad(\n disk(2) / 1.0, [[1, 1], [1, 1]], mode=\"constant\", constant_values=0.2\n)\nbeam_img = zoom(s_beam_img, [cell_img.shape[0] / 7.0, cell_img.shape[1] / 7.0])\n\nfig, (ax_beam, ax_img, ax_det) = plt.subplots(1, 3, figsize=(12, 4))\n\nax_beam.imshow(beam_img, cmap=\"hot\")\nax_beam.set_title(\"Beam Profile\")\n\nax_img.imshow(cell_img, cmap=\"hot\")\nax_img.set_title(\"Sample Profile\")\n\nax_det.imshow(cell_img * beam_img, cmap=\"hot\")\nax_det.set_title(\"Detector\")\n\n\n# In[4]:\n\n\nfig, (ax_prof) = plt.subplots(1, 1, figsize=(12, 4))\n\nax_prof.plot(beam_img[beam_img.shape[0] // 2], label=\"Beam Profile\")\nax_prof.plot(cell_img[beam_img.shape[0] // 2], label=\"Sample Image\")\nax_prof.plot((cell_img * beam_img)[beam_img.shape[0] // 2], label=\"Detector\")\nax_prof.set_ylabel(\"Intensity\")\nax_prof.set_xlabel(\"Pixel Position\")\n# make an interactive plot\nimport plotly.offline as py\nimport plotly.tools as tls\n\npy.init_notebook_mode()\npy.iplot(tls.mpl_to_plotly(fig))\n\n\n# Frequently there is a fall-off of the beam away from the center (as is the case of a Gaussian beam which frequently shows up for laser systems). This can make extracting detail away from the center challenging\n\n# In[5]:\n\n\nfig, ax1 = plt.subplots(1, 1, figsize=(8, 8))\nax1.matshow(cell_img * beam_img, cmap=\"hot\")\n\n\n# # Absorption Imaging (X-ray, Ultrasound, Optical)\n#\n# - For absorption/attenuation imaging $\\rightarrow$ [Beer-Lambert Law](http://en.wikipedia.org/wiki/Attenuation_coefficient)\n# $$ I_{detector} = \\underbrace{I_{source}}_{I_{stimulus}}\\underbrace{\\exp(-\\alpha d)}_{S_{sample}} $$\n# - Different components have a different $\\alpha$ based on the strength of the interaction between the light and the chemical / nuclear structure of the material\n# $$ I_{sample}(x,y) = I_{source}\\exp(-\\alpha(x,y) d) $$\n# $$ \\alpha = f(N,Z,\\sigma,\\cdots) $$\n#\n# - For segmentation this model is:\n# - there are 2 (or more) distinct components that make up the image\n# - these components are distinguishable by their values (or vectors, colors, tensors, ...)\n#\n\n# In[6]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nI_source = 1.0\nd = 1.0\nalpha_1 = np.random.normal(1, 0.25, size=100)\nalpha_2 = np.random.normal(2, 0.25, size=100)\nalpha_3 = np.random.normal(3, 0.5, size=100)\n\nabs_df = pd.DataFrame(\n [\n dict(alpha=c_x, material=c_mat)\n for c_vec, c_mat in zip(\n [alpha_1, alpha_2, alpha_3], [\"material 1\", \"material 2\", \"material 3\"]\n )\n for c_x in c_vec\n ]\n)\nabs_df[\"I_detector\"] = I_source * np.exp(-abs_df[\"alpha\"] * d)\n\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8))\nfor c_mat, c_df in abs_df.groupby(\"material\"):\n ax1.scatter(x=c_df[\"alpha\"], y=c_df[\"I_detector\"], label=c_mat)\n ax3.hist(c_df[\"alpha\"], alpha=0.5, label=c_mat)\n ax2.hist(c_df[\"I_detector\"], alpha=0.5, label=c_mat, orientation=\"horizontal\")\nax1.set_xlabel(\"$\\\\alpha(x,y)$\", fontsize=15)\nax1.set_ylabel(\"$I_{detector}$\", fontsize=18)\nax1.legend()\nax2.legend()\nax3.legend(loc=0)\n\nax4.axis(\"off\")\n\n\n# # Example Mammography\n# Mammographic imaging is an area where model-based absorption imaging is problematic. Even if we assume a constant illumination (_rarely_ the case),\n#\n# $$ I_{detector} = \\underbrace{I_{source}}_{I_{stimulus}}\\underbrace{\\exp(-\\alpha d)}_{S_{sample}} $$\n# $$ \\downarrow $$\n# $$ I_{detector} = \\exp(-\\alpha(x,y) d(x,y)) $$\n# $$ \\downarrow $$\n# $$ I_{detector} = \\exp(-\\int_{0}^{l}\\alpha(x,y, z) dz) $$\n#\n\n# Specifically the problem is related to the inability to separate the $\\alpha$ and $d$ terms. We model a basic breast volume as a half sphere with a constant absorption factor.\n#\n# $$\\alpha(x,y,z) = 1e-2$$\n#\n# The $\\int$ then turns into a $\\Sigma$ in discrete space\n\n# In[7]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.morphology import ball\n\nbreast_mask = ball(50)[:, 50:]\n\n# just for 3d rendering, don't worry about it\nimport plotly.offline as py\nfrom plotly.figure_factory import create_trisurf\n\npy.init_notebook_mode()\nfrom skimage.measure import marching_cubes_lewiner\n\nvertices, simplices, _, _ = marching_cubes_lewiner(breast_mask > 0)\nx, y, z = zip(*vertices)\nfig = create_trisurf(\n x=x, y=y, z=z, plot_edges=False, simplices=simplices, title=\"Breast Phantom\"\n)\npy.iplot(fig)\n\n\n# In[8]:\n\n\nbreast_alpha = 1e-2\nbreast_vol = breast_alpha * breast_mask\ni_detector = np.exp(-np.sum(breast_vol, 2))\n\nfig, (ax_hist, ax_breast) = plt.subplots(1, 2, figsize=(20, 8))\n\nb_img_obj = ax_breast.imshow(i_detector, cmap=\"bone_r\")\nplt.colorbar(b_img_obj)\n\nax_hist.hist(i_detector.flatten())\nax_hist.set_xlabel(\"$I_{detector}$\")\nax_hist.set_ylabel(\"Pixel Count\")\n\n\n# If we know that $\\alpha$ is constant we can reconstruct d from the image\n\n# In[9]:\n\n\nbreast_thickness = -np.log(i_detector) / breast_alpha\nfig, (ax_hist, ax_breast) = plt.subplots(1, 2, figsize=(12, 5))\n\nb_img_obj = ax_breast.imshow(breast_thickness, cmap=\"bone\")\nplt.colorbar(b_img_obj)\n\nax_hist.hist(breast_thickness.flatten())\nax_hist.set_xlabel(\"Breast Thickness ($d$)\\nIn Pixels\")\nax_hist.set_ylabel(\"Pixel Count\")\n\n\n# In[10]:\n\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(8, 4), dpi=200)\nax = fig.gca(projection=\"3d\")\n# Plot the surface.\nyy, xx = np.meshgrid(\n np.linspace(0, 1, breast_thickness.shape[1]),\n np.linspace(0, 1, breast_thickness.shape[0]),\n)\nsurf = ax.plot_surface(\n xx, yy, breast_thickness, cmap=plt.cm.jet, linewidth=0, antialiased=False\n)\nax.view_init(elev=30, azim=45)\nax.set_zlabel(\"Breast Thickness\")\n\n\n# We run into problems when the $\\alpha$ is no longer constant. For example if we place a dark lump in the center of the breast. It is impossible to tell if the breast if thicker or if the lump inside is denser. For the lump below we can see on the individual slices of the sample that the lesion appears quite clearly and is very strangely shaped.\n\n# In[11]:\n\n\nbreast_vol = breast_alpha * breast_mask\nrenorm_slice = np.sum(breast_mask[10:40, 0:25], 2) / np.sum(breast_mask[30, 10])\nbreast_vol[10:40, 0:25] /= np.stack([renorm_slice] * breast_vol.shape[2], -1)\n\nfrom skimage.util import montage as montage2d\n\nfig, ax1 = plt.subplots(1, 1, figsize=(12, 12))\nax1.imshow(\n montage2d(breast_vol.swapaxes(0, 2).swapaxes(1, 2)[::3]),\n cmap=\"bone\",\n vmin=breast_alpha * 0.8,\n vmax=breast_alpha * 1.2,\n)\n\n\n# When we make the projection and apply Beer's Law we see that it appears as a relatively constant region in the image\n\n# In[12]:\n\n\ni_detector = np.exp(-np.sum(breast_vol, 2))\n\nfig, (ax_hist, ax_breast) = plt.subplots(1, 2, figsize=(20, 8))\n\nb_img_obj = ax_breast.imshow(i_detector, cmap=\"bone_r\")\nplt.colorbar(b_img_obj)\n\nax_hist.hist(i_detector.flatten())\nax_hist.set_xlabel(\"$I_{detector}$\")\nax_hist.set_ylabel(\"Pixel Count\")\n\n\n# And as a flat constant region in the thickness reconstruction. So we fundamentally from this single image cannot answer is the breast oddly shaped or does it have an possible tumor inside of it\n\n# In[13]:\n\n\nbreast_thickness = -np.log(i_detector) / 1e-2\nfig, (ax_hist, ax_breast) = plt.subplots(1, 2, figsize=(12, 5))\n\nb_img_obj = ax_breast.imshow(breast_thickness, cmap=\"bone\")\nplt.colorbar(b_img_obj)\n\nax_hist.hist(breast_thickness.flatten())\nax_hist.set_xlabel(\"Breast Thickness ($d$)\\nIn Pixels\")\nax_hist.set_ylabel(\"Pixel Count\")\n\n\n# In[14]:\n\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(8, 4), dpi=200)\nax = fig.gca(projection=\"3d\")\n# Plot the surface.\nyy, xx = np.meshgrid(\n np.linspace(0, 1, breast_thickness.shape[1]),\n np.linspace(0, 1, breast_thickness.shape[0]),\n)\nsurf = ax.plot_surface(\n xx, yy, breast_thickness, cmap=plt.cm.jet, linewidth=0, antialiased=False\n)\nax.view_init(elev=30, azim=130)\nax.set_zlabel(\"Breast Thickness\")\n\n\n# # Where does segmentation get us?\n#\n#\n# - We convert a decimal value (or something even more complicated like 3 values for RGB images, a spectrum for hyperspectral imaging, or a vector / tensor in a mechanical stress field)\n# - to a single, discrete value (usually true or false, but for images with phases it would be each phase, e.g. bone, air, cellular tissue)\n#\n# - __2560 x 2560 x 2160 x 32 bit = 56GB / sample__\n# $$\\downarrow$$\n# - 2560 x 2560 x 2160 x **1 bit** = 1.75GB / sample\n#\n\n# # Applying a threshold to an image\n# Start out with a simple image of a cross with added noise\n# $$ I(x,y) = f(x,y) $$\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nnx = 5\nny = 5\nxx, yy = np.meshgrid(\n np.arange(-nx, nx + 1) / nx * 2 * np.pi, np.arange(-ny, ny + 1) / ny * 2 * np.pi\n)\ncross_im = 1.5 * np.abs(np.cos(xx * yy)) / (\n np.abs(xx * yy) + (3 * np.pi / nx)\n) + np.random.uniform(-0.25, 0.25, size=xx.shape)\nplt.matshow(cross_im, cmap=\"hot\")\nplt.colorbar()\n\n\n# The intensity can be described with a probability density function\n# $$ P_f(x,y) $$\n\n# In[16]:\n\n\nfig, ax1 = plt.subplots(1, 1)\nax1.hist(cross_im.ravel(), 20)\nax1.set_title(\"$P_f(x,y)$\")\nax1.set_xlabel(\"Intensity\")\nax1.set_ylabel(\"Pixel Count\")\n\n\n# # Applying a threshold to an image\n#\n# By examining the image and probability distribution function, we can _deduce_ that the underyling model is a whitish phase that makes up the cross and the darkish background\n#\n# Applying the threshold is a deceptively simple operation\n#\n# $$ I(x,y) =\n# \\begin{cases}\n# 1, & f(x,y)\\geq0.40 \\\\\n# 0, & f(x,y)<0.40\n# \\end{cases}$$\n\n# In[17]:\n\n\nfig, ax1 = plt.subplots(1, 1)\nax1.imshow(cross_im, cmap=\"hot\", extent=[xx.min(), xx.max(), yy.min(), yy.max()])\nthresh_img = cross_im > 0.4\n\nax1.plot(\n xx[np.where(thresh_img)],\n yy[np.where(thresh_img)],\n \"ks\",\n markerfacecolor=\"green\",\n alpha=0.5,\n label=\"threshold\",\n markersize=20,\n)\nax1.legend()\n\n\n# # Various Thresholds\n# We can see the effect of choosing various thresholds\n#\n\n# In[18]:\n\n\nfig, m_axs = plt.subplots(3, 3, figsize=(15, 15))\nfor c_thresh, ax1 in zip(np.linspace(0.1, 0.9, 9), m_axs.flatten()):\n\n ax1.imshow(cross_im, cmap=\"bone\", extent=[xx.min(), xx.max(), yy.min(), yy.max()])\n thresh_img = cross_im > c_thresh\n\n ax1.plot(\n xx[np.where(thresh_img)],\n yy[np.where(thresh_img)],\n \"rs\",\n alpha=0.5,\n label=\"img>%2.2f\" % c_thresh,\n markersize=20,\n )\n ax1.legend(loc=1)\n\n\n# # Segmenting Cells\n#\n# - We can peform the same sort of analysis with this image of cells\n# - This time we can derive the model from the basic physics of the system\n# - The field is illuminated by white light of nearly uniform brightness\n# - Cells absorb light causing darker regions to appear in the image\n# - _Lighter_ regions have no cells\n# - __Darker__ regions have cells\n\n# In[19]:\n\n\nfrom skimage.io import imread\nfrom skimage.color import rgb2gray\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ncell_img = rgb2gray(imread(\"../common/figures/Cell_Colony.jpg\"))\nfig, (ax_hist, ax_img) = plt.subplots(1, 2, figsize=(12, 6))\nax_hist.hist(cell_img.ravel(), np.arange(255))\nax_obj = ax_img.matshow(cell_img, cmap=\"bone\")\nplt.colorbar(ax_obj)\n\n\n# In[20]:\n\n\nfrom skimage.color import label2rgb\n\nfig, m_axs = plt.subplots(3, 3, figsize=(15, 15), dpi=200)\nfor c_thresh, ax1 in zip(np.linspace(100, 200, 9), m_axs.flatten()):\n thresh_img = cell_img < c_thresh\n\n ax1.imshow(label2rgb(thresh_img, image=1 - cell_img, bg_label=0, alpha=0.4))\n\n ax1.set_title(\"img<%2.2f\" % c_thresh)\n\n\n# # Other Image Types\n#\n# While scalar images are easiest, it is possible for any type of image\n# $$ I(x,y) = \\vec{f}(x,y) $$\n\n# In[21]:\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnx = 10\nny = 10\nxx, yy = np.meshgrid(\n np.linspace(-2 * np.pi, 2 * np.pi, nx), np.linspace(-2 * np.pi, 2 * np.pi, ny)\n)\n\nintensity_img = 1.5 * np.abs(np.cos(xx * yy)) / (\n np.abs(xx * yy) + (3 * np.pi / nx)\n) + np.random.uniform(-0.25, 0.25, size=xx.shape)\n\nbase_df = pd.DataFrame(\n dict(x=xx.ravel(), y=yy.ravel(), I_detector=intensity_img.ravel())\n)\n\nbase_df[\"x_vec\"] = base_df.apply(\n lambda c_row: c_row[\"x\"]\n / np.sqrt(1e-2 + np.square(c_row[\"x\"]) + np.square(c_row[\"y\"])),\n 1,\n)\nbase_df[\"y_vec\"] = base_df.apply(\n lambda c_row: c_row[\"y\"]\n / np.sqrt(1e-2 + np.square(c_row[\"x\"]) + np.square(c_row[\"y\"])),\n 1,\n)\n\nbase_df.head(5)\n\n\n# In[22]:\n\n\nimport seaborn as sns\n\nsns.pairplot(base_df)\n\n\n# In[23]:\n\n\nfig, ax1 = plt.subplots(1, 1, figsize=(8, 8))\nax1.quiver(\n base_df[\"x\"],\n base_df[\"y\"],\n base_df[\"x_vec\"],\n base_df[\"y_vec\"],\n base_df[\"I_detector\"],\n cmap=\"hot\",\n)\n\n\n# # Applying a threshold\n#\n# A threshold is now more difficult to apply since there are now two distinct variables to deal with. The standard approach can be applied to both\n# $$ I(x,y) =\n# \\begin{cases}\n# 1, & \\vec{f}_x(x,y) \\geq0.25 \\text{ and}\\\\\n# & \\vec{f}_y(x,y) \\geq0.25 \\\\\n# 0, & \\text{otherwise}\n# \\end{cases}$$\n\n# In[24]:\n\n\nthresh_df = base_df.copy()\nthresh_df[\"thresh\"] = thresh_df.apply(\n lambda c_row: c_row[\"x_vec\"] > 0.25 and c_row[\"y_vec\"] > 0.25, 1\n)\n\nfig, ax1 = plt.subplots(1, 1, figsize=(8, 8))\nax1.quiver(\n thresh_df[\"x\"],\n thresh_df[\"y\"],\n thresh_df[\"x_vec\"],\n thresh_df[\"y_vec\"],\n thresh_df[\"thresh\"],\n cmap=\"hot\",\n)\n\n\n# This can also be shown on the joint probability distribution as\n\n# In[25]:\n\n\nfig, ax1 = plt.subplots(1, 1, figsize=(4, 4), dpi=200)\nax1.hist2d(thresh_df[\"x_vec\"], thresh_df[\"y_vec\"], cmap=\"hot\")\nax1.set_xlabel(\"$\\\\vec{f}_x(x,y)$\")\nax1.set_ylabel(\"$\\\\vec{f}_y(x,y)$\")\n\n\n# # Applying a threshold\n# Given the presence of two variables; however, more advanced approaches can also be investigated. For example we can keep only components parallel to the x axis by using the dot product.\n# $$ I(x,y) =\n# \\begin{cases}\n# 1, & |\\vec{f}(x,y)\\cdot \\vec{i}| = 1 \\\\\n# 0, & \\text{otherwise}\n# \\end{cases}$$\n\n# # Looking at Orientations\n# We can tune the angular acceptance by using the fact $$\\vec{x}\\cdot\\vec{y}=|\\vec{x}| |\\vec{y}| \\cos(\\theta_{x\\rightarrow y}) $$\n# $$ I(x,y) =\n# \\begin{cases}\n# 1, & \\cos^{-1}(\\vec{f}(x,y)\\cdot \\vec{i}) \\leq \\theta^{\\circ} \\\\\n# 0, & \\text{otherwise}\n# \\end{cases}$$\n", "meta": {"hexsha": "4860374ff94fe108570b8f6018940558ef2350f6", "size": 20374, "ext": "py", "lang": "Python", "max_stars_repo_path": "Lectures/04-BasicSegmentation.py", "max_stars_repo_name": "kmader/qbi-2019-py", "max_stars_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-11-06T16:20:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T03:38:02.000Z", "max_issues_repo_path": "Lectures/04-BasicSegmentation.py", "max_issues_repo_name": "kmader/qbi-2019-py", "max_issues_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-11-06T16:41:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-07T13:02:17.000Z", "max_forks_repo_path": "Lectures/04-BasicSegmentation.py", "max_forks_repo_name": "kmader/qbi-2019-py", "max_forks_repo_head_hexsha": "25ca789cc35e02ac02eaa5e1943093ef55c096a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-09T10:43:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T10:43:55.000Z", "avg_line_length": 28.6151685393, "max_line_length": 348, "alphanum_fraction": 0.6891135761, "include": true, "reason": "import numpy,from scipy", "num_tokens": 6163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.18476751289253923, "lm_q1q2_score": 0.08374806434687902}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # 16 - AgriPV - 3-up and 4-up collector optimization\n# \n# \n# This journal helps the exploration of varying collector widths and xgaps in the ground underneath as well as on the rear irradiance for bifacial AgriPV. The optimization varies the numpanels combinations with xgaps for having 3-up and 4-up collectors with varying space along the row (xgap). The actual raytracing is not performed in the jupyter journal but rather on the HPC, but the geometry is the same as presented here.\n# \n# The steps on this journal:\n#
    \n#
  1. Making Collectors for each number panel and xgap case
  2. \n#
  3. Builds the Scene so it can be viewed with rvu
  4. \n# \n# \n# An area of 40m x 20 m area is sampled on the HPC, and is highlighted in the visualizations below with an appended terrain of 'litesoil'. The image below shows the two extremes of the variables optimized and the raytrace results, including the worst-case shading experienced under the array ( 100 - min_irradiance *100 / GHI).\n# \n# \n# \n# ![AgriPV Collector Width and Xgap Optimization](../images_wiki/AdvancedJournals/AgriPV_CWandXgap_Optimization.PNG)\n# \n\n# In[1]:\n\n\nimport os\nfrom pathlib import Path\n\ntestfolder = Path().resolve().parent.parent / 'bifacial_radiance' / 'TEMP' / 'Tutorial_16'\nif not os.path.exists(testfolder):\n os.makedirs(testfolder)\n\nprint (\"Your simulation will be stored in %s\" % testfolder)\n\n\n# In[2]:\n\n\nimport bifacial_radiance\nimport numpy as np\n\nrad_obj = bifacial_radiance.RadianceObj('tutorial_16', str(testfolder)) \n\n\n# \n\n# ## 1. Making Collectors for each number panel and xgap case\n\n# In[3]:\n\n\nx = 2\ny = 1\nygap = 0.1524 # m = 6 in\nzgap = 0.002 # m, veyr little gap to torquetube.\n\ntubeParams = {'diameter':0.15,\n 'tubetype':'square',\n 'material':'Metal_Grey',\n 'axisofrotation':True,\n 'visible': True}\n\nft2m = 0.3048\nxgaps = [3, 4, 6, 9, 12, 15, 18, 21]\nnumpanelss = [3, 4]\n\n\n# Loops\nfor ii in range(0, len(numpanelss)):\n numpanels = numpanelss[ii]\n for jj in range(0, len(xgaps)):\n xgap = xgaps[jj]*ft2m\n\n moduletype = 'test-module_'+str(numpanels)+'up_'+str(round(xgap,1))+'xgap'\n rad_obj.makeModule(moduletype, \n x=x, y=y, \n xgap=xgap, zgap=zgap, ygap = ygap, numpanels=numpanels, \n tubeParams=tubeParams)\n\n\n# \n\n# ## 2. Build the Scene so it can be viewed with rvu\n\n# In[4]:\n\n\nxgaps = np.round(np.array([3, 4, 6, 9, 12, 15, 18, 21]) * ft2m,1)\nnumpanelss = [3, 4]\nsensorsxs = np.array(list(range(0, 201))) \n\n# Select CASE:\nxgap = np.round(xgaps[-1],1)\nnumpanels = 4\n\n# All the rest\n\nft2m = 0.3048\nhub_height = 8.0 * ft2m\ny = 1\npitch = 0.001 # If I recall, it doesn't like when pitch is 0 even if it's a single row, but any value works here. \nygap = 0.15\ntilt = 18\n\nsim_name = ('Coffee_'+str(numpanels)+'up_'+\n str(round(xgap,1))+'_xgap')\n\nalbedo = 0.35 # Grass value from Torres Molina, \"Measuring UHI in Puerto Rico\" 18th LACCEI \n # International Multi-Conference for Engineering, Education, and Technology\n\nazimuth = 180\nif numpanels == 3:\n nMods = 9\nif numpanels == 4:\n nMods = 7\nnRows = 1\n\nmoduletype = 'test-module_'+str(numpanels)+'up_'+str(round(xgap,1))+'xgap'\n\nrad_obj.setGround(albedo)\nlat = 18.202142\nlon = -66.759187\nmetfile = rad_obj.getEPW(lat,lon)\nrad_obj.readWeatherFile(metfile)\n\nsceneDict = {'tilt':tilt,'pitch':pitch,'hub_height':hub_height,'azimuth':azimuth, 'nMods': nMods, 'nRows': nRows} \nscene = rad_obj.makeScene(module=moduletype,sceneDict=sceneDict, radname = sim_name)\n\nrad_obj.gendaylit(4020)\n\n\noctfile = rad_obj.makeOct(filelist = rad_obj.getfilelist(), octname = rad_obj.basename) \n\nname='SampleArea'\ntext='! genbox litesoil cuteBox 40 20 0.01 | xform -t -20 -10 0.01'\ncustomObject =rad_obj.makeCustomObject(name,text)\nrad_obj.appendtoScene(scene.radfiles, customObject, '!xform -rz 0')\n\noctfile = rad_obj.makeOct(rad_obj.getfilelist()) \n\n\n# \n# ### To View the generated Scene, you can navigate to the testfolder on a terminal and use:\n# \n# front view:\n# > rvu -vf views\\front.vp -e .0265652 -vp 2 -21 2.5 -vd 0 1 0 makemod.oct\n# \n# top view: \n# > rvu -vf views\\front.vp -e .0265652 -vp 5 0 70 -vd 0 0.0001 -1 makemod.oct\n# \n# ### Or run it directly from Jupyter by removing the comment from the following cell:\n# \n\n# In[5]:\n\n\n\n## Comment the ! line below to run rvu from the Jupyter notebook instead of your terminal.\n## Simulation will stop until you close the rvu window\n\n#!rvu -vf views\\front.vp -e .0265652 -vp 2 -21 2.5 -vd 0 1 0 makemod.oct\n#!rvu -vf views\\front.vp -e .0265652 -vp 5 0 70 -vd 0 0.0001 -1 makemod.oct\n\n", "meta": {"hexsha": "d55ee118bd3f4348551af4c9c648fd48b54e6807", "size": 4772, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/tutorials/16 - AgriPV - 3-up and 4-up collector optimization.py", "max_stars_repo_name": "kperrynrel/bifacial_radiance", "max_stars_repo_head_hexsha": "cf5ae46b4ef93990e3e1619956a186376cb4fd8a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/tutorials/16 - AgriPV - 3-up and 4-up collector optimization.py", "max_issues_repo_name": "kperrynrel/bifacial_radiance", "max_issues_repo_head_hexsha": "cf5ae46b4ef93990e3e1619956a186376cb4fd8a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/16 - AgriPV - 3-up and 4-up collector optimization.py", "max_forks_repo_name": "kperrynrel/bifacial_radiance", "max_forks_repo_head_hexsha": "cf5ae46b4ef93990e3e1619956a186376cb4fd8a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2760736196, "max_line_length": 426, "alphanum_fraction": 0.6766554904, "include": true, "reason": "import numpy", "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.17328819952513227, "lm_q1q2_score": 0.08258562966314019}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: all\n# formats: ipynb,py:percent\n# notebook_metadata_filter: all,-language_info,-toc,-latex_envs\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown] toc=true\n#\n# # Plotting\n#\n# single: MatPlotLib single: plots\n#\n# The graphical representation of data---plotting---is one of the most\n# important tools for evaluating and understanding scientific data and\n# theoretical predictions. However, plotting is not a part of core Python\n# but is provided through one of several possible library modules. The\n# most highly developed and widely used plotting package for Python is\n# MatPlotLib (). It is a powerful and\n# flexible program that has become the *de facto* standard for 2-d\n# plotting with Python.\n#\n# Because MatPlotLib is an external library---in fact it's a collection of\n# libraries---it must be imported into any routine that uses it.\n# MatPlotLib makes extensive use of NumPy so the two should be imported\n# together. Therefore, for any program for which you would like to produce\n# 2-d plots, you should include the lines\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n# ```\n#\n# There are other MatPlotLib sub-libraries, but the `pyplot` library\n# provides nearly everything that you need for 2-d plotting. The standard\n# prefix for it is `plt`. The two statements above must appear before any\n# calls to NumPy or MatPlotLib routines are made.\n#\n# One final word before we get started: We only scratch the surface of\n# what is possible using MatPlotLib and as you become familiar with it,\n# you will surely want to do more than this manual describes. In that\n# case, you need to go the the web to get more information. A good place\n# to start is . Another\n# interesting web page is .\n#\n# An interactive session with `pyplot`\n# ------------------------------------\n#\n# single: plots; interactive\n#\n# We begin with an interactive plotting session that illustrates some very\n# basic features of MatPlotLib. Type in the `plot` command shown below and\n# press the return key. Take care to follow the exact syntax.\n#\n# ``` ipython\n# In [1]: plt.plot([1,2,3,2,3,4,3,4,5])\n# Out[1]: []\n# ```\n#\n#
    \n# \"\"
    Interactive plot window
    \n#
    \n#\n# A window should appear with a plot that looks something like the\n# `fig-zigzagPlotDemo` shown here. By default, the `plot` function draws a\n# line between the data points that were entered. You can save this plot\n# to an image file by clicking on the floppy disk icon at the top of the\n# plot window. You can also zoom, pan, scroll through the plot, and return\n# to the original view using the other icons in the plot window.\n# Experimenting with them reveals their functions.\n#\n# When you are finished, be sure to close the plot window.\n#\n# Let's take a closer look at the `plot` function. It is used to plot\n# $x$-$y$ data sets and is written like this\n#\n# ``` python\n# plt.plot(x, y)\n# ```\n#\n# where `x` and `y` are arrays (or lists) that have the same size. If the\n# `x` array is missing, that is, if there is only a single array, as in\n# our example above, the `plot` function uses `0, 1, ..., N-1` for the `x`\n# array, where `N` is the size of the `y` array. Thus, the `plot` function\n# provides a quick graphical way of examining a data set.\n#\n# More typically, you supply both an $x$ and a $y$ data set to plot.\n# Taking things a bit further, you may also want to plot several data sets\n# on the same graph, use symbols as well as lines, label the axes, create\n# a title and a legend, and control the color of symbols and lines. All of\n# this is possible but requires calling a number of plotting functions.\n# For this reason, plotting is usually done using a Python script or\n# program.\n#\n# Basic plotting\n# --------------\n#\n# single: plots; basic\n#\n# The quickest way to learn how to plot using the MatPlotLib library is by\n# example. For our first task, let's plot the sine function over the\n# interval from 0 to $4\\pi$. The main plotting function `plot` in\n# MatPlotLib does not plot functions *per se*, it plots $(x,y)$ data\n# points. As we shall see, we can instruct the function `plot` either to\n# just draw point---or dots---at each data point, or we can instruct it to\n# draw straight lines between the data points. To create the illusion of\n# the smooth function that the sine function is, we need to create enough\n# $(x,y)$ data points so that when `plot` draws straight lines between the\n# data points, the function appears to be smooth. The sine function\n# undergoes two full oscillations with two maxima and two minima between 0\n# and $4\\pi$. So let's start by creating an array with 33 data points\n# between 0 and $4\\pi$, and then let MatPlotLib draw a straight line\n# between them. Our code consists of four parts\n#\n# - import the NumPy and MatPlotLib modules (lines 1-2 below)\n# - create the $(x,y)$ data arrays (lines 3-4 below)\n# - have `plot` draw straight lines between the $(x,y)$ data points\n# (line 5 below)\n# - display the plot in a figure window using the `show` function (line\n# 6 below)\n#\n# Here is our code, which consists of only 6 lines:\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n# x = np.linspace(0, 4.*np.pi, 33)\n# y = np.sin(x)\n# plt.plot(x, y)\n# plt.show()\n# ```\n#\n#
    \n# \"\"
    Sine function
    \n#
    \n#\n# Only 6 lines suffice to create the plot, which consists of the sine\n# function over the interval from 0 to $4\\pi$, as advertised, as well as\n# axes annotated with nice whole numbers over the appropriate interval.\n# It's a pretty nice plot made with very little code.\n#\n# One problem, however, is that while the plot oscillates like a sine\n# wave, it is not smooth. This is because we did not create the $(x,y)$\n# arrays with enough data points. To correct this, we need more data\n# points. The plot below was created using the same program shown above\n# but with 129 $(x,y)$ data points instead of 33. Try it out your self by\n# copying the above program and replacing 33 in line 3 with 129 so that\n# the function `linspace` creates an array with 129 data points instead of\n# 33.\n#\n#
    \n# \"\"
    Sine function plotted using more data points
    \n#
    \n#\n# The code above illustrates how plots can be made with very little code\n# using the MatPlotLib module. In making this plot, MatPlotLib has made a\n# number of choices, such as the size of the figure, the blue color of the\n# line, even the fact that by default a line is drawn between successive\n# data points in the $(x,y)$ arrays. All of these choices can be changed\n# by explicitly instructing MatPlotLib to do so. This involves including\n# more arguments in the function calls we have used and using new\n# functions that control other properties of the plot. The next example\n# illustrates a few of the simpler embellishments that are possible.\n#\n# In the `fig-WavyPulse` figure, we plot two $(x,y)$ data sets: a smooth\n# line curve and some data represented by red circles. In this plot, we\n# label the $x$ and $y$ axes, create a legend, and draw lines to indicate\n# where $x$ and $y$ are zero. The code that creates this plot is shown\n# below.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# # read data from file\n# xdata, ydata = np.loadtxt('wavePulseData.txt', unpack=True)\n#\n# # create x and y arrays for theory\n# x = np.linspace(-10., 10., 200)\n# y = np.sin(x) * np.exp(-(x/5.0)**2)\n#\n# # create plot\n# plt.figure(1, figsize = (6,4) )\n# plt.plot(x, y, 'b-', label='theory')\n# plt.plot(xdata, ydata, 'ro', label=\"data\")\n# plt.xlabel('x')\n# plt.ylabel('transverse displacement')\n# plt.legend(loc='upper right')\n# plt.axhline(color = 'gray', zorder=-1)\n# plt.axvline(color = 'gray', zorder=-1)\n#\n# # save plot to file\n# plt.savefig('WavyPulse.pdf')\n#\n# # display plot on screen\n# plt.show()\n# ```\n#\n#
    \n# \"\"
    Wavy pulse
    \n#
    \n#\n# If you have read the first four chapters, the code in lines 1-9 in the\n# above script should be familiar to you. Fist, the script loads the NumPy\n# and MatPlotLib modules, then reads data from a data file into two\n# arrays, `xdata` and `ydata`, and then creates two more arrays, `x` and\n# `y`. The first pair or arrays, `xdata` and `ydata`, contain the $x$-$y$\n# data that are plotted as red circles in the `fig-WavyPulse` figure; the\n# arrays created in line 8 and 9 contain the $x$-$y$ data that are plotted\n# as a blue line.\n#\n# The functions that do the plotting begin on line 12. Let's go through\n# them one by one and see what they do. You will notice in several cases\n# that *keyword arguments* (`kwargs`) are used in several cases. Keyword\n# arguments are *optional* arguments that have the form `kwarg=` *data*,\n# where *data* might be a number, a string, a tuple, or some other form of\n# data.\n#\n# > `figure()` \n# > creates a blank figure window. If it has no arguments, it creates a\n# > window that is 8 inches wide and 6 inches high by default, although\n# > the size that appears on your computer depends on your screen's\n# > resolution. For most computers, it will be much smaller. You can\n# > create a window whose size differs from the default using the optional\n# > keyword argument `figsize`, as we have done here. If you use\n# > `figsize`, set it equal to a 2-element tuple where the elements are\n# > the width and height, respectively, of the plot. Multiple calls to\n# > `figure()` opens multiple windows: `figure(1)` opens up one window for\n# > plotting, `figure(2)` another, and `figure(3)` yet another.\n# >\n# > `plot(x, y,` *optional arguments* `)` \n# > graphs the $x$-$y$ data in the arrays `x` and `y`. The third argument\n# > is a format string that specifies the color and the type of line or\n# > symbol that is used to plot the data. The string `'ro'` specifies a\n# > red (`r`) circle (`o`). The string `'b-'` specifies a blue (`b`) solid\n# > line (`-`). The keyword argument `label` is set equal to a string that\n# > labels the data if the `legend` function is called subsequently.\n# >\n# > `xlabel(` *string* `)` \n# > takes a string argument that specifies the label for the graph's\n# > $x$-axis.\n# >\n# > `ylabel(` *string* `)` \n# > takes a string argument that specifies the label for the graph's\n# > $y$-axis.\n# >\n# > `legend()` \n# > makes a legend for the data plotted. Each $x$-$y$ data set is labeled\n# > using the string that was supplied by the `label` keyword in the\n# > `plot` function that graphed the data set. The `loc` keyword argument\n# > specifies the location of the legend.\n# >\n# > `axhline()` \n# > draws a horizontal line across the width of the plot at `y=0`. The\n# > optional keyword argument `color` is a string that specifies the color\n# > of the line. The default color is black. The optional keyword argument\n# > `zorder` is an integer that specifies which plotting elements are in\n# > front of or behind others. By default, new plotting elements appear\n# > *on top of* previously plotted elements and have a value of\n# > `zorder=0`. By specifying `zorder=-1`, the horizontal line is plotted\n# > *behind* all existing plot elements that have not be assigned an\n# > explicit `zorder` less than -1.\n# >\n# > `axvline()` \n# > draws a vertical line from the top to the bottom of the plot at `x=0`.\n# > See `axhline()` for explanation of the arguments.\n# >\n# > `savefig(` *string* `)` \n# > saves the figure to data data file with a name specified by the string\n# > argument. The string argument can also contain path information if you\n# > want to save the file so some place other than the default directory.\n# >\n# > `show()` \n# > displays the plot on the computer screen. No screen output is produced\n# > before this function is called.\n#\n# single: MatPlotLib functions; figure single: MatPlotLib functions; plot\n# single: MatPlotLib functions; xlabel, ylabel single: MatPlotLib\n# functions; legend single: MatPlotLib functions; ayhline, axhline single:\n# MatPlotLib functions; savefig single: MatPlotLib functions; show\n#\n# To plot the solid blue line, the code uses the `'b-'` format specifier\n# in the `plot` function call. It is important to understand that\n# MatPlotLib draws *straight lines* between data points. Therefore, the\n# curve will appear smooth only if the data in the NumPy arrays are\n# sufficiently dense. If the space between data points is too large, the\n# straight lines the `plot` function draws between data points will be\n# visible. For plotting a typical function, something on the order of\n# 100-200 data points usually produces a smooth curve, depending on just\n# how curvy the function is. On the other hand, only two points are\n# required to draw a smooth straight line.\n#\n# Detailed information about the MatPlotLib plotting functions are\n# available online, starting with the site\n# . The main MatPlotLib\n# site is .\n#\n# ### Specifying line and symbol types and colors\n#\n# In the above example, we illustrated how to draw one line type (solid),\n# one symbol type (circle), and two colors (blue and red). There are many\n# more possibilities, which are specified in the tables below. The way it\n# works is to specify a string consisting of one or more plotting format\n# specifiers. There are two types of format specifiers, one for the line\n# or symbol type and another for the color. It does not matter in which\n# order the format specifiers are listed in the string. Examples are given\n# following the two tables. Try them out to make sure you understand how\n# these plotting format specifiers work.\n#\n# single: plots; line and symbol specifiers\n#\n# The first table below shows the characters used to specify the line or\n# symbol type that is used. If a line type is chosen, the lines are drawn\n# between the data points. If a marker type is chosen, the a marker is\n# plotted at each data point.\n#\n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# >
    characterdescriptioncharacterdescription
    -solid line style3tri_left marker
    --dashed line style4tri_right marker
    -.dash-dot line stylessquare marker
    :dotted line styleppentagon marker
    .point marker*star marker
    ,pixel markerhhexagon1 marker
    ocircle markerHhexagon2 marker
    vtriangle_down marker+plus marker
    ^triangle_up markerxx marker
    <triangle_left markerDdiamond marker
    >triangle_right markerdthin_diamond marker
    1tri_down marker|vline marker
    2tri_up marker_hline marker
    \n# >\n# This second table gives the character codes for eight different colors.\n# Many more are possible but the color specification becomes more complex.\n# You can consult the web-based MatPlotLib documentation for further\n# details.\n#\n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# > \n# >
    charactercolor
    bblue
    ggreen
    rred
    ccyan
    mmagenta
    yyellow
    kblack
    wwhite
    \n# >\n# Here are some examples of how these format specifiers can be used:\n#\n# ``` python\n# plot(x, y, 'ro') # plots red circles\n# plot(x, y, 'ks-') # plot black squares connected by black lines\n# plot(x, y, 'g^') # plots green triangles that point up\n#\n# plot(x, y, 'k-') # plots a black line between the points\n# plot(x, y, 'ms') # plots magenta squares \n# ```\n#\n# You can also make two calls sequentially for added versatility. For\n# example, by sequentially calling the last two plot calls, the plot\n# produces magenta squares on top of black lines connecting the data\n# points.\n#\n# These format specifiers give rudimentary control of the plotting symbols\n# and lines. MatPlotLib provides much more precise and detailed control of\n# the plotting symbol size, line types, and colors using optional keyword\n# arguments instead of the plotting format strings introduced above. For\n# example, the following command creates a plot of large yellow diamond\n# symbols with blue edges connected by a green dashed line:\n#\n# ``` python\n# plt.plot(x, y, color='green', linestyle='dashed', marker='d', \n# markerfacecolor='yellow', markersize=12, \n# markeredgecolor='blue')\n# ```\n#\n# Try it out! The online MatPlotLib documentation provides all the\n# plotting format keyword arguments and their possible values.\n#\n# ### Error bars\n#\n# single: plots; error bars\n#\n# When plotting experimental data it is customary to include error bars\n# that indicate graphically the degree of uncertainty that exists in the\n# measurement of each data point. The MatPlotLib function `errorbar` plots\n# data with error bars attached. It can be used in a way that either\n# replaces or augments the `plot` function. Both vertical and horizontal\n# error bars can be displayed. The figure below illustrates the use of\n# error bars.\n#\n#
    \n# \"\"
    Error Bars
    \n#
    \n#\n# When error bars are desired, you typically replace the `plot` function\n# with the `errorbar` function. The first two arguments of the `errorbar`\n# function are the `x` and `y` arrays to be plotted, just as for the\n# `plot` function. The keyword `fmt` *must be used* to specify the format\n# of the points to be plotted; the format specifiers are the same as for\n# `plot`. The keywords `xerr` and `yerr` are used to specify the $x$ and\n# $y$ error bars. Setting one or both of them to a constant specifies one\n# size for all the error bars. Alternatively, setting one or both of them\n# equal to an array that has the same length as the `x` and `y` arrays\n# allows you to give each data point an error bar with a different value.\n# If you only want $y$ error bars, then you should only specify the `yerr`\n# keyword and omit the `xerr` keyword. The color of the error bars is set\n# with the keyword `ecolor`.\n#\n# The code and plot below illustrates how to make error bars and was used\n# to make the above plot. Lines 14 and 15 contain the call to the\n# `errorbar` function. The $x$ error bars are all set to a constant value\n# of 0.75, meaning that the error bars extend 0.75 to the left and 0.75 to\n# the right of each data point. The $y$ error bars are set equal to an\n# array, which was read in from the data file containing the data to be\n# plotted, so each data point has a different $y$ error bar. By the way,\n# leaving out the `xerr` keyword argument in the `errorbar` function call\n# below would mean that only the $y$ error bars would be plotted.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# # read data from file\n# xdata, ydata, yerror = np.loadtxt('expDecayData.txt', unpack=True)\n#\n# # create theoretical fitting curve\n# x = np.linspace(0, 45, 128)\n# y = 1.1+ 3.0*x*np.exp(-(x/10.0)**2)\n#\n# # create plot\n# plt.figure(1, figsize = (6,4) )\n# plt.plot(x, y, 'b-', label=\"theory\")\n# plt.errorbar(xdata, ydata, fmt='ro', label=\"data\", \n# xerr=0.75, yerr=yerror, ecolor='black')\n# plt.xlabel('x')\n# plt.ylabel('transverse displacement')\n# plt.legend(loc='upper right')\n#\n# # save plot to file\n# plt.savefig('ExpDecay.pdf')\n#\n# # display plot on screen\n# plt.show()\n# ```\n#\n# We have more to say about the `errorbar` function in the sections on\n# logarithmic plots. But the brief introduction given here should suffice\n# for making most plots not involving logarithmic axes.\n#\n# ### Setting plotting limits and excluding data\n#\n# It turns out that you often want to restrict the range of numerical\n# values over which you plot data or functions. In these cases you may\n# need to manually specify the plotting window or, alternatively, you may\n# wish to exclude data points that are outside some set of limits. Here we\n# demonstrate methods for doing this.\n#\n# #### Setting plotting limits\n#\n# single: plots; setting axis limits\n#\n# Suppose you want to plot the tangent function over the interval from 0\n# to 10. The following script offers an straightforward first attempt.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# theta = np.arange(0.01, 10., 0.04)\n# ytan = np.tan(theta)\n#\n# plt.figure()\n# plt.plot(theta, ytan)\n# plt.show()\n# ```\n#\n#
    \n# \"\"\n#
    \n#\n# The resulting plot, shown above, doesn't quite look like what you might\n# have expected for $\\tan\\theta$ *vs* $\\theta$. The problem is that\n# $\\tan\\theta$ diverges at $\\theta = \\pi/2, 3\\pi/2, 5\\pi/2, ...$, which\n# leads to large spikes in the plots as values in the `theta` array come\n# near those values. Of course, we don't want the plot to extend all the\n# way out to $\\pm\\infty$ in the $y$ direction, nor can it. Instead, we\n# would like the plot to extend far enough that we get the idea of what is\n# going on as $y\\rightarrow\\pm\\infty$, but we would still like to see the\n# behavior of the graph near $y=0$. We can restrict the range of `ytan`\n# values that are plotted using the MatPlotLib function `ylim`, as we\n# demonstrate in the script below.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# theta = np.arange(0.01, 10., 0.04)\n# ytan = np.tan(theta)\n#\n# plt.figure()\n# plt.plot(theta, ytan)\n# plt.ylim(-8, 8) # restricts range of y axis from -8 to +8\n# plt.axhline(color=\"gray\", zorder=-1)\n#\n# plt.show()\n# ```\n#\n# The figure produced by this script is shown below. The plot now looks\n# much more like the familiar $\\tan\\theta$ function we know. We have also\n# include a call to the `axline` function to create an $x$ axis.\n#\n#
    \n# \"\"
    Tangent function (with spurious lines)
    \n#
    \n#\n# The vertical blue lines at $\\theta = \\pi/2, 3\\pi/2, 5\\pi/2$ should not\n# appear in a plot of $\\tan\\theta$ *vs* $\\theta$. However, they do appear\n# because the `plot` function simply draws lines between the data points\n# in the `x`-`y` arrays provided in its arguments. Thus, `plot` draws a\n# line between the very large positive and negative `ytan` values\n# corresponding to the `theta` values on either side of $\\pi/2$ where\n# $\\tan\\theta$ diverges to $\\pm\\infty$. It would be nice to exclude that\n# line.\n#\n# #### Masked arrays\n#\n# single: plots; masked arrays single: masked arrays\n#\n# We can exclude the data points near $\\theta = \\pi/2, 3\\pi/2, 5\\pi/2$ in\n# the above plot, and thus avoid drawing the nearly vertical lines at\n# those points, using NumPy's *masked array* feature. The code below shows\n# how this is done and produces the graph below. The masked array feature\n# is implemented in line 6 with a call to NumPy's `masked_where` function\n# in the sub-module `ma` (masked array). Therefore, it is called by\n# writing `np.ma.masked_where`. The `masked_where` function works as\n# follows. The first argument sets the condition for masking elements of\n# the array, which is specified by the second argument. In this case, the\n# function says to mask all elements of the array `ytan` (the second\n# argument) where the absolute value of `ytan` is greater than 20. The\n# result is set equal to `ytanM`. When `ytanM` is plotted, MatPlotLib's\n# `plot` function omits all masked points from the plot. You can think of\n# it as the `plot` function lifting the pen that is drawing the line in\n# the plot when it comes to the masked points in the array `ytanM`.\n#\n#
    \n# \"\"
    Tangent function
    \n#
    \n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# theta = np.arange(0.01, 10., 0.04)\n# ytan = np.tan(theta)\n# ytanM = np.ma.masked_where(np.abs(ytan)>20., ytan)\n#\n# plt.figure()\n# plt.plot(theta, ytanM)\n# plt.ylim(-8, 8)\n# plt.axhline(color=\"gray\", zorder=-1)\n#\n# plt.show()\n# ```\n#\n# ### Subplots\n#\n# single: plots; subplots\n#\n# Often you want to create two or more graphs and place them next to one\n# another, generally because they are related to each other in some way.\n# The plot below shows an example of such a plot. In the top graph,\n# $\\tan\\theta$ and $\\sqrt{(8/\\theta)^2-1}$ *vs* $\\theta$ are plotted. The\n# two curves cross each other at the points where\n# $\\tan\\theta=\\sqrt{(8/\\theta)^2-1}$. In the bottom $\\cot\\theta$ and\n# $-\\sqrt{(8/\\theta)^2-1}$ *vs* $\\theta$ are plotted. These two curves\n# cross each other at the points where\n# $\\cot\\theta=-\\sqrt{(8/\\theta)^2-1}$.\n#\n#
    \n# \"\"
    Crossing functions
    \n#
    \n#\n# The code that produces this plot is provided below.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# theta = np.arange(0.01, 8., 0.04)\n# y = np.sqrt((8./theta)**2-1.)\n# ytan = np.tan(theta)\n# ytan = np.ma.masked_where(np.abs(ytan)>20., ytan)\n# ycot = 1./np.tan(theta)\n# ycot = np.ma.masked_where(np.abs(ycot)>20., ycot)\n#\n# plt.figure(1)\n#\n# plt.subplot(2, 1, 1)\n# plt.plot(theta, y)\n# plt.plot(theta, ytan)\n# plt.ylim(-8, 8)\n# plt.axhline(color=\"gray\", zorder=-1)\n# plt.axvline(x=np.pi/2., color=\"gray\", linestyle='--', zorder=-1)\n# plt.axvline(x=3.*np.pi/2., color=\"gray\", linestyle='--', zorder=-1)\n# plt.axvline(x=5.*np.pi/2., color=\"gray\", linestyle='--', zorder=-1)\n# plt.xlabel(\"theta\")\n# plt.ylabel(\"tan(theta)\")\n#\n# plt.subplot(2, 1, 2)\n# plt.plot(theta, -y)\n# plt.plot(theta, ycot)\n# plt.ylim(-8, 8)\n# plt.axhline(color=\"gray\", zorder=-1)\n# plt.axvline(x=np.pi, color=\"gray\", linestyle='--', zorder=-1)\n# plt.axvline(x=2.*np.pi, color=\"gray\", linestyle='--', zorder=-1)\n# plt.xlabel(\"theta\")\n# plt.ylabel(\"cot(theta)\")\n#\n# plt.show()\n# ```\n#\n# The function `subplot`, called on lines 13 and 24, creates the two\n# subplots in the above figure. `subplot` has three arguments. The first\n# specifies the number of rows that the figure space is to be divided\n# into; on line 13, it's two. The second specifies the number of columns\n# that the figure space is to be divided into; on line 13, it's one. The\n# third argument specifies which rectangle the will contain the plot\n# specified by the following function calls. Line 13 specifies that the\n# plotting commands that follow will be act on the first box. Line 24\n# specifies that the plotting commands that follow will be act on the\n# second box.\n#\n# We have also labeled the axes and included dashed vertical lines at the\n# values of $\\theta$ where $\\tan\\theta$ and $\\cot\\theta$ diverge.\n#\n# Logarithmic plots\n# -----------------\n#\n# single: plots; logarithmic axes\n#\n# Data sets can span many orders of magnitude from fractional quantities\n# much smaller than unity to values much larger than unity. In such cases\n# it is often useful to plot the data on logarithmic axes.\n#\n# ### Semi-log plots\n#\n# single: plots; semi-log\n#\n# For data sets that vary exponentially in the independent variable, it is\n# often useful to use one or more logarithmic axes. Radioactive decay of\n# unstable nuclei, for example, exhibits an exponential decrease in the\n# number of particles emitted from the nuclei as a function of time. In\n# the plot below, for example, we show the decay of the radioactive\n# isotope Phosphorus-32 over a period of 6 months, where the radioactivity\n# is measured once each week. Starting at a decay rate of nearly $10^4$\n# electrons (counts) per second, the decay rate diminishes to only about 1\n# count per second after about 6 months or 180 days. If we plot counts per\n# second as a function of time on a normal plot, as we have done in the\n# plot on the left below, then the count rate is indistinguishable from\n# zero after about 100 days. On the other hand, if we use a logarithmic\n# axis for the count rate, as we have done in the plot on the right below,\n# then we can follow the count rate well past 100 days and can readily\n# distinguish it from zero. Moreover, if the data vary exponentially in\n# time, then the data will fall along a straight line, as they do for the\n# case of radioactive decay.\n#\n#
    \n# \"\"
    Semi-log plotting
    \n#
    \n#\n# MatPlotLib provides two functions for making semi-logarithmic plots,\n# `semilogx` and `semilogy`, for creating plots with logarithmic $x$ and\n# $y$ axes, with linear $y$ and $x$ axes, respectively. We illustrate\n# their use in the program below, which made the above plots.\n#\n# ``` python\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# # read data from file\n# time, counts, unc = np.loadtxt('SemilogDemo.txt', unpack=True)\n#\n# # create theoretical fitting curve\n# tau = 20.2 # Phosphorus-32 half life = 14 days; tau = t_half/ln(2)\n# N0 = 8200. # Initial count rate (per second)\n# t = np.linspace(0, 180, 128)\n# N = N0 * np.exp(-t/tau)\n#\n# # create plot\n# plt.figure(1, figsize = (10,4) )\n#\n# plt.subplot(1, 2, 1)\n# plt.plot(t, N, 'b-', label=\"theory\")\n# plt.plot(time, counts, 'ro', label=\"data\")\n# plt.xlabel('time (days)')\n# plt.ylabel('counts per second')\n# plt.legend(loc='upper right')\n#\n# plt.subplot(1, 2, 2)\n# plt.semilogy(t, N, 'b-', label=\"theory\")\n# plt.semilogy(time, counts, 'ro', label=\"data\")\n# plt.xlabel('time (days)')\n# plt.ylabel('counts per second')\n# plt.legend(loc='upper right')\n#\n# plt.tight_layout()\n#\n# # display plot on screen\n# plt.show()\n# ```\n#\n# The `semilogx` and `semilogy` functions work the same way as the `plot`\n# function. You just use one or the other depending on which axis you want\n# to be logarithmic.\n#\n# #### The `tight_layout()` function\n#\n# single: MatPlotLib functions; tight\\_layout\n#\n# You may have noticed the `tight_layout()` function, called without\n# arguments on line 30 of the program. This is a convenience function that\n# adjusts the sizes of the plots to make room for the axes labels. If it\n# is not called, the $y$-axis label of the right plot runs into the left\n# plot. The `tight_layout()` function can also be useful in graphics\n# windows with only one plot sometimes.\n#\n# ### Log-log plots\n#\n# single: plots; log-log\n#\n# MatPlotLib can also make log-log or double-logarithmic plots using the\n# function `loglog`. It is useful when both the $x$ and $y$ data span many\n# orders of magnitude. Data that are described by a power law $y=Ax^b$,\n# where $A$ and $b$ are constants, appear as straight lines when plotted\n# on a log-log plot. Again, the `loglog` function works just like the\n# `plot` function but with logarithmic axes.\n#\n# More advanced graphical output\n# ------------------------------\n#\n# The plotting methods introduced in the previous sections are perfectly\n# adequate for basic plotting and are therefore recommended for simple\n# graphical output. Here, we introduce an alternative syntax that\n# harnesses the full power of MatPlotLib. It gives the user more options\n# and greater control. Perhaps the most efficient way to learn this\n# alternative syntax is to look at an example. The figure below\n# illustrating `MultPlotDemo` is produced by the following code:\n#\n#
    \n# \"\"
    Mulitple plots in the same window
    \n#
    \n#\n# # Demonstrates the following:\n# # plotting logarithmic axes\n# # user-defined functions\n# # \"where\" function, NumPy array conditional\n#\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# # Define the sinc function, with output for x=0 defined\n# # as a special case to avoid division by zero. The code\n# # below defining the sinc function is developed and\n# # explained in Chapter 7, Section 1.\n# def s(x):\n# a = np.where(x==0., 1., np.sin(x)/x)\n# return a\n#\n# # create arrays for plotting\n# x = np.arange(0., 10., 0.1)\n# y = np.exp(x)\n#\n# t = np.linspace(-10., 10., 100)\n# z = s(t)\n#\n# # create a figure window\n# fig = plt.figure(1, figsize=(9,8))\n#\n# # subplot: linear plot of exponential\n# ax1 = fig.add_subplot(2,2,1)\n# ax1.plot(x, y)\n# ax1.set_xlabel('time (ms)')\n# ax1.set_ylabel('distance (mm)')\n# ax1.set_title('exponential')\n#\n# # subplot: semi-log plot of exponential\n# ax2 = fig.add_subplot(2,2,2)\n# ax2.plot(x, y)\n# ax2.set_yscale('log')\n# ax2.set_xlabel('time (ms)')\n# ax2.set_ylabel('distance (mm)')\n# ax2.set_title('exponential')\n#\n# # subplot: wide subplot of sinc function\n# ax3 = fig.add_subplot(2,1,2)\n# ax3.plot(t, z, 'r')\n# ax3.axhline(color='gray')\n# ax3.axvline(color='gray')\n# ax3.set_xlabel('angle (deg)')\n# ax3.set_ylabel('electric field')\n# ax3.set_title('sinc function')\n#\n# # Adjusts white space to avoid collisions between subplots\n# fig.tight_layout()\n# plt.show()\n#\n# After defining several arrays for plotting, the above program opens a\n# figure window in line 23 with the statement :\n#\n# fig = plt.figure(figsize=(9,8))\n#\n# The MatPlotLib statement above creates a **Figure** object, assigns it\n# the name `fig`, and opens a blank figure window. Thus, just as we give\n# lists, arrays, and numbers variable names (*e.g.* `a = [1, 2, 5, 7]`,\n# `dd = np.array([2.3, 5.1, 3.9])`, or `st = 4.3`), we can give a figure\n# object and the window in creates a name: here it is `fig`. In fact we\n# can use the `figure` function to open up multiple figure objects with\n# different figure windows. The statements :\n#\n# fig1 = plt.figure()\n# fig2 = plt.figure()\n#\n# open up two separate windows, one named `fig1` and the other `fig2`. We\n# can then use the names `fig1` and `fig2` to plot things in either\n# window. The `figure` function need not take any arguments if you are\n# satisfied with the default settings such as the figure size and the\n# background color. On the other hane, by supplying one or more keyword\n# arguments, you can customize the figure size, the background color, and\n# a few other properties. For example, in the program listing (line 23),\n# the keyword argument `figsize` sets the width and height of the figure\n# window; the default size is `(8, 6)`; in our program we set it to\n# `(9, 8)`, which is a bit wider and higher than the default size. In the\n# example above, we also choose to open only a single window, hence the\n# single `figure` call.\n#\n# The `fig.add_subplot(2,2,1)` in line 30 is a MatPlotLib function that\n# divides the figure window into 2 rows (the first argument) and 2 columns\n# (the second argument). The third argument creates a subplot in the first\n# of the 4 subregions (*i.e.* of the 2 rows $\\times$ 2 columns) created by\n# the `fig.add_subplot(2,2,1)` call. To see how this works, type the\n# following code into a Python module and run it:\n#\n# import numpy as np\n# import matplotlib.pyplot as plt\n#\n# fig = plt.figure(figsize=(9,8))\n# ax1 = fig.add_subplot(2,2,1)\n#\n# plt.show()\n#\n# You should get a figure window with axes drawn in the upper left\n# quadrant. The `fig.` prefix used with the `add_subplot(2,2,1)` function\n# directs Python to draw these axes in the figure window named `fig`. If\n# we had opened two figure windows, changing the prefix to correspond to\n# the name of one or the other of the figure windows would direct the axes\n# to be drawn in the appropriate window. Writing\n# `ax1 = fig.add_subplot(2,2,1)` assigns the name ax1 to the axes in the\n# upper left quadrant of the figure window.\n#\n# The `ax1.plot(x, y)` in line 27 directs Python to plot the\n# previously-defined `x` and `y` arrays onto the axes named `ax1`. The\n# `ax2 = fig.add_subplot(2,2,2)` draws axes in the second, or upper right,\n# quadrant of the figure window. The `ax3 = fig.add_subplot(2,1,2)`\n# divides the figure window into 2 rows (first argument) and 1 column\n# (second argument), creates axes in the second or these two sections, and\n# assigns those axes (*i.e.* that subplot) the name `ax3`. That is, it\n# divides the figure window into 2 halves, top and bottom, and then draws\n# axes in the half number 2 (the third argument), or lower half of the\n# figure window.\n#\n# You may have noticed in above code that some of the function calls are a\n# bit different from those used before: `xlabel(’time (ms)’)` becomes\n# `set_xlabel(’time (ms)’)`, `title(’exponential’)` becomes\n# `set_title(’exponential’)`, *etc.*\n#\n# The call `ax2.set_yscale('log')` sets the $y$-axes in the second plot to\n# be logarithmic, thus creating a semi-log plot. Creating properly-labeled\n# logarthmic axes like this is more straightforward with the advanced\n# syntax illustrated in the above example.\n#\n# Using the prefixes `ax1`, `ax2`, or `ax3`, direct graphical instructions\n# to their respective subplots. By creating and specifying names for the\n# different figure windows and subplots within them, you access the\n# different plot windows more efficiently. For example, the following code\n# makes four identical subplots in a single figure window using a `for`\n# loop.\n#\n# ``` ipython\n# In [1]: fig = figure()\n#\n# In [2]: ax1 = fig.add_subplot(221)\n#\n# In [3]: ax2 = fig.add_subplot(222)\n#\n# In [4]: ax3 = fig.add_subplot(223)\n#\n# In [5]: ax4 = fig.add_subplot(224)\n#\n# In [6]: for ax in [ax1, ax2, ax3, ax4]:\n# ...: ax.plot([3,5,8],[6,3,1])\n#\n# In [7]: show()\n# ```\n#\n# Exercises\n# ---------\n#\n# 1. Plot the function $y=3x^2$ for $-1 \\le x \\le 3$ as a continuous\n# line. Include enough points so that the curve you plot appears\n# smooth. Label the axes $x$ and $y$.\n#\n# 2. Plot the following function for $-15 \\le x \\le 15$:\n#\n# $$y = \\frac{\\cos x}{1+\\frac{1}{5}x^2}$$\n#\n# Include enough points so that the curve you plot appears smooth.\n# Label the axes $x$ and $y$.\n#\n# 3. Plot the functions $\\sin x$ and $\\cos x$ *vs* $x$ on the same plot\n# with $x$ going from $-\\pi$ to $\\pi$. Make sure the limits of\n# $x$-axis do not extend beyond the limits of the data. Plot $\\sin x$\n# in the color green and $\\cos x$ in the color black and include a\n# legend to label the two curves. Place the legend within the plot,\n# but such that it does not cover either of the sine or cosine traces.\n#\n# 4. Create a data file with the data shown below.\n#\n# 1. Read the data into Python program and plot $t$ *vs* $y$ using\n# circles for data points with error bars. Use the data in the\n# `dy` column as the error estimates for the $y$ data. Label the\n# horizontal and vertical axes \"time (s)\" and \"position (cm)\".\n#\n# 2. On the same graph, plot the function below as a smooth line.\n# Make the line pass *behind* the data points.\n#\n# $$y(t) = \\left[3 + \n# \\frac{1}{2}\\sin\\frac{\\pi t}{5}\\right]\n# t\\, e^{-t/10}$$\n#\n# Data for Exercise 4\n# Date: 16-Aug-2013\n# Data taken by Lauren and John\n#\n# t d dy\n# 1.0 2.94 0.7\n# 4.5 8.29 1.2\n# 8.0 9.36 1.2\n# 11.5 11.60 1.4\n# 15.0 9.32 1.3\n# 18.5 7.75 1.1\n# 22.0 8.06 1.2\n# 25.5 5.60 1.0\n# 29.0 4.50 0.8\n# 32.5 4.01 0.8\n# 36.0 2.62 0.7\n# 39.5 1.70 0.6\n# 43.0 2.03 0.6\n#\n# 5. Use MatPlotLib's function `hist` along with NumPy's function's\n# `random.rand` and `random.randn` to create the histogram graphs\n# shown in Fig. `fig-randhistos`\n#\n# 6. Plot force *vs* distance with error bars using the following data:\n#\n# d=np.array([0.38, 0.64, 0.91, 1.26, 1.41, 1.66, 1.90, 2.18])\n# f=np.array([1.4, 1.65, 3.0, 3.95, 4.3, 5.20, 6.85, 7.4])\n# df=np.array([ 0.4, 0.5, 0.4, 0.5, 0.6, 0.5, 0.5, 0.4])\n#\n# Your plot should also include a visual straight \"best fit\" to the\n# data as well as visual \"fits\" that give the smallest and largest\n# slopes consistent with the data. Note, you only need two points to\n# define a straight line so the straight lines you draw on the plot\n# should be arrays of length 2 and no longer. All of your fitted lines\n# should lie *behind* the data. Try to make your plot look like the\n# one below. *In addition*, add a legend to your plot the gives the\n# slope with its uncertainty obtained from your visual fits to the\n# data.\n#\n#
    \n# \"\"\n#
    \n#\n# The web page gives a\n# summary of the main plotting commands available in MatPlotLib. The\n# two important ones here are `plot` and `errorbar`, which make\n# regular plots and plots with error bars, respectively. You will find\n# the following keyword arguments useful: `yerr`, `ls`, `marker`,\n# `mfc`, `mec`, `ms`, and `ecolor`, which you can find described by\n# clicking on the `errorbar` function link on the web page cited\n# above.\n#\n# 7. The data file below shows data obtained for the displacement\n# (position) *vs* time of a falling object, together with the\n# estimated uncertainty in the displacement.\n#\n# > Measurements of fall velocity vs time\n# > Taken by A.P. Crawford and S.M. Torres\n# > 19-Sep-13 \n# > time (s) position (m) uncertainty (m)\n# > 0.0 0.0 0.04\n# > 0.5 1.3 0.12\n# > 1.0 5.1 0.2\n# > 1.5 10.9 0.3\n# > 2.0 18.9 0.4\n# > 2.5 28.7 0.4\n# > 3.0 40.3 0.5\n# > 3.5 53.1 0.6\n# > 4.0 67.5 0.6\n# > 4.5 82.3 0.6\n# > 5.0 97.6 0.7\n# > 5.5 113.8 0.7\n# > 6.0 131.2 0.7\n# > 6.5 148.5 0.7\n# > 7.0 166.2 0.7\n# > 7.5 184.2 0.7\n# > 8.0 201.6 0.7\n# > 8.5 220.1 0.7\n# > 9.0 238.3 0.7\n# > 9.5 256.5 0.7\n# > 10.0 275.6 0.8\n#\n# 1. Use these data to calculate the velocity and acceleration (in a\n# Python program `.py` file), together with their uncertainties\n# propagated from the displacement *vs* time uncertainties. Be\n# sure to calculate time arrays corresponding the midpoint in time\n# between the two displacements or velocities for the velocity and\n# acceleration arrays, respectively.\n# 2. In a single window frame, make three vertically stacked plots of\n# the displacement, velocity, and acceleration *vs* time. Show the\n# error bars on the different plots. Make sure that the time axes\n# of all three plots cover the same range of times. Why do the\n# relative sizes of the error bars grow progressively greater as\n# one progresses from displacement to velocity to acceleration?\n\n# %%\n", "meta": {"hexsha": "9f9b2a58a223d80a28291c92734a77766b0fde38", "size": 46092, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/chap5_plot.py", "max_stars_repo_name": "lorenghoh/pyman", "max_stars_repo_head_hexsha": "9b4ddd52c5577fc85e2601ae3128f398f0eb673c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/chap5_plot.py", "max_issues_repo_name": "lorenghoh/pyman", "max_issues_repo_head_hexsha": "9b4ddd52c5577fc85e2601ae3128f398f0eb673c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/chap5_plot.py", "max_forks_repo_name": "lorenghoh/pyman", "max_forks_repo_head_hexsha": "9b4ddd52c5577fc85e2601ae3128f398f0eb673c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5300171527, "max_line_length": 144, "alphanum_fraction": 0.6684240215, "include": true, "reason": "import numpy", "num_tokens": 13251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879064146934857, "lm_q2_score": 0.17328820806405806, "lm_q1q2_score": 0.08123589021742372}} {"text": "# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.13.3\n# kernelspec:\n# display_name: tcv-x21\n# language: python\n# name: tcv-x21\n# ---\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# # Post-processing a GRILLIX simulation\n#\n# This notebook demonstrates how to perform the post-processing analysis for\n# a GRILLIX simulation, contained in the `sample_data` folder.\n#\n# To limit the repository size, only 5 snapshot write-outs are provided. The sample data is provided primarily to demonstrate the\n# method by which you can generate a standard NetCDF file for another simulation,\n# to perform an equivalent validation.\n#\n# Analysis routines are provided in the `tcvx21/grillix_post` folder.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nimport tcvx21\n\n# %reload_ext autoreload\n# %autoreload 2\n# %matplotlib inline\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xarray as xr\nfrom pathlib import Path\nfrom tcvx21.units_m import Quantity, Dimensionless, convert_xarray_to_quantity\nfrom tcvx21.file_io.json_io_m import read_from_json\n\nimport tcvx21.grillix_post as grillix\nfrom tcvx21 import test_session\n\nplt.style.use(tcvx21.style_sheet)\n\nplt.rcParams.update({\"mathtext.default\": \"regular\"})\nplt.rcParams[\"figure.facecolor\"] = \"white\"\nxr.set_options(keep_attrs=True)\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfile_path = tcvx21.sample_data\ntime_slice = slice(None)\n\nfile_path = Path(file_path)\nassert file_path.exists()\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Setting up an interface to the data\n#\n# We start by reading in the basic simulation data. For GRILLIX, this is\n#\n# 1. Grid: the $R,Z$ grid used for the simulation (assumed to be axisymmetric).\n# Since we trim our grid at a limiting flux-surface, the data is stored as unstructured\n# $(R, Z, value)$ column data. The grid allows us to map this to a matrix form $value(R, Z)$, which is needed\n# for plotting and analysis.\n# 2. Normalisation: a set of `pint.Quantity` values which allows us to go from\n# normalised values to SI values. The `pint.Quantity` class is highly capable,\n# allowing unit tracking through basic operations, and unit conversion.\n# 3. `xr.Dataset` snaps: an interface to the GRILLIX snapshot data. The xarray\n# module interfaces with dask to provide a memory-light interface to very\n# large files. It is similar to a `pandas.DataFrame`.\n# 4. Equi: an interface to the equilibrium file, providing data about the magnetic\n# field and penalisation (which is how GRILLIX sets boundary conditions). The\n# `flip_z` parameter is used to invert the toroidal field direction.\n#\n# To limit the size of the tcvx21 repository, we provide only sample data over a few snapshots\n# of a low-resolution (2mm) case.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\ngrid = grillix.components.Grid(file_path / \"vgrid.nc\")\nnorm = grillix.components.Normalisation.initialise_from_normalisation_file(\n file_path / \"physical_parameters.nml\"\n)\nsnaps = grillix.components.read_snaps_from_file(\n file_path, norm, time_slice=slice(None), all_planes=True\n)\nequi = grillix.components.Equi(\n file_path / \"TCV_ortho.nc\", file_path / \"pen_metainfo.nc\", flip_z=True\n)\n\nparameter_filepath = grillix.filepath_resolver(file_path, \"params.in\")\nparams = grillix.components.convert_params_filepaths(\n parameter_filepath, grillix.components.read_fortran_namelist(parameter_filepath)\n)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Data extraction via \"lineouts\"\n#\n# Now that we have the interface prepared, we want to extract values at the\n# set of experimental observable positions. We do this via \"lineouts\", which\n# provide an efficient way to get points at specific $R,Z$ positions.\n#\n# We also need to be able to map from a flux-surface label to the\n# $R^u - R^u_{sep}$ coordinate. We do this via the OutboardMidplaneMap.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nn_points = 500\nomp_map = grillix.lineouts.OutboardMidplaneMap(grid, equi, norm)\nomp = grillix.lineouts.outboard_midplane_chord(grid, equi, n_points=500)\nlfs = grillix.lineouts.penalisation_contour(\n grid, equi, level=0.0, contour_index=0, n_points=n_points\n)\nhfs = grillix.lineouts.penalisation_contour(\n grid, equi, level=0.0, contour_index=1, n_points=n_points\n)\nts = grillix.lineouts.thomson_scattering(\n grid, equi, tcvx21.thomson_coords_json, n_points=n_points\n)\nrdpa = grillix.lineouts.rdpa(grid, equi, omp_map, norm, tcvx21.rdpa_coords_json)\nxpt = grillix.lineouts.xpoint(grid, equi, norm)\n\nlineouts = {\"omp\": omp, \"lfs\": lfs, \"hfs\": hfs, \"ts\": ts, \"rdpa\": rdpa, \"xpt\": xpt}\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# We also want to be able to calculate parallel gradients. In GRILLIX, this\n# is done via the FCI method. A simplified trace-and-interpolate method\n# is demonstrated here. Note that since we're interpolating in Python,\n# this is very slow!\n#\n# To speed things up a little, we trace only once per lineout, and only\n# for the lineouts where we need parallel gradients.\n#\n# (Unfortunately, dask-based parallelism raises a strange `CancelledError` when\n# these loops are attempted to be parallelized)\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\n# %%time\ngrillix.observables.initialise_lineout_for_parallel_gradient(\n lfs,\n grid,\n equi,\n norm,\n params[\"params_grid\"][\"npol\"],\n stored_trace=file_path / f\"lfs_trace_{n_points}.nc\",\n)\n# We don't compute the heat flux for the HFS, so can save time by not tracing for it\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# As a sanity check, it's always a good idea to plot things before we perform the\n# analysis.\n#\n# The lfs and hfs lineouts in GRILLIX are defined at positions which don't exactly\n# correspond to the physical wall. This is because GRILLIX uses a smooth\n# penalisation characteristic function. The lfs and hfs positions are defined as\n# the surface where we *start* to apply boundary conditions. For more details\n# on this method, see Stegmeir et al., 2019.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\ndivertor_ = read_from_json(tcvx21.divertor_coords_json)\n\n_, ax = plt.subplots(figsize=(10, 10))\nplt.contour(grid.r_s, grid.z_s, equi.normalised_flux_surface_label(grid.r_s, grid.z_s))\n\nplt.scatter(\n lineouts[\"xpt\"].r_points,\n lineouts[\"xpt\"].z_points,\n s=1,\n marker=\".\",\n color=\"r\",\n label=\"xpt\",\n)\nplt.scatter(\n lineouts[\"rdpa\"].r_points,\n lineouts[\"rdpa\"].z_points,\n s=1,\n marker=\"+\",\n color=\"k\",\n label=\"rdpa\",\n)\n\nfor key, lineout in lineouts.items():\n\n if key in [\"rdpa\", \"xpt\"]:\n continue\n\n plt.plot(lineout.r_points, lineout.z_points, label=key, linewidth=2.5)\n\n if hasattr(lineout, \"forward_lineout\"):\n plt.plot(\n lineout.forward_lineout.r_points,\n lineout.forward_lineout.z_points,\n label=f\"{key}+\",\n linewidth=2.5,\n )\n if hasattr(lineout, \"reverse_lineout\"):\n plt.plot(\n lineout.reverse_lineout.r_points,\n lineout.reverse_lineout.z_points,\n label=f\"{key}-\",\n linewidth=2.5,\n )\n\nplt.legend()\nif equi.flipped_z:\n ax.invert_yaxis()\nax.set_aspect(\"equal\")\n\nplt.plot(\n divertor_[\"r_points\"] / equi.axis_r.values,\n divertor_[\"z_points\"] / equi.axis_r.values * -1.0 if equi.flipped_z else 1.0,\n color=\"k\",\n)\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Interfacing with the snaps\n#\n# The `snaps` object (an `xarray` labelled multi-dimensional array) provides\n# convenient access to the simulation data. We mostly focus on 1D lineouts\n# which can be compared to the experimental diagnostics, but we demonstrate\n# here the use of the analysis components to show the density perturbation.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfig, ax = plt.subplots()\ngrid.shape(\n snaps.density.isel(tau=0, phi=0) - snaps.density.mean(dim=(\"tau\", \"phi\"))\n).plot(shading=\"flat\")\n\nax.invert_yaxis()\nax.set_aspect(\"equal\")\nax.set_title(\"Density perturbation\")\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Demonstrating the lineout functionality\n#\n# Looks good! Next, let's test the lineout functionality. If you just want\n# normalised units, it's very easy using the xarray functionality.\n#\n# This one-liner has a lot going on, so let's unpack it\n# 1. `lineouts[omp]` requests the stored omp `Lineout`\n# 2. `.interpolate(` calls the interpolate method\n# 3. `snaps.density` requests the density stored in the snaps\n# 4. `).mean(dim='phi')` toroidally averages the result (since snaps.density has\n# `phi, tau, points` dimensions, the lineout will have `phi, tau, interp_points`\n# dimensions. We want to plot 2D, so average over `phi` to eliminate this dimension).\n# 5. `.plot()` is a thin wrapper of `matplotlib.pyplot.pcolormesh`, which automatically\n# sets the x and y values of the plot from the xarray coordinates\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nlineouts[\"omp\"].interpolate(snaps.density).mean(dim=\"tau\").plot.contourf()\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# What about if we want this in SI units? Unfortunately, xarray isn't completely\n# compatible with `pint`, so we have to manually convert to `pint.Quantity` objects\n# and then set up the plotting manually.\n#\n# N.b. the underscore in the variable names is simply to indicate that these variables\n# are private -- i.e. they shouldn't be used in other routines (since Python\n# automatically promotes variables outside of functions to global scope. This\n# is something to be careful about in Jupyter notebooks).\n#\n# You can see that the result doesn't vary much with time,\n# but that's not surprising since 5 snaps is only 8 microseconds\n# of plasma time!\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\ntau_ = convert_xarray_to_quantity(snaps.tau).to(\"microseconds\")\ntau_ -= tau_[0]\n\nlineout_ = lineouts[\"omp\"]\nlineout_rho_ = equi.normalised_flux_surface_label(\n lineout_.r_points, lineout_.z_points, grid=False\n)\nlineout_ru_ = convert_xarray_to_quantity(\n omp_map.convert_rho_to_distance(lineout_rho_)\n).to(\"cm\")\n\nlineout_density_ = convert_xarray_to_quantity(\n lineout_.interpolate(snaps.density).mean(dim=\"phi\")\n).to(\"1/m^3\")\n\nfig, ax = plt.subplots()\n\nim = ax.contourf(lineout_ru_, tau_, lineout_density_, shading=\"nearest\")\nplt.colorbar(im, ax=ax)\n\nax.set_ylabel(\"$\\\\tau$ [$\\\\mu$ s]\")\nax.set_xlabel(\"$R^u - R^u_{sep}$ [cm]\")\nax.set_title(\"OMP density [$1/m^3$]\")\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Synthetic diagnostics and bootstrap\n#\n# For observables which do not directly map to the simulation dynamic quantities,\n# we need a method to estimate what the measured value will be given plasma\n# parameters from the simulation. These can be roughly termed *synthetic\n# diagnostics*, although we use here only simple approximations. The functions\n# are stored in the `experimental_quantities_m.py` file.\n#\n# We show here how to calculate the skewness of the ion saturation current measured the low-field-side\n# target Langmuir probe array.\n#\n# This method also gives an estimate of the uncertainty of the statistical moment via the\n# bootstrap method. The bootstrap method takes several random samples of the signal (potentially\n# double-counting some points and omitting others) and then calculates the mean\n# and standard deviation of the statistical moments calculated from the random samples.\n# Strictly speaking it should be applied for purely random data, rather than correlated\n# data, but we use it nevertheless because it is a nice and simple approximation of the\n# finite-sampling error.\n#\n# For the mean, the bootstrap error is tiny, but for the higher-order statistical moments it\n# can be appreciable.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nlineout_ = lineouts[\"lfs\"]\nlineout_rho_ = equi.normalised_flux_surface_label(\n lineout_.r_points, lineout_.z_points, grid=False\n)\nlineout_ru_ = convert_xarray_to_quantity(\n omp_map.convert_rho_to_distance(lineout_rho_)\n).to(\"cm\")\n\nsound_speed_ = grillix.observables.sound_speed(\n electron_temp=snaps.electron_temp, ion_temp=snaps.ion_temp, norm=norm\n)\n\njsat_ = grillix.observables.ion_saturation_current(\n density=snaps.density, sound_speed=sound_speed_, norm=norm, wall_probe=True\n)\n\njsat_skew_, jsat_skew_err_ = tcvx21.analysis.compute_statistical_moment_with_bootstrap(\n lineout_.interpolate(jsat_).rename({\"interp_points\": \"points\"}), moment=\"skew\"\n)\n\njsat_skew_ = convert_xarray_to_quantity(jsat_skew_)\njsat_skew_err_ = convert_xarray_to_quantity(jsat_skew_err_)\n\nfig, ax = plt.subplots()\n\nax.plot(lineout_ru_, jsat_skew_)\nax.fill_between(\n lineout_ru_, jsat_skew_ + jsat_skew_err_, jsat_skew_ - jsat_skew_err_, alpha=0.5\n)\n\nax.set_xlabel(\"$R^u - R^u_{sep}$ [cm]\")\nax.set_title(\"LFS ion saturation current skewness\")\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Heat flux profile fitting\n#\n# A more involved synthetic diagnostic is the parallel heat flux to the\n# boundaries. From our anomalous heat transmission boundary conditions, we can\n# determine the heat flux to the boundaries as\n#\n# $q_{\\parallel,e} = \\frac{5}{2}n v_{\\parallel,e}T_e + \\frac{5}{2}n u_{E\\times B}T_e - \\chi_{\\parallel e,0} T_e^{5/2}\\nabla_\\parallel T_e$\n#\n# $q_{\\parallel,i} = \\frac{5}{2}n u_{\\parallel,i}T_i + \\frac{5}{2}n u_{E\\times B}T_i - \\chi_{\\parallel i,0} T_i^{5/2}\\nabla_\\parallel T_i$\n#\n# We can check the heat flux routines and the contribution from each component here.\n# Note that, unless the $E \\times B$ contribution is included, the heat flux\n# can become negative.\n#\n# You notice that there's a lot of terms in this equation.\n# $q_\\parallel$ isn't directly evolved in the code, so it has\n# a lower simulation hierarchy than other simpler observables.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nlineout_ = lineouts[\"lfs\"]\nlineout_rho_ = equi.normalised_flux_surface_label(\n lineout_.r_points, lineout_.z_points, grid=False\n)\nlineout_ru_ = convert_xarray_to_quantity(\n omp_map.convert_rho_to_distance(lineout_rho_)\n).to(\"cm\")\n\ndensity = lineout_.interpolate(snaps.density)\nion_velocity = lineout_.interpolate(snaps.velocity)\ncurrent = lineout_.interpolate(snaps.current)\nelectron_temp = lineout_.interpolate(snaps.electron_temp)\nelectron_temp_parallel_gradient = grillix.observables.compute_gradient_on_plane(\n lineout_, snaps.electron_temp, plane=0\n)\nion_temp = lineout_.interpolate(snaps.ion_temp)\nion_temp_parallel_gradient = grillix.observables.compute_gradient_on_plane(\n lineout_, snaps.ion_temp, plane=0\n)\neffective_parallel_exb = lineout_.interpolate(\n grillix.observables.effective_parallel_exb_velocity(\n grid, equi, norm, snaps.potential\n )\n)\n\nq_e_conv = grillix.observables.heat_flux.electron_parallel_heat_convection(\n density, electron_temp, ion_velocity, current, norm\n).isel(tau=0, phi=0)\nq_i_conv = grillix.observables.heat_flux.ion_parallel_heat_convection(\n density, ion_temp, ion_velocity, norm\n).isel(tau=0, phi=0)\nq_e_cond = grillix.observables.heat_flux.electron_parallel_heat_conduction(\n electron_temp, electron_temp_parallel_gradient, norm\n).isel(tau=0, phi=0)\nq_i_cond = grillix.observables.heat_flux.ion_parallel_heat_conduction(\n ion_temp, ion_temp_parallel_gradient, norm\n).isel(tau=0, phi=0)\nq_e_exb = grillix.observables.heat_flux.exb_effective_parallel_heat_convection(\n density, electron_temp, effective_parallel_exb, norm\n).isel(tau=0, phi=0)\nq_i_exb = grillix.observables.heat_flux.exb_effective_parallel_heat_convection(\n density, ion_temp, effective_parallel_exb, norm\n).isel(tau=0, phi=0)\n\nq_par = grillix.observables.total_parallel_heat_flux(\n density,\n electron_temp,\n electron_temp_parallel_gradient,\n ion_temp,\n ion_temp_parallel_gradient,\n ion_velocity,\n current,\n effective_parallel_exb,\n norm,\n).load()\n\nfig, ax = plt.subplots()\n\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_e_conv), label=\"q_e_conv\")\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_i_conv), label=\"q_i_conv\")\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_e_cond), label=\"q_e_cond\")\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_i_cond), label=\"q_i_cond\")\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_i_exb), label=\"q_i_exb\")\nax.plot(lineout_ru_, convert_xarray_to_quantity(q_e_exb), label=\"q_e_exb\")\n\nax.plot(\n lineout_ru_,\n convert_xarray_to_quantity(q_par.isel(tau=0, phi=0)),\n \"k--\",\n label=\"total\",\n)\n\nax.legend()\n\nfig, ax = plt.subplots()\n_, lambda_q, _, _, _ = tcvx21.analysis.fit_eich_profile(\n lineout_ru_, convert_xarray_to_quantity(q_par.mean(dim=(\"tau\", \"phi\"))), plot=True\n)\n\nprint(f\"lambda_q = {lambda_q[0]:4.3}±{lambda_q[1]:4.3}\")\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## 2D data from the divertor volume\n#\n# As well as 1D profiles, we also have 2D profiles from the reciprocating\n# divertor probe array. Since the plasma can move relative to the wall,\n# we use $R^u - R^u_{omp}$ and $Z$ instead of the original $R, Z$ coordinates.\n# This means that our sample grid is not rectangular. We need to sample our\n# data on the unstructured grid.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom scipy.interpolate import griddata\n\n\ndef plot_rdpa_field(rdpa_lineout, field, n_rsep=50, n_z=50):\n\n x = rdpa_lineout.coords[\"Rsep\"]\n y = rdpa_lineout.coords[\"Z\"]\n assert x.shape == y.shape\n z = rdpa_lineout.interpolate(field)\n\n x_sample = np.linspace(x.min(), x.max(), num=n_rsep)\n y_sample = np.linspace(y.min(), y.max(), num=n_z)\n x_mesh, y_mesh = np.meshgrid(x_sample, y_sample)\n\n z_sample = griddata(\n points=(x.magnitude, y.magnitude),\n values=z,\n xi=(x_mesh.magnitude, y_mesh.magnitude),\n )\n\n z_sample *= z.norm\n\n plt.pcolormesh(x_sample, y_sample, z_sample, shading=\"nearest\")\n plt.colorbar()\n plt.xlabel(\"$R^u - R^u_{sep}$\" + f\" [{x.units}]\")\n plt.ylabel(f\"Z [{y.units}]\")\n plt.title(f\"RDPA {z.name} [{z_sample.units}]\")\n\nplt.figure()\nplot_rdpa_field(lineouts[\"rdpa\"], snaps.electron_temp.mean(dim=(\"phi\", \"tau\")))\n\nif test_session:\n plt.close(\"all\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Integral values for sources\n#\n# As well as profiles, we are also interested in integrals of the sources, to determine whether\n# we are using a source in the region of the experimental values.\n#\n# The sources in GRILLIX are given in the file tcvx21/grillix_analysis/sources_m.py. In GRILLIX we have\n# set a 'constant-power, constant-particle' source. That is, we actively adapt our electron-temperature\n# source to compensate for the power due to the particle source. This way, we inject a constant\n# 150kW exactly. This is deposited in the core as a temperature source. However, since the density source\n# also contributes to the power source we compensate for this by adding a negative temperature source\n# at the edge.\n#\n# $P = \\frac{3}{2}\\int n S_{T_e} + (T_e + T_i) S_n \\textrm{d}^3V$\n#\n# We are using\n# $S_n = n_0 / \\tau_0 \\hat{S}_n$\n# where\n#\n# $\\hat{S}_n = \\hat{S}_{n0} f_{S,n}(R,Z) = \\hat{S}_{n0} \\exp\\left[-\\left(\\rho(R,Z)^2 - \\rho_{cn}^2 \\right)/\\rho_{wn}^2\\right]$\n#\n# for $\\rho_{cn} = 0.815$ and $\\rho_{wn} =0.083$, and\n#\n# $S_{Te} = T_{0} / \\tau_0 \\left(\\frac{1}{\\hat{n}}\\hat{S}_{Te} - \\frac{\\hat{T}_e + \\hat{T}_i}{\\hat{n}} \\hat{S}_n \\right)$\n#\n# where\n#\n# $\\hat{S}_{Te} = \\hat{S}_{Te0} f_{S,Te}(R,Z) = \\hat{S}_{Te0} \\left(1 - \\mathcal{S}_3(\\rho, \\rho_{cT}, \\rho_{wT})\\right)$\n#\n# for $\\mathcal{S}_3(x, c, w)$ is a third-order [smoothstep](https://en.wikipedia.org/wiki/Smoothstep) function\n# centred at $c$ and of transition width $w$.\n#\n# This allows us to write\n#\n# $P = \\frac{3}{2}\\iiint n_0 \\hat{n} T_{0} / \\tau_0 \\left(\\frac{1}{\\hat{n}}\\hat{S}_{Te} - \\frac{\\hat{T}_e + \\hat{T}_i}{\\hat{n}} \\hat{S}_n \\right) + T_0(\\hat{T}_e + \\hat{T}_i) n_0 / \\tau_0 \\hat{S}_n \\textrm{d}^3V$\n#\n# $P= \\frac{3}{2}\\frac{n_0 T_0}{\\tau_0} \\iiint \\hat{S}_{Te} - (\\hat{T}_e + \\hat{T}_i) \\hat{S}_n + (\\hat{T}_e + \\hat{T}_i) \\hat{S}_n \\textrm{d}^3V$\n#\n# $P= \\frac{3}{2}\\frac{n_0 T_0}{\\tau_0} \\hat{S}_{Te0} \\iiint f_{S,Te}(R,Z) \\textrm{d}^3V$\n#\n# $P= \\frac{3}{2}\\frac{n_0 T_0}{\\tau_0} \\hat{S}_{Te0} \\mathcal{V}_w$\n#\n# That is, our power injection is determined entirely by our core electron temperature source.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\ngrillix.components.integrated_sources(grid, equi, norm, params, snaps)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ## Iterating over all observables\n#\n# The final step to producing a standard NetCDF file for comparison is to iterate over each element\n# of the standard dictionary and fill the dictionary with results.\n# We then use the `RecordWriter`\n# to convert the standard dictionary into a NetCDF file.\n#\n# Since the raw data is very large (does not fit in memory), we do a two-step post-processing. In the first step, we iterate\n# over the time points in our raw data to compute the raw observables at the observable positions.\n# These are iteratively written to an intermediate processing file. In the second\n# step, we perform statistics over the processing file, calculating the data used for the validation\n# analysis.\n#\n# The first step is done with the `fill_work_file()` method of the `DataExtract` object.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.grillix_post.work_file_writer_m import WorkFileWriter\n\n(file_path / \"processing_file.nc\").unlink(missing_ok=True)\n\ndata = WorkFileWriter(\n file_path=file_path,\n work_file=file_path / \"processing_file.nc\",\n toroidal_field_direction=\"forward\",\n make_work_file=True,\n)\n\ndata.fill_work_file()\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# In the second step, we need to make a `Record`, which is a NetCDF file formatted according\n# to the data template in `observables.json`.\n#\n# The validation is done in terms of statistical moments, rather than raw values.\n#\n# To compute statistical values and the uncertainty associated with it, we use the bootstrap\n# method. We take samples from all toroidal planes, and 1ms of data (500 snaps).\n#\n# We select values from the samples available for each observable point *with replacement*. This means that some points may be double-counted,\n# and some may be missed entirely.\n#\n# We repeat this a number of times, to generate a number of *tests*.\n#\n# Finally, we compute the median of the tests and a confidence interval -- which gives us a\n# robust estimator for the statistical moment and its uncertainty.\n#\n# The 65% and 95% confidence intervals are shown for the different statistical moments of $J_{sat}$\n#\n# Note that since we only have 5 time points here, the uncertainty is\n# higher than for the real result with 500 time points.\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nimport xarray as xr\n\n\ndef Q(netcdf_array):\n \"\"\"Converts netcdf arrays to Quantities\"\"\"\n return Quantity(netcdf_array.values, netcdf_array.units)\n\n\ndef plot_region(x, y, dy, label):\n plt.plot(x, y, label=label)\n plt.fill_between(x, y - dy, y + dy, alpha=0.2)\n\n\nwork_file_path = file_path / \"processing_file.nc\"\nvalues = (\n xr.open_dataset(work_file_path, group=\"LFS-LP/observables\")\n .jsat.isel(tau=slice(-500, None))\n .persist()\n)\nRsep = Q(xr.open_dataset(work_file_path, group=\"LFS-LP\").Rsep)\n\nfor moment in [\"mean\", \"std\", \"skew\", \"kurt\"]:\n plt.figure()\n\n mean, error = tcvx21.analysis.compute_statistical_moment_with_bootstrap(\n values=values, moment=moment, ci=0.95, n_tests=1000\n )\n plot_region(Rsep, Q(mean), Q(error), label=\"95%\")\n\n mean, error = tcvx21.analysis.compute_statistical_moment_with_bootstrap(\n values=values, moment=moment, ci=0.65, n_tests=1000\n )\n plot_region(Rsep, Q(mean), Q(error), label=\"65%\")\n\n plt.legend(title=\"Confidence interval\")\n plt.title(f\"$J_{{sat}}$ {moment} on low-field-side target\")\n\nif test_session:\n plt.close(\"all\")\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom netCDF4 import Dataset\n\nstandard_dict = read_from_json(tcvx21.template_file)\nsimulation_hierarchy = read_from_json(file_path / \"simulation_hierarchy.json\")\nwork_file_path = file_path / \"processing_file.nc\"\n\ndataset = Dataset(work_file_path)\n\n\ndef strip_moment(observable_key):\n if observable.endswith(\"_std\"):\n moment = \"std\"\n key = observable_key.rstrip(\"std\").rstrip(\"_\")\n elif observable.endswith(\"_skew\"):\n moment = \"skew\"\n key = observable_key.rstrip(\"skew\").rstrip(\"_\")\n elif observable.endswith(\"_kurtosis\"):\n moment = \"kurt\"\n key = observable_key.rstrip(\"kurtosis\").rstrip(\"_\")\n else:\n moment = \"mean\"\n key = observable_key\n return key, moment\n\n\ndef write_observable(diagnostic_key, observable_key, output_dict):\n\n print(f\"\\tProcessing {diagnostic_key}:{observable_key}\")\n\n observable_key, moment = strip_moment(observable_key)\n\n diagnostic = xr.open_dataset(work_file_path, group=diagnostic_key)\n observable = xr.open_dataset(work_file_path, group=f\"{diagnostic_key}/observables\")[\n observable_key\n ]\n observable = observable.isel(tau=slice(-500, None)).persist()\n\n output_dict[\"simulation_hierarchy\"] = simulation_hierarchy[\n observable_key if moment != \"lambda_q\" else moment\n ]\n\n value, error = tcvx21.analysis.compute_statistical_moment_with_bootstrap(\n observable, moment=moment\n )\n\n output_dict[\"values\"] = Q(value).to(output_dict[\"units\"]).magnitude\n output_dict[\"errors\"] = Q(error).to(output_dict[\"units\"]).magnitude\n\n for variable_key in diagnostic.variables.keys():\n variable = diagnostic[variable_key]\n output_key = variable_key.replace(\"Rsep\", \"Ru\")\n\n output_dict[output_key] = variable.values\n output_dict[f\"{output_key}_units\"] = getattr(variable, \"units\", \"\")\n\n\nprint(\"Filling standard dict\")\n\nfor diagnostic, diagnostic_dict in standard_dict.items():\n for observable, observable_dict in diagnostic_dict[\"observables\"].items():\n write_observable(diagnostic, observable, observable_dict)\n\nprint(\"Done\")\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# Finally, we write this into a standard NetCDF\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.record_c.record_writer_m import RecordWriter\n\nwriter = RecordWriter(\n file_path=file_path / \"GRILLIX_example.nc\",\n descriptor=\"GRX\",\n description=Path(file_path / \"description.txt\").read_text(),\n allow_overwrite=True,\n)\n\nwriter.write_data_dict(standard_dict)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# To perform the entire setup and file write in a single step, you can also use\n# the following command, although this is more for convenience\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.grillix_post.validation_writer_m import (\n convert_work_file_to_validation_netcdf,\n)\n\nconvert_work_file_to_validation_netcdf(\n work_file=file_path / \"processing_file.nc\",\n output_file=file_path / \"GRILLIX_example.nc\",\n simulation_hierarchy=tcvx21.read_from_json(\n tcvx21.grillix_dir / \"simulation_hierarchy.json\"\n ),\n)\n\n# %% [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# We can then load this as a `Record` -- a NetCDF file which has a rigid common\n# structure shared between the simulations and the experiment.\n#\n# This allows us to write interfaces to the data -- i.e. plotting routines -- and\n# don't have to worry about which data source the data is coming from\n\n# %% jupyter={\"outputs_hidden\": false} pycharm={\"name\": \"#%%\\n\"}\nfrom tcvx21.record_c.record_m import Record\n\nds = Record(file_path / \"GRILLIX_example.nc\", color=\"C1\", label=\"GRILLIX\")\n\nplt.figure()\nds.get_observable(\"LFS-LP\", \"density\").plot()\n\nplt.figure()\nds.get_observable(\"RDPA\", \"density\").plot(log_cbar=True)\n\nif test_session:\n plt.close(\"all\")\n# %%\n", "meta": {"hexsha": "3a35ab7a14308642e01599d6d47e6ab0795ac2b1", "size": 28322, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/simulation_postprocessing.py", "max_stars_repo_name": "dsoliveir/TCV-X21", "max_stars_repo_head_hexsha": "784c55adb33417e21a6736e2504a3895a9348dbe", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-13T11:52:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T11:52:39.000Z", "max_issues_repo_path": "notebooks/simulation_postprocessing.py", "max_issues_repo_name": "dsoliveir/TCV-X21", "max_issues_repo_head_hexsha": "784c55adb33417e21a6736e2504a3895a9348dbe", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-18T17:18:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T09:23:23.000Z", "max_forks_repo_path": "notebooks/simulation_postprocessing.py", "max_forks_repo_name": "dsoliveir/TCV-X21", "max_forks_repo_head_hexsha": "784c55adb33417e21a6736e2504a3895a9348dbe", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-12-13T12:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:30:28.000Z", "avg_line_length": 36.7818181818, "max_line_length": 212, "alphanum_fraction": 0.7184167785, "include": true, "reason": "import numpy,from scipy", "num_tokens": 7810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.16238003666671086, "lm_q1q2_score": 0.08119001833335543}} {"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n\"Open\n\n%%html\n\n\n

    Code is hidden for ease of viewing. Click the Show/Hide button to see. \n

    \n\n# Modules\n\nimport string\nimport numpy as np\nimport pandas as pd\nimport qgrid as q\nimport matplotlib.pyplot as plt\n\n# Widgets & Display modules, etc..\n\nfrom ipywidgets import widgets as w\nfrom ipywidgets import Button, Layout\nfrom IPython.display import display, Javascript, Markdown, HTML\n\n# grid features for interactive grids \n\ngrid_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': True,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n\ndef rerun_cell( b ):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+2)')) \n\ndef check_answers(series_input,answer_list):\n \n # convert valid answer list to string format \n \n valid_answers = \"\"\n \n for item in answer_list:\n \n valid_answers = valid_answers + item + \",\"\n \n valid_answers = valid_answers[:len(valid_answers)-1]\n \n # compare student's answers to answer list\n \n for entry in series_input:\n \n if(entry != '' and entry not in answer_list):\n \n # display(Markdown(\"Some of your inputs are invalid. Please enter valid inputs from the following: \", valid_answers))\n \n return 0\n \n return 1\n\nname_text = w.Textarea( value='', placeholder='STUDENT NAME', description='', disabled=False , layout=Layout(width='30%', height='32.5px') )\ndate_text = w.Textarea( value='', placeholder='DATE', description='', disabled=False , layout=Layout(width='30%', height='32.5px') )\nprofile_button = w.Button(button_style='info',description=\"Save\", layout=Layout(width='15%', height='30px'))\n\ndisplay(name_text)\ndisplay(date_text)\ndisplay(profile_button)\n\nprofile_button.on_click( rerun_cell ) \n\nname = name_text.value\ndate = date_text.value\n\nname_saved = False\ndate_saved = False\n\nif(name != ''):\n \n name_text.close()\n display(Markdown(\"### Student Name: $\\hspace{1.5cm}$\"+ name ))\n name_saved = True\n \nif(date != ''):\n \n date_text.close()\n display(Markdown(\"### $\\hspace{2.15cm}$Date: $\\hspace{1.5cm}$\"+ date ))\n date_saved = True\n \nif(name_saved == True and date_saved == True):\n \n profile_button.close()\n\n# Budget and Banking\n\n## Assignment Lesson 1\n\nanswers_recorded = 0\nq1_answered = 0\nq2_answered = 0\nq3a_answered = 0\nq3b_answered = 0\nq3c_answered = 0\nq3d_answered = 0\n\nFor question 1 and 2, choose the best answer.\n\n**Question 1.** A good reason for preparing a budget\n\nif(q1_answered == 1):\n \n q1_answered += 1\n q1_student_answer = q1_choices.value\n correct_answer = 'd.) All the above are good reasons for preparing a budget'\n \n if(q1_student_answer == correct_answer):\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q1_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q1_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n \n # Question 1 Answer Choices\n\n choice_1 = 'a.) Running out of money each month'\n choice_2 = 'b.) To reduce debt'\n choice_3 = 'c.) To save for something special'\n choice_4 = 'd.) All the above are good reasons for preparing a budget'\n\n answer_choices = [ choice_1,choice_2,choice_3,choice_4 ]\n\n # Question 1 choices widget \n\n q1_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q1_choices)\n\nq1_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q1_choices.close()\n \nif(q1_answered >= 2):\n \n q1_button.close()\n \nelse:\n \n q1_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q1_button.on_click( record_answer ) \n display(q1_button)\n\n**Question 2.** Which equation best describes gross and net pay?\n\nif(q2_answered == 1):\n \n q2_answered += 1\n q2_student_answer = q2_choices.value\n correct_answer = 'b.) Net Pay = Gross Pay - Deductions'\n \n if(q2_student_answer == correct_answer):\n\n display(Markdown(\"### You answered: \"))\n display(Markdown(q2_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q2_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n\n # Question 2 Answer Choices\n\n choice_1 = 'a.) Gross Pay = Net Pay - Deductions'\n choice_2 = 'b.) Net Pay = Gross Pay - Deductions'\n choice_3 = 'c.) Gross Pay = Net Pay ÷ Deductions'\n choice_4 = 'd.) Net Pay = Gross Pay ÷ Deductions'\n\n answer_choices = [ choice_1,choice_2,choice_3,choice_4 ]\n\n q2_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q2_choices)\n\nq2_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q2_choices.close()\n \nif(q2_answered >= 2):\n \n q2_button.close()\n \nelse:\n \n q2_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q2_button.on_click( record_answer ) \n display(q2_button)\n\n**Question 3.** Label the following incomes as **fixed** or **variable**. Explain reasons for each.\n\n$\\hspace{0.35cm}$**a.)** Lloyd earns $50.00 for every set of knife he sells.\n\nif(q3a_answered == 1):\n \n q3a_answered += 1\n q3a_student_answer = q3a_choices.value\n correct_answer = 'Variable'\n\n if(q3a_student_answer == correct_answer):\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3a_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3a_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n\n # Question 3.a Answer Choices\n\n choice_1 = 'Fixed'\n choice_2 = 'Variable'\n\n answer_choices = [ choice_1,choice_2 ]\n\n q3a_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q3a_choices)\n\nq3a_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q3a_choices.close()\n \nif(q3a_answered >= 2):\n \n q3a_button.close()\n \nelse:\n \n q3a_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q3a_button.on_click( record_answer ) \n display(q3a_button)\n\n$\\hspace{0.35cm}$**b.)** Each month, Florence is paid 4.5% commission on her first $1,500.00 in sales. If she makes more than this, Florence is paid 6% in commission.\n\nif(q3b_answered == 1):\n \n q3b_answered += 1\n q3b_student_answer = q3b_choices.value\n correct_answer = 'Variable'\n \n if(q3b_student_answer == correct_answer):\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3b_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3b_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n\n # Question 3.b Answer Choices\n\n choice_1 = 'Fixed'\n choice_2 = 'Variable'\n\n answer_choices = [ choice_1,choice_2 ]\n\n q3b_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q3b_choices)\n\nq3b_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q3b_choices.close()\n \nif(q3b_answered >= 2):\n \n q3b_button.close()\n \nelse:\n \n q3b_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q3b_button.on_click( record_answer ) \n display(q3b_button)\n\n$\\hspace{0.35cm}$**c.)** Corinne works 40 hours a week at $17.00 an hour. She is paid bi-weekly (every two weeks).\n\nif(q3c_answered == 1):\n \n q3c_answered += 1\n q3c_student_answer = q3c_choices.value\n correct_answer = 'Fixed'\n \n if(q3c_student_answer == correct_answer):\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3c_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3c_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n\n # Question 3.c Answer Choices\n\n choice_1 = 'Fixed'\n choice_2 = 'Variable'\n\n answer_choices = [ choice_1,choice_2 ]\n\n q3c_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q3c_choices)\n\nq3c_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q3c_choices.close()\n \nif(q3c_answered >= 2):\n \n q3c_button.close()\n \nelse:\n \n q3c_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q3c_button.on_click( record_answer ) \n display(q3c_button)\n\n$\\hspace{0.35cm}$**d.)** Gord earns a salary of $3,000.00 each month.\n\nif(q3d_answered == 1):\n \n q3d_answered += 1\n q3d_student_answer = q3d_choices.value\n correct_answer = 'Fixed'\n \n if(q3d_student_answer == correct_answer):\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3d_student_answer))\n \n display(Markdown(\"This is correct!\"))\n \n else:\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(q3d_student_answer))\n\n display(Markdown(\"This is incorrect.\"))\n display(Markdown(\"### Correct answer: \"))\n display(Markdown(correct_answer))\n \nelse:\n\n # Question 3.d Answer Choices\n\n choice_1 = 'Fixed'\n choice_2 = 'Variable'\n\n answer_choices = [ choice_1,choice_2 ]\n\n q3d_choices = w.RadioButtons( options=answer_choices , description=\"\" , disabled=False , layout=Layout(width='100%'))\n display(q3d_choices)\n\nq3d_answered += 1\n\ndef record_answer(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range( IPython.notebook.get_selected_index()-1 , IPython.notebook.get_selected_index()+1) ')) \n q3d_choices.close()\n \nif(q3d_answered >= 2):\n \n q3d_button.close()\n \nelse:\n \n q3d_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n q3d_button.on_click( record_answer ) \n display(q3d_button)\n\n4) Lian works in a retail store $35$ hours a week. She is paid $\\$12.75$ an hour bi-weekly (every two weeks). Her last paycheque had a deduction of $\\$71.19$ for Income Tax, $\\$35.82$ for CPP, and $\\$14.85$ for EI.\n\n$\\hspace{1.5cm}$a.) Determine Lian's gross pay for two weeks.\n\n**Write your calculations below.** \n* Valid inputs: Numbers and decimals. \n* Valid operations: `+,-,*` for addition, subtraction, and multiplication, respectively.\n\n**Example input:** `40 * 10 * 2 + 30`\n\nq4a_text = w.Textarea( value='', placeholder='Your calculations for Exercise 4.a.', description='', disabled=False , layout=Layout(width='100%', height='30px') )\nq4a_button = w.Button(button_style='info',description=\"Calculate\", layout=Layout(width='15%', height='30px'))\n\ndisplay(q4a_text)\ndisplay(q4a_button)\n\nq4a_button.on_click( rerun_cell ) \n\n# Obtain user's input\n\nq4a_input = q4a_text.value\n\n# Define the valid character inputs for this exercise\n\nnumbers = '0123456789'\noperations = '+-*'\nothers = ' .'\nvalid_inputs = numbers + operations + others\n\n# Check if every character in user's string input is valid\n\nuser_input_valid = all( ch in valid_inputs for ch in q4a_input)\n\n# Check for correctness of user's calculation\n\nif(q4a_input != '' and user_input_valid == True):\n \n user_answer = eval(q4a_input)\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(\"$\\$\"+str(round(user_answer,2))+\"$\"))\n \n if(user_answer == 892.50):\n \n display(Markdown(\"Your calculation is correct!\"))\n\n q4a_button.close()\n q4a_text.close()\n \n else:\n \n display(Markdown(\"Your calculation is incorrect. Try again.\"))\n \nif(q4a_input != '' and user_input_valid == False):\n \n display(Markdown(\"Your answer contains invalid inputs or operations.\"))\n\n$\\hspace{1.5cm}$b.) Determine Lian's net pay for two weeks. \n\nq4b_text = w.Textarea( value='', placeholder='Your calculations for Exercise 4.b.', description='', disabled=False , layout=Layout(width='100%', height='30px') )\nq4b_button = w.Button(button_style='info',description=\"Calculate\", layout=Layout(width='15%', height='30px'))\n\ndisplay(q4b_text)\ndisplay(q4b_button)\n\nq4b_button.on_click( rerun_cell ) \n\n# Obtain user's input\n\nq4b_input = q4b_text.value\n\n# Define the valid character inputs for this exercise\n\nnumbers = '0123456789'\noperations = '+-*'\nothers = ' .'\nvalid_inputs = numbers + operations + others\n\n# Check if every character in user's string input is valid\n\nuser_input_valid = all( ch in valid_inputs for ch in q4a_input)\n\n# Check for correctness of user's calculation\n\nif(q4b_input != '' and user_input_valid == True):\n \n user_answer = round(eval(q4b_input),2)\n correct_answer = round(eval(\"892.5 - 71.19 - 35.82 - 14.85\"),2)\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(\"$\\$\"+str(round(user_answer,2))+\"$\"))\n \n if(user_answer == correct_answer):\n\n q4b_button.close()\n q4b_text.close()\n \n display(Markdown(\"Your calculation is correct!\"))\n \n else:\n \n display(Markdown(\"Your calculation is incorrect. Try again.\")) \n\nif(q4b_input != '' and user_input_valid == False):\n \n display(Markdown(\"Your answer contains invalid inputs or operations.\"))\n\n---\n\n

    Character Section Lesson

    \n\nTo conclude the Chapter 1 Assignment, you will be constructing a conservative budget and answering a \"what if\" question. You will be marked using a rubric that is located on the last page of the booklet.\n\n### Character Background\n\nEmma, a high school student working at a local grocery store as a cashier.\n\n### Personal Background\n\nEmma is 16 years old, in grade 11 and living at home with her parents. She plays soccer and rugby. Emma is the bass player in a band. Currently, she is using an old bass guitar that her dad played in the 1980s, and she would like to buy her own. Her goal is to buy it in five months because the band has a big gig coming up in six months. The new bass costs $828.45 including GST.\n\n\n### Salary\n\n\nEmma works part-time at Gobey’s Grocery. She is paid a biweekly amount of $321.13.\n\nEmma babysits occasionally for her neighbours for $10.00 an hour. Several of Emma's babysitting client pay her by cheque, and Emma puts the money directly into her bank account.\n\n### Expenses\n\nEmma’s parents have encouraged her to save for post-secondary schooling. To achieve this, Emma and her parents set up a direct withdrawal from her bank account of $40.00 a paycheque into an RESP account. Emma pays for her own transit pass, which she uses to travel around the city. Emma is very thrifty and creative, so she chooses to shop for clothing at local second-hand stores. Emma’s position as the bass player in a local band requires her to maintain her instrument and provide her own sound equipment.\n\nEmma downloads the bank record of her spending during two months (February and March).\n\n### Notes\n\n* The credit column contains all income (part-time job and babysitting).\n\n* The debit column contains all expenses that Emma has paid.\n\n* An automatic withdrawal of $40.00 each paycheque goes into an RESP account.\n\n* In February, Emma paid rugby fees with cash, which are $180.00.\n\n* At the end of March, Emmas’ soccer team went to an overnight tournament for which she paid $160.00 in cash as her portion of the hotel room.\n\n

    Character Section Lesson Exercises

    \n\n**Question 1.** List **at least two** reasons Emma might want to prepare a budget for herself.\n\nemma1_text = w.Textarea( value='', placeholder='Write your answer here for Question 1.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nemma1_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(emma1_text)\ndisplay(emma1_button)\n\nemma1_button.on_click( rerun_cell ) \n\nemma1_input = emma1_text.value\n\nif(emma1_input != ''):\n \n emma1_text.close()\n emma1_button.close()\n display(Markdown(\"### Your answer for Question 1:\"))\n display(Markdown(emma1_input))\n\n**Question 2.** Determine Emma’s net income for the month of February and March. Her bank statements are displayed below.\n\n# Prepare dataframes for Emma's February & March Transactions\n\nentry_types = {'Debit ($)': str , 'Credit ($)' : str}\n\nfebruary_transactions_df = pd.read_csv('./data/februarytransactions.csv',converters=entry_types)\nfebruary_transactions_df.set_index('Date',inplace=True)\nfebruary_transactions_df[['Debit ($)','Credit ($)']] = february_transactions_df[['Debit ($)','Credit ($)']].replace(np.nan,\"0.00\")\n\nmarch_transactions_df = pd.read_csv('./data/marchtransactions.csv',converters=entry_types)\nmarch_transactions_df.set_index('Date',inplace=True)\nmarch_transactions_df[['Debit ($)','Credit ($)']] = march_transactions_df[['Debit ($)','Credit ($)']].replace(np.nan,\"0.00\")\n\n# Control grid features\n\nemma_grid_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': False,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n\nq_emma_feb = q.show_grid( february_transactions_df , grid_options = emma_grid_features ) \nq_emma_mar = q.show_grid( march_transactions_df , grid_options = emma_grid_features ) \n\ndisplay(Markdown(\"

    Emma's February Transactions

    \"))\n\ndisplay(q_emma_feb)\n\n**Write your calculations below.**\n* Valid inputs: Numbers and decimals.\n* Valid operations: `+` for addition.\n\n**Example input:** `35 + 27.13 + 11.32`\n\nfeb_text = w.Textarea( value='', placeholder=\"Enter your calculation here to determine Emma's net income for the month of February. Hint: which column do Emma's income come from?\", description='', disabled=False , layout=Layout(width='100%', height='30px') )\nfeb_button = w.Button(button_style='info',description=\"Calculate\", layout=Layout(width='15%', height='30px'))\n\ndisplay(feb_text)\ndisplay(feb_button)\n\nfeb_button.on_click( rerun_cell ) \n\n# Obtain user's input\n\nfeb_input = feb_text.value\n\n# Define the valid character inputs for this exercise\n\nnumbers = '0123456789'\noperations = '+'\nothers = ' .'\nvalid_inputs = numbers + operations + others\n\n# Check if every character in user's string input is valid\n\nuser_input_valid = all( ch in valid_inputs for ch in feb_input)\n\n# Check for correctness of user's calculation\n\nif(feb_input != '' and user_input_valid == True):\n \n user_answer = eval(feb_input)\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(\"$\\$\"+str(user_answer)+\"$\"))\n \n if(user_answer == 1042.26):\n \n feb_button.close()\n feb_text.close()\n \n display(Markdown(\"Your calculation is correct!\"))\n \n else:\n \n display(Markdown(\"Your calculation is incorrect. Try again.\")) \n\nif(feb_input != '' and user_input_valid == False):\n \n display(Markdown(\"Your answer contains invalid inputs or operations.\"))\n\ndisplay(Markdown(\"

    Emma's March Transactions

    \"))\n\ndisplay(q_emma_mar)\n\n**Write your calculations below.**\n* Valid inputs: Numbers and decimals.\n* Valid operations: `+` for addition.\n\n**Example input:** `35 + 27.13 + 11.32`\n\nmar_text = w.Textarea( value='', placeholder=\"Enter your calculation here to determine Emma's net income for the month of March. Hint: which column do Emma's income come from?\", description='', disabled=False , layout=Layout(width='100%', height='30px') )\nmar_button = w.Button(button_style='info',description=\"Calculate\", layout=Layout(width='15%', height='30px'))\n\ndisplay(mar_text)\ndisplay(mar_button)\n\nmar_button.on_click( rerun_cell ) \n\n# Obtain user's input\n\nmar_input = mar_text.value\n\n# Define the valid character inputs for this exercise\n\nnumbers = '0123456789'\noperations = '+'\nothers = ' .'\nvalid_inputs = numbers + operations + others\n\n# Check if every character in user's string input is valid\n\nuser_input_valid = all( ch in valid_inputs for ch in mar_input)\n\n# Check for correctness of user's calculation\n\nif(mar_input != '' and user_input_valid == True):\n \n user_answer = eval(mar_input)\n \n display(Markdown(\"### You answered: \"))\n display(Markdown(\"$\\$\"+str(user_answer)+\"$\"))\n \n if(user_answer == 922.26):\n \n mar_button.close()\n mar_text.close()\n \n display(Markdown(\"Your calculation is correct!\"))\n \n else:\n \n display(Markdown(\"Your calculation is incorrect. Try again.\")) \n\nif(mar_input != '' and user_input_valid == False):\n \n display(Markdown(\"Your answer contains invalid inputs or operations.\"))\n\n**Question 3.** Categorize Emma’s income as fixed, variable or both. Explain.\n\nemma3_text = w.Textarea( value='', placeholder='Write your answer here for Question 3.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nemma3_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(emma3_text)\ndisplay(emma3_button)\n\nemma3_button.on_click( rerun_cell ) \n\nemma3_input = emma3_text.value\n\nif(emma3_input != ''):\n \n emma3_text.close()\n emma3_button.close()\n display(Markdown(\"### Your answer for Question 3:\"))\n display(Markdown(emma3_input))\n\n

    Interactive Exercise: Entering & Saving Spreadsheet Data

    \n\n**Question 4.** By analyzing the bank statements for the two months, complete the following tables for each month.\n\n$\\hspace{0.35cm}$**a.)** For each row in the table, fill the **Expense Category** column with the appropriate expense label. The valid choices are listed below - write the associated upper case letter for each expense. Expand the **Description** column to see the expense entry.\n\n**Categories: **\n\n$$\\text{(S) Savings, (U) Utilities, (C) Clothing, (E) Entertainment, (M) Miscellaneous, (P) Personal Care, (T) Transportation, (F) Food}$$\n\n# Note to developers:\n# 1. data in tables below obtained by converting relevant pages from Math20-3Unit1Key.pdf into .csv format.\n# 2. this part of the interactive focuses on categorizing expenses\n\n# Answer key for this lesson\n\nfeb_expenses_answer_key = ['S', 'T', 'F', 'U', 'F', 'F', 'F', 'C', 'E', 'S', 'F', 'F', 'E', 'M', 'M', 'F', 'F', 'M', 'M', 'C']\nfeb_fv_answer_key = ['V','V','V','V','F','F','F']\n\n# Setting up the dataframe \n\npd.options.display.max_rows = 50 \n\nentry_types = {'Debit ($)': str , 'Balance ($)' : str}\n\nfebruary_df = pd.read_csv('./data/februarydebits.csv',converters=entry_types)\nfebruary_df.set_index('Transaction #',inplace=True)\nfebruary_df['Debit ($)'] = february_df['Debit ($)'].replace(np.nan,\"0.00\")\nfebruary_df['Expense Category'] = february_df['Expense Category'].replace(np.nan,\"\")\n\noriginal_feb_df = february_df[['Date','Description','Debit ($)','Balance ($)']]\n\n# Display interactive grid 1: categorizing expenses\n\nq_february_df = q.show_grid( february_df , grid_options = grid_features )\n\n# Recording answers\n\nq4a_button = w.Button(button_style='info',description=\"Record Answers\", layout=Layout(width='15%', height='30px'))\n\ndef record_spreadsheet(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+3)'))\n\ndisplay(q_february_df)\ndisplay(q4a_button)\n\nq4a_button.on_click( record_spreadsheet )\n\n# Recover entries\n\nq4a_recover_button = w.Button(button_style='info',description=\"Reset all values\", layout=Layout(width='15%', height='30px'))\n\ndef recover_entries(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()-1,IPython.notebook.get_selected_index()+0)'))\n \ndisplay(q4a_recover_button)\n\nq4a_recover_button.on_click( recover_entries )\n\n# Obtain the changed dataframe\n\nstudent_feb_df = q_february_df.get_changed_df()\n\n# Check answers\n\nanswer_list = ['S','F','C','E','T','U','M']\n\nanswers_valid = check_answers(student_feb_df['Expense Category'],answer_list)\n\nif(answers_valid == 0):\n \n display(Markdown(\"Some of your inputs are invalid. Please enter inputs from the following list: S,U,C,E,M,P,T,F\"))\n\n\n# Group the dataframe according to student's expense categories once student's answers are correct\n\nif(answers_valid == 1):\n \n # Check if every entry matches the answer key\n \n student_answers = (student_feb_df['Expense Category'].values).tolist() \n \n if( feb_expenses_answer_key == student_answers):\n \n display(Markdown(\"Your selections are correct!\"))\n\n q4a_button.close()\n q4a_recover_button.close()\n q_february_df.close()\n \n q4a_grid_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': False,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n \n student_q4a_df = q.show_grid( student_feb_df , grid_options = q4a_grid_features )\n \n display(student_q4a_df)\n \n else:\n \n display(Markdown(\"Some of your inputs are incorrect.\"))\n\n$\\hspace{0.35cm}$**b.)** Calculate the total of each expense category you used in (a). \n\n$\\hspace{3cm}$This is done for you. Proceed to exercise (c).\n\nq4b_df = pd.read_csv('./data/expensesum.csv')\nq4b_df.set_index(\"Expense Category\",inplace=True)\nq_q4b_df = q.show_grid( q4b_df , grid_options = grid_features ) \ndisplay(q_q4b_df)\n\n$\\hspace{0.35cm}$**c.)** For each category, determine whether it is **fixed** or **variable**. Enter F for fixed and V for variable.\n\n# Setting up the dataframe \n\nfixed_or_var_df = pd.read_csv('./data/fixedorvar.csv')\nfixed_or_var_df.set_index('Expense Category',inplace=True)\nfixed_or_var_df['Fixed or Variable'] = fixed_or_var_df['Fixed or Variable'].replace(np.nan,\"\")\n\nq_fixed_or_var_df = q.show_grid( fixed_or_var_df , grid_options = grid_features)\n\nq4c_button = w.Button(button_style='info',description=\"Record Answers\", layout=Layout(width='15%', height='30px'))\n\ndef record_spreadsheet(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+2)'))\n\ndisplay(q_fixed_or_var_df)\ndisplay(q4c_button)\n\nq4c_button.on_click( record_spreadsheet )\n\n# Obtain the changed dataframe\n\nq4c_df = q_fixed_or_var_df.get_changed_df()\n\n# Check answers\n\nq4c_answer_list = ['V','F','V','F','V','V','V','V']\nq4c_student_answer = (q4c_df['Fixed or Variable'].values).tolist()\n\ndef check_q4c(student_inputs):\n \n valid_inputs = 'VF'\n \n for entry in student_inputs:\n \n if(entry not in valid_inputs):\n \n display(Markdown(\"Please enter valid inputs only.\"))\n \n return False\n \n if(entry == ''):\n \n display(Markdown(\"Please fill all the entries in the spreadsheet above.\"))\n \n return False\n \n return True\n \nif(check_q4c(q4c_student_answer) == True):\n \n if(q4c_student_answer == q4c_answer_list):\n \n display(Markdown(\"Your selections are correct!\"))\n \n q4c_grid_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': False,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n \n student_q4c_df = q.show_grid( q4c_df , grid_options = q4c_grid_features )\n \n q_fixed_or_var_df.close()\n \n display(student_q4c_df)\n \n else:\n \n display(Markdown(\"Some inputs are incorrect.\"))\n\n**Question 5.** Construct a **monthly** conservative budget skeleton for Emma based upon her February and March data. To do this, compare the data for February and March and use the _highest_ expense amount for each category.\n\n**Note: ** The **February Expense Data** and **March Expense Data** are given below.\n\nentry_types = {'February Totals ($)': str , 'March Totals ($)' : str}\n\ncomparison_df = pd.read_csv('./data/expensecomparison.csv',converters = entry_types)\ncomparison_df.set_index('Expense Categories',inplace=True)\ncomparison_df['Highest Expense Amount ($)'] = comparison_df['Highest Expense Amount ($)'].replace(np.nan,\"\")\n\ndel comparison_df['Transaction #']\n\nq_comparison_df = q.show_grid( comparison_df , grid_options = grid_features )\n\nexpense_button = w.Button(button_style='info',description=\"Record Answers\", layout=Layout(width='15%', height='30px'))\n\ndef record_spreadsheet(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+3)')) \n \ndisplay(q_comparison_df)\ndisplay(expense_button)\n\nexpense_button.on_click( record_spreadsheet )\n\n# Recover entries\n\nrecover_button = w.Button(button_style='info',description=\"Reset all values\", layout=Layout(width='15%', height='30px'))\n\ndef recover_entries(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()-1,IPython.notebook.get_selected_index()+0)'))\n \ndisplay(recover_button)\n\nrecover_button.on_click( recover_entries )\n\n# Obtain changed dataframe\n\nstudent_comparison_df = q_comparison_df.get_changed_df()\n\n# Answers \n\ncorrect_answers = ['80.00', '73.50', '91.95', '30.15', '189.45', '233.64', '206.00', '116.53']\nstudent_answers = (student_comparison_df['Highest Expense Amount ($)'].values).tolist()\n\n# Function to check if every entry is a valid input\n\ndef check_floats(input_array):\n \n valid_inputs = '0123456789.'\n \n for answer in input_array:\n \n current_user_input = all( ch in valid_inputs for ch in answer)\n \n if(current_user_input == False):\n \n return False\n \n return True\n\n# Check if answer is correct\n\nif(check_floats(student_answers) == False):\n \n display(Markdown(\"Please enter decimal numbers only.\"))\n \nelse:\n\n if(student_answers == correct_answers):\n\n display(Markdown(\"Your choices are correct!\"))\n\n recover_button.close()\n expense_button.close()\n q_comparison_df.close()\n \n comparison_grid_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': False,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n \n student_comparison_df = q.show_grid( student_comparison_df , grid_options = comparison_grid_features )\n display(student_comparison_df)\n \n else:\n \n display(Markdown(\"Some of your entries are incorrect. Please fill them with the correct values. Make sure to write numbers in decimal form. Write 80.00 for 80, 206.00, etc.\"))\n\n**Question 6.** If there is excess money, where should Emma put it? If there is not enough income for expenses, suggest how Emma can cover her expenses or reduce her expenses.\n\nq6_text = w.Textarea( value='', placeholder='Write your answer here for Question 6.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nq6_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(q6_text)\ndisplay(q6_button)\n\nq6_button.on_click( rerun_cell ) \n\nq6_input = q6_text.value\n\nif(q6_input != ''):\n \n q6_text.close()\n q6_button.close()\n display(Markdown(\"### Your answer for question 6:\"))\n display(Markdown(q6_input))\n\n**Question 7.**\n\n$\\hspace{0.35cm}$**a.)** How much will Emma need to save each month to purchase a new base, in 5 months, that costs $\\$828.45$ (including GST)?\n\nq7a_text = w.Textarea( value='', placeholder='Write your answer here for Question 7.a.', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nq7a_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(q7a_text)\ndisplay(q7a_button)\n\nq7a_button.on_click( rerun_cell ) \n\nq7a_input = q7a_text.value\n\nif(q7a_input != ''):\n \n q7a_text.close()\n q7a_button.close()\n display(Markdown(\"### Your answer for question 7.a:\"))\n display(Markdown(q7a_input))\n\n$\\hspace{0.35cm}$**b.)** Based upon her budget, will Emma be able to save enough? If not, modify her budget so that she can afford it. A new category has been added to show her savings for the bass.\n\n**Note:** Income and expenses should be balanced at this point.\n\nFrom the previous exercises, we saw that a conservative income for Emma was $\\$922.26$. In this exercise, we want to create a budget amount in such a way that the sum of each category is exactly $\\$922.26$.\n\n# Prepare dataframes for Emma's February & March Transactions\n\nex_7b_df = pd.read_csv('./data/exercise7b.csv')\nex_7b_df[['Budgeted Amount ($)']] = ex_7b_df[['Budgeted Amount ($)']].replace(np.nan,\"\")\nex_7b_df.set_index('Category',inplace=True)\n\nq_ex_7b = q.show_grid( ex_7b_df , grid_options = grid_features ) \n\ndisplay(Markdown(\"

    Emma's Modified Conservative Budget

    \"))\n\ndisplay(q_ex_7b)\n\nex_7b_button = w.Button(button_style='info',description=\"Record Answers\", layout=Layout(width='15%', height='30px'))\n\ndef record_spreadsheet(button_widget):\n \n display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index()+1,IPython.notebook.get_selected_index()+3)')) \n \ndisplay(ex_7b_button)\n\nex_7b_button.on_click( record_spreadsheet )\n\n**Question 8.** Determine the percent of Emma’s income on each category. \n\nTo calculate percentage of income for each category use the formula:\n\n$$\\text{Percent of Income} = \\frac{\\text{Amount Allotted for Expense}}{\\text{Budgeted Income}}\\times 100\\%$$\n\n**Note:** This part of the exercise is done for you and changes based on your inputs in exercise 7.b., the formula above is for your reference.\n\n# Set up student inputs as a list\n\nex_7b_student_df = q_ex_7b.get_changed_df()\nstudent_budget_input = ex_7b_student_df['Budgeted Amount ($)']\nstudent_budget_col = (student_budget_input.values).tolist()\n\n# Check if every entry is valid \n\ndef check_ex_7b(student_inputs):\n\n valid_inputs = '0123456789. '\n\n for entry in student_inputs:\n\n for ch in entry:\n \n if(ch not in valid_inputs):\n \n display(Markdown(\"Please enter valid inputs only.\"))\n\n return False\n\n if(entry == ''):\n\n display(Markdown(\"Please fill all the entries in the spreadsheet above.\"))\n\n return False\n\n return True\n\n# Check if student's budget matches the total income\n\nvalid_input = check_ex_7b(student_budget_col)\n\nif(valid_input == True):\n \n # Convert every entry to float and get the sum\n \n budget_sum = 0\n \n for entry in student_budget_col:\n \n current_entry = eval(entry)\n budget_sum += current_entry\n \n # If the budget sum matches, then create the percentages chart \n \n percentages_col = []\n \n if(budget_sum != 922.26): \n \n display(Markdown(\"Your budget proposal does not total $922.26. Please try again.\"))\n \n else:\n \n for entry in student_budget_col:\n \n current_percent = round( eval(entry)/budget_sum , 4)\n percentages_col.append( round(current_percent*100,4) )\n \n indices = ['Savings (RESP)','Transportation','Utilities','Food','Clothing','Entertainment','Miscellaneous','Personal Care','Savings (Bass)']\n \n percentage_df = pd.DataFrame({'Percentage (%): ': percentages_col },index=indices)\n updated_ex_7b_student_df = pd.concat( [ex_7b_student_df,percentage_df] , axis = 1 )\n \n ex_7b_features = { 'fullWidthRows': True,\n 'syncColumnCellResize': True,\n 'forceFitColumns': True,\n 'rowHeight': 40,\n 'enableColumnReorder': True,\n 'enableTextSelectionOnCells': True,\n 'editable': False,\n 'filterable': False,\n 'sortable': False,\n 'highlightSelectedRow': True}\n \n q_ex_7b_updated = q.show_grid( updated_ex_7b_student_df , grid_options = ex_7b_features )\n \n display(Markdown(\"

    Emma's Modified Budget Percentage Breakdown

    \"))\n \n display(q_ex_7b_updated)\n\n**Question 9.** Are there any categories that Emma is far above or far below the spending guidelines? How does being a high school student affect Emma’s consideration of the spending guidelines?\n\n\"drawing\"\n\n\nq9_text = w.Textarea( value='', placeholder='Write your answer here for Question 9', description='', disabled=False , layout=Layout(width='100%', height='75px') )\nq9_button = w.Button(button_style='info',description=\"Record Answer\", layout=Layout(width='15%', height='30px'))\n\ndisplay(q9_text)\ndisplay(q9_button)\n\nq9_button.on_click( rerun_cell ) \n\nq9_input = q9_text.value\n\nif(q9_input != ''):\n \n q9_text.close()\n q9_button.close()\n display(Markdown(\"### Your answer for question 9:\"))\n display(Markdown(q9_input))\n\n--- \n

    Student Interactive Section

    \n\nIn this section, you will enter your own expense categories and see how your expense percentage breakdown compares to the spending guideline above.\n\n# Create button and dropdown widget\n\nnumber_of_cat = 13\ndropdown_options = [ str(i+1) for i in range(number_of_cat) ] \ndropdown_widget = w.Dropdown( options = dropdown_options , value = '3' , description = 'Categories' , disabled=False )\n\ncategories_button = w.Button(button_style='info',description=\"Save\", layout=Layout(width='15%', height='30px'))\n\n# Display widgets\n\ndisplay(dropdown_widget)\ndisplay(categories_button)\n\ncategories_button.on_click( rerun_cell ) \n\n# Create dataframe\n\ndf_num_rows = int(dropdown_widget.value)\nempty_list = [ '' for i in range(df_num_rows) ] \ncategory_list = [ i+1 for i in range(df_num_rows) ] \n\n# Set up data input for dataframe\n\ndf_dict = {'Category #': category_list, 'Budget ($)': empty_list , 'Expense Category': empty_list}\n\nstudent_df = pd.DataFrame(data = df_dict)\nstudent_df.set_index('Category #',inplace=True)\n\n# Reorder column labels\n\nstudent_df = student_df[['Expense Category','Budget ($)']]\n\n# Set up & display as Qgrid\n\nq_student_df = q.show_grid( student_df , grid_options = grid_features )\ndisplay(q_student_df)\n\n# Create & display save entries widget button\n\nsave_student_entries_button = w.Button(button_style='info',description=\"Plot Pie Chart\", layout=Layout(width='15%', height='30px'))\ndisplay(save_student_entries_button)\n\nsave_student_entries_button.on_click( rerun_cell ) \n\n# Convert qgrid to dataframe\n\nstudent_updated_df = q_student_df.get_changed_df()\n\nstudent_budget_col = student_updated_df['Budget ($)'].values.tolist()\nstudent_labels_col = student_updated_df['Expense Category'].values.tolist()\n\n# Check if a number if float\n\ndef isfloat(value):\n \n try:\n \n float(value)\n \n return True\n \n except ValueError:\n \n return False\n\n# Function: Check for validity of budget column entries\n# Input: Student's budget column values\n# Output: Boolean, false if one of the entries is invalid\n\ndef check_budget_column(input_list):\n \n valid_inputs = '0123456789.'\n \n # Check if inputs are valid\n \n for entry in input_list:\n \n if( isfloat(entry) == False):\n \n return False\n \n return True\n\n# Function: Calculate the percentage of each expense category\n# Input: Student expense category lists and student budget column values\n# Output: Percentages column \n\ndef get_percentages(input_list):\n \n total = 0\n percentage_col = []\n \n # Obtain total\n \n for entry in input_list:\n \n entry = eval(entry) \n total += entry\n \n # Obtain percentages\n \n for entry in input_list:\n \n entry = eval(entry)\n current_percentage = entry/total\n percentage_col.append( round(current_percentage*100,2) )\n \n return percentage_col\n\n# If student input is valid, create a pie chart plot\n\ncolors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral','darkseagreen','lightcyan','lightpink','coral','tan','slateblue','azure','tomato','lawngreen']\n\nif(check_budget_column(student_budget_col) == True):\n \n student_values = get_percentages(student_budget_col)\n labels = student_labels_col\n \n plt.figure(figsize=(20,10))\n plt.rcParams['font.size'] = 20\n plt.title('Your Expense Category Percentage Breakdown',fontsize=25)\n plt.pie(student_values, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=35)\n plt.axis('equal') \n plt.show()\n \nelse:\n \n display(Markdown(\"Please enter decimal numbers only for the budget column\"))\n\n[![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)", "meta": {"hexsha": "9a478187cff16456c8193da8a6ed49a4f069c72a", "size": 45500, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/BudgetAndBankingAssignment/budget-and-banking-assignment.py", "max_stars_repo_name": "BryceHaley/curriculum-jbook", "max_stars_repo_head_hexsha": "d1246799ddfe62b0cf5c389394a18c2904383437", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T18:19:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:19:40.000Z", "max_issues_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/BudgetAndBankingAssignment/budget-and-banking-assignment.py", "max_issues_repo_name": "callysto/curriculum-jbook", "max_issues_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/BudgetAndBankingAssignment/budget-and-banking-assignment.py", "max_forks_repo_name": "callysto/curriculum-jbook", "max_forks_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6867816092, "max_line_length": 509, "alphanum_fraction": 0.6713626374, "include": true, "reason": "import numpy", "num_tokens": 11017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.16667540675766923, "lm_q1q2_score": 0.08073424757218048}} {"text": "#!/usr/bin/env python\nimport numpy as np\nfrom openbabel import pybel\n# import time\nfrom rdkit import Chem\nfrom rdkit.Chem import Draw\nfrom pdbtools.pdbtools import pdbtools\n\n\ndef cal_angle_from_points(dist_lp, dist_dh, dist_ah):\n cos_theta = (np.power(dist_dh, 2) + np.power(dist_ah, 2) -\n np.power(dist_lp, 2)) / (2 * dist_dh * dist_ah)\n theta = np.arccos(cos_theta)\n\n return theta\n\n\ndef cal_angle_from_vectors(A, B):\n cos_theta = np.dot(A, B)\n theta = np.arccos(cos_theta)\n return theta\n\n\nclass Pharmacophore(object):\n \"\"\"\n pharmacophore\n \"\"\"\n feature_type_dict = {\n 'HBD': 0,\n 'HBA': 1,\n 'Anion': 2,\n 'Cation': 3,\n 'Hydrophobic': 4,\n 'Aromatic': 5\n }\n feature_type_list = ['HBD', 'HBA', 'Anion',\n 'Cation', 'Hydrophobic', 'Aromatic']\n\n complementary_feature = {\n 'HBD': [['HBA', 3.4]],\n 'HBA': [['HBD', 3.4]],\n 'Anion': [['Cation', 5.0]],\n 'Cation': [['Anion', 5.0], ['Aromatic', 5.0]],\n 'Hydrophobic': [['Hydrophobic', 6.5]],\n 'Aromatic': [['Cation', 5.0], ['Aromatic', 6.0]],\n 'MBA': [['Metal', 3.1]],\n 'Metal': [['MBA', 3.1]],\n }\n\n num_feature_type = len(feature_type_list)\n SMARTS_pattern_dict = {\n 'HBD': {\n 0: '[N&H2&v3]',\n 1: '[N&H1&v3]',\n 2: '[N&!H0&+1&v4]',\n 3: '[n&H1&+0]',\n 4: '[n&H1&+1]',\n 5: '[O;H1;+0]',\n 6: '[S;H1;+0]',\n 7: '[O;H2;+0]',\n },\n 'HBA': {\n 0: '[$([O,S;-])]',\n 1: '[$([O,S;H0;v2])]',\n 2: '[$([O,S;H1;v2]-[!$(*=[O,N,P,S])])]',\n 3: '[$([N;v3;!$(N-*=!@[O,N,P,S])])]',\n 4: '[$([nH0,o,s;+0])]',\n 5: '[$([N;H0]#[C&v4])]',\n 6: '[N&v3;H0;$(Nc)]',\n 7: '[F;$(F-[#6])]',\n 8: '[O;H2;+0]',\n\n },\n 'Anion': {\n 0: '[-]',\n 1: '[SX4](=O)(=O)(-[O;H1,H0&-1])',\n 2: '[PX4](=O)(-[O;H1,H0&-1])([!O])([!O])',\n 3: '[PX4](=O)(-[O;H1,H0&-1])(-[O;H1,H0&-1])',\n 4: '[CX3,SX3](=[O,S,P])-[O;H1,H0&-1]',\n },\n 'Cation': {\n 0: '[+]',\n 1: '[NX3]=[CX3]([NX3])[!N]',\n 2: 'NC(=N)N',\n 3: 'c1ncnc1'\n },\n 'Hydrophobic': {\n 0: '[D3,D4;#6;+0;!$([#6][#7,#8,#9])]',\n 1: '[R0;D2;#6;+0;!$([#6][#7,#8,#9])]',\n 2: '[CX4](F)(F)(F)',\n 3: '[#6;R]',\n 4: '[#17,#35,#53]',\n },\n 'Aromatic': {\n 0: 'a1:a:a:a:1',\n 1: 'a1:a:a:a:a:1',\n 2: 'a1:a:a:a:a:a:1',\n 3: 'a1:a:a:a:a:a:a:1',\n 4: 'a1:a:a:a:a:a:a:a:1',\n }\n }\n\n metal_name_dict = {\n 'MG': 0,\n 'K': 1,\n 'MN': 2,\n 'FE': 3,\n 'ZN': 4,\n }\n metal_type_list = ['MG', 'K', 'MN', 'FE', 'ZN']\n metal_atomic_name_dict = {12: 'MG', 19: 'K', 25: 'MN', 26: 'FE', 30: 'ZN'}\n metal_bind_name_dict = {\n 7: 0,\n 8: 1,\n 16: 2,\n }\n metal_interaction_cutoff = {\n 0: {2: 2.6, 3: 2.5, 4: 2.56},\n 1: {0: 3.1, 1: 2.4, 2: 2.7, 3: 2.5, 4: 2.8},\n 2: {4: 2.6},\n }\n\n weight_pis = {\n 'HBD:HBA': 0.129,\n 'HBA:HBD': 0.129,\n 'Anion:Cation': 0.31,\n 'Cation:Anion': 0.31,\n 'Cation:Aromatic': 0.039,\n 'Hydrophobic:Hydrophobic': 0.00585,\n 'Aromatic:Cation': 0.039,\n 'Aromatic:Aromatic': 0.064,\n 'MBA:Metal': 1.0\n }\n bias_pis = 4.0\n cutoff = 6.5\n use_pinfo = False\n\n def __init__(self, params=None):\n \"\"\"\n initialize Pharmacophore\n set parameters\n \"\"\"\n\n self.interaction_feature = list(self.weight_pis.keys())\n if 'weight_pis' in params:\n self.weight_pis = params['weight_pis']\n if 'bias_pis' in params:\n self.bias_pis = params['bias_pis']\n if 'cutoff' in params:\n self.cutoff = params['cutoff']\n cmin = -99999.999\n cmax = 99999.999\n\n use_box = False\n if 'dock_config' in params:\n box_center, box_size = self.read_dock_config(params['dock_config'])\n box_min = box_center - box_size/2\n box_max = box_center + box_size/2\n cmin = box_min - self.cutoff\n cmax = box_max + self.cutoff\n use_box = True\n\n if 'ligand_file' in params:\n ligand_file = params['ligand_file']\n ligand_model_dict = pdbtools.read_coor_pdb(\n ligand_file, exclude_Hs=True)\n ligand_dict = ligand_model_dict[1]\n ligand_coor = list(ligand_dict.values())[0]\n cmin, cmax = pdbtools.cal_ligand_size(ligand_coor)\n cmin = cmin - self.cutoff\n cmax = cmax + self.cutoff\n use_box = True\n\n if 'include_hydrophobic' in params:\n include_hydrophobic = params['include_hydrophobic']\n\n piscore_receptor = params['piscore_receptor']\n pf_receptor = params['pf_receptor']\n\n if piscore_receptor is not None:\n ms = pybel.readfile('pdb', piscore_receptor)\n m_protein = list(ms)[0]\n receptor_bond_dict = self.get_bond_info(m_protein)\n PF_dict_protein = self.find_PF(m_protein, receptor_bond_dict,\n is_protein=True)\n PF_coor_protein = self.find_PF_coor(m_protein, PF_dict_protein,\n receptor_bond_dict, is_protein=True)\n metal_coor = self.find_metal_ion(m_protein, is_protein=True)\n PF_coor_protein['Metal'] = metal_coor\n if use_box:\n self.PF_coor_protein = self.box_protein(\n PF_coor_protein, cmin, cmax)\n else:\n self.PF_coor_protein = PF_coor_protein\n if pf_receptor is not None:\n PF_coor_protein_dict = {0: self.PF_coor_protein}\n self.write_PF(PF_coor_protein_dict,\n pf_receptor, is_protein=True)\n elif pf_receptor is not None:\n self.PF_coor_protein = self.read_PF(pf_receptor,\n is_protein=True)[0]\n\n pinfo_ligand = params['pinfo_ligand']\n pf_receptor_info = params['pf_receptor_info']\n if pinfo_ligand is not None:\n self.use_pinfo = True\n template_dict = self.find_template(self.PF_coor_protein, pinfo_ligand,\n include_hydrophobic=include_hydrophobic)\n self.PF_coor_info = self.select_template_protein(self.PF_coor_protein,\n template_dict, cut_num=1)\n if pf_receptor_info is not None:\n PF_coor_info_dict = {0: self.PF_coor_info}\n self.write_PF(PF_coor_info_dict, pf_receptor_info,\n is_protein=True)\n elif pf_receptor_info is not None:\n self.use_pinfo = True\n self.PF_coor_info = self.read_PF(\n pf_receptor_info, is_protein=True)[0]\n\n def get_bond_info(self, m):\n \"\"\"\n find neighbor atoms in molecule\n input:\n m: pybel molecule object\n output:\n bond_dict: neighbor atom dictionary\n \"\"\"\n bond_dict = dict()\n mol = m.OBMol\n\n for i in range(mol.NumBonds()):\n bb = mol.GetBondById(i)\n if bb is None:\n continue\n begin = bb.GetBeginAtomIdx()\n end = bb.GetEndAtomIdx()\n if begin not in bond_dict:\n bond_dict[begin] = [end]\n else:\n bond_dict[begin] += [end]\n if end not in bond_dict:\n bond_dict[end] = [begin]\n else:\n bond_dict[end] += [begin]\n return bond_dict\n\n def find_PF(self, m, bond_dict, is_protein=False):\n \"\"\"\n Find pharmacophoric features\n input:\n m: pybel molecule object\n is_protein: protein or not\n output: PF dictionary\n \"\"\"\n PF_dict = dict()\n atoms = m.atoms\n# bond_dict = self.get_bond_info(m)\n\n # search pharmacophoric feature using SMARTS pattern\n for feature_type in self.feature_type_list:\n patterns = self.SMARTS_pattern_dict[feature_type]\n PF_dict[feature_type] = list()\n pattern_keys = sorted(patterns.keys())\n for pattern_idx in pattern_keys:\n smarts_pattern = patterns[pattern_idx]\n smarts = pybel.Smarts(smarts_pattern)\n atom_idx_group_list = smarts.findall(m)\n Nfeatures = len(atom_idx_group_list)\n for k in range(Nfeatures):\n atom_idx_group = atom_idx_group_list[k]\n\n fea_dict = dict()\n fea_dict['atom_idx_group'] = atom_idx_group\n fea_dict['pattern_idx'] = pattern_idx\n if feature_type == 'HBD':\n h_atoms_idx = list()\n atom_idx = atom_idx_group[0]\n neighbor_atoms_idx = bond_dict[atom_idx]\n for neighbor_atom_idx in neighbor_atoms_idx:\n neighbor_atom = atoms[neighbor_atom_idx - 1]\n if neighbor_atom.atomicnum != 1:\n continue\n h_atoms_idx += [neighbor_atom_idx]\n if len(h_atoms_idx) == 0:\n continue\n fea_dict['h_atoms_idx'] = h_atoms_idx\n\n atom_idx = atom_idx_group[0]\n atom = atoms[atom_idx-1]\n fea_dict['atom_type'] = atom.type\n if is_protein:\n residue = atom.residue\n chain_id = residue.OBResidue.GetChain()\n fea_dict['chain_id'] = chain_id\n residue_name = residue.name\n fea_dict['residue_name'] = residue_name\n residue_num = residue.OBResidue.GetNum()\n fea_dict['residue_num'] = residue_num\n fea_dict['weight'] = 1.0\n\n PF_dict[feature_type] += [fea_dict]\n\n return PF_dict\n\n def find_PF_coor(self, m, PF_dict, bond_dict, is_protein=False):\n \"\"\"\n Find pharmacophoric features\n input:\n m: pybel molecule object\n PF_dict: pharmacophoric feature dictionary\n is_protein: True or False\n output:\n PF_coor: dictionary\n \"\"\"\n\n atoms = m.atoms\n PF_coor = dict()\n for feature_type in self.feature_type_list:\n if feature_type not in PF_dict:\n continue\n fea_dict_list = PF_dict[feature_type]\n PF_coor[feature_type] = list()\n Nfeatures = len(fea_dict_list)\n p00_atoms_old = list()\n num_member = list()\n for k in range(Nfeatures):\n fea_dict = fea_dict_list[k]\n num_member += [len(fea_dict['atom_idx_group'])]\n num_member = -np.array(num_member)\n index = num_member.argsort()\n for k in index:\n fea_dict = fea_dict_list[k]\n atom_idx_group = fea_dict['atom_idx_group']\n pattern_idx = fea_dict['pattern_idx']\n\n intersection = set(atom_idx_group).intersection(p00_atoms_old)\n p00_atoms_old += atom_idx_group\n if len(intersection) > 0 and feature_type != 'Aromatic':\n continue\n\n pseudo_atom = []\n for atom_index in atom_idx_group:\n coor = np.array(atoms[atom_index - 1].coords)\n pseudo_atom += [coor]\n pseudo_atom = np.array(pseudo_atom)\n pseudo_atom_coor = pseudo_atom.mean(axis=0)\n\n fea_dict_new = dict()\n fea_dict_new['atom_idx_group'] = atom_idx_group\n fea_dict_new['pattern_idx'] = pattern_idx\n fea_dict_new['pseudo_atom_coor'] = pseudo_atom_coor\n\n if feature_type == 'HBD':\n h_atoms = list()\n atom_idx = atom_idx_group[0]\n neighbor_heavy_atom_list = list()\n neighbor_atoms_idx = bond_dict[atom_idx]\n neighbor_atom_list = list()\n for neighbor_atom_idx in neighbor_atoms_idx:\n neighbor_atom = atoms[neighbor_atom_idx - 1]\n if neighbor_atom.atomicnum == 1:\n continue\n nei_coor = np.array(atoms[neighbor_atom_idx - 1].coords)\n neighbor_atom_list += [[neighbor_atom_idx, nei_coor]]\n\n h_atoms_idx = fea_dict['h_atoms_idx']\n num_neighbor_atom = len(neighbor_atom_list)\n for h_atom_idx in h_atoms_idx:\n h_coor = np.array(atoms[h_atom_idx - 1].coords)\n h_atoms += [[h_atom_idx, h_coor]]\n #if len(neighbor_atom_list)==1:\n #nei_coor = neighbor_atom_list[0][1]\n #vec_a = pseudo_atom_coor - nei_coor\n #vec_b = h_coor - pseudo_atom_coor\n #vec_c = h_coor - nei_coor\n #a = np.linalg.norm(vec_a)\n #b = np.linalg.norm(vec_b)\n #c = np.linalg.norm(vec_c)\n #d = (c**2 - a**2 - b**2)/(2*a**2)\n #m_coor = pseudo_atom_coor + vec_a * d/a\n #h_coor2 = h_coor + 2 * (m_coor - h_coor)\n #h_atoms += [[h_atom_idx, h_coor2]]\n\n fea_dict_new['h_atoms'] = h_atoms\n fea_dict_new['num_neighbor_atom'] = num_neighbor_atom\n\n\n\n elif feature_type == 'Aromatic':\n v_a = pseudo_atom[1] - pseudo_atom[0]\n v_b = pseudo_atom[2] - pseudo_atom[1]\n v_c = np.cross(v_a, v_b)\n v_n = v_c / np.linalg.norm(v_c)\n fea_dict_new['v_n'] = v_n\n fea_dict_new['atom_type'] = fea_dict['atom_type']\n if is_protein:\n fea_dict_new['chain_id'] = fea_dict['chain_id']\n fea_dict_new['residue_name'] = fea_dict['residue_name']\n fea_dict_new['residue_num'] = fea_dict['residue_num']\n fea_dict_new['weight'] = fea_dict['weight']\n\n PF_coor[feature_type] += [fea_dict_new]\n\n return PF_coor\n\n def find_metal_ion(self, m, is_protein=True):\n \"\"\"\n input:\n m: pybel molecule object\n is_protein: True or False\n output:\n metal_coor: list\n \"\"\"\n metal_coor = list()\n atoms = m.atoms\n for atom in atoms:\n atomic_num = atom.atomicnum\n\n if atomic_num not in self.metal_atomic_name_dict:\n continue\n atomic_name = self.metal_atomic_name_dict[atomic_num]\n atom_idx = atom.idx\n atom_idx_group = (atom_idx,)\n coor = np.array(atom.coords)\n if atomic_name not in self.metal_name_dict:\n continue\n pattern_idx = self.metal_name_dict[atomic_name]\n\n fea_dict = dict()\n fea_dict['atom_type'] = atom.type\n fea_dict['atom_idx_group'] = atom_idx_group\n fea_dict['pattern_idx'] = pattern_idx\n fea_dict['pseudo_atom_coor'] = coor\n if is_protein:\n residue = atom.residue\n chain_id = residue.OBResidue.GetChain()\n fea_dict['chain_id'] = chain_id\n residue_name = residue.name\n fea_dict['residue_name'] = residue_name\n residue_num = residue.OBResidue.GetNum()\n fea_dict['residue_num'] = residue_num\n fea_dict['weight'] = 1.0\n\n metal_coor += [fea_dict]\n\n return metal_coor\n\n def find_mba(self, m, is_protein=False):\n \"\"\"\n metal binding atom for ligand\n input:\n m: pybel molecule object\n is_protein: True or False\n output:\n mba_coor: list\n \"\"\"\n\n mba_coor = list()\n atoms = m.atoms\n for atom in atoms:\n atom_idx = atom.idx\n atomic_num = atom.atomicnum\n if atomic_num != 7 and atomic_num != 8 and atomic_num != 16:\n continue\n\n # if atom.formalcharge>0:\n # continue\n # Excluded because protonation state calculation is incomplete\n\n atom_idx_group = (atom_idx,)\n coor = np.array(atom.coords)\n pattern_idx = self.metal_bind_name_dict[atomic_num]\n\n fea_dict = dict()\n fea_dict['atom_type'] = atom.type\n fea_dict['atom_idx_group'] = atom_idx_group\n fea_dict['pattern_idx'] = pattern_idx\n fea_dict['pseudo_atom_coor'] = coor\n if is_protein:\n residue = atom.residue\n chain_id = residue.OBResidue.GetChain()\n fea_dict['chain_id'] = chain_id\n residue_name = residue.name\n fea_dict['residue_name'] = residue_name\n residue_num = residue.OBResidue.GetNum()\n fea_dict['residue_num'] = residue_num\n fea_dict['weight'] = 1.0\n mba_coor += [fea_dict]\n\n return mba_coor\n\n def draw_ligand(self, m_ligand, PF_dict, output_name, size):\n type_list = self.feature_type_list\n patom_list = list()\n for fea in type_list:\n patoms = list()\n fff = PF_dict[fea]\n for ff in fff:\n atom_idx_group = ff[0]\n for idx in atom_idx_group:\n patoms += [idx-1]\n patom_list += [patoms]\n m_ligand_noH = Chem.RemoveHs(m_ligand)\n m_ligand_noH.RemoveConformer(0)\n mol_list = [m_ligand_noH]*6\n img = Draw.MolsToGridImage(mol_list, legends=type_list,\n highlightAtomLists=patom_list,\n subImgSize=size, molsPerRow=2)\n img.save(output_name)\n\n def box_protein(self, PF_coor_protein, cmin, cmax):\n \"\"\"\n select PF of PF_coor_protein in the box\n input:\n PF_coor_protein: dict\n cmin : np.array\n cmax : np.array\n output:\n PF_coor_box: dict\n \"\"\"\n\n type_list = self.feature_type_list + ['Metal']\n PF_coor_box = dict()\n for fea in type_list:\n if fea not in PF_coor_protein:\n continue\n fea_dict_list = PF_coor_protein[fea]\n PF_coor_box[fea] = list()\n for fea_dict in fea_dict_list:\n pseudo_atom_coor = fea_dict['pseudo_atom_coor']\n if (pseudo_atom_coor > cmax).any():\n continue\n elif (pseudo_atom_coor < cmin).any():\n continue\n PF_coor_box[fea] += [fea_dict]\n return PF_coor_box\n\n def find_template(self, PF_coor_protein, template_ligand_file, include_hydrophobic=False):\n template_dict = dict()\n feature_type_list_receptor = self.feature_type_list + ['Metal']\n for feature_type_receptor in feature_type_list_receptor:\n if not include_hydrophobic and feature_type_receptor == 'Hydrophobic':\n continue\n template_dict[feature_type_receptor] = dict()\n\n file_format = template_ligand_file.split('.')[-1]\n ms = list(pybel.readfile(file_format, template_ligand_file))\n m_ligand = ms[0]\n ligand_bond_dict = self.get_bond_info(m_ligand)\n PF_dict_ligand = self.find_PF(m_ligand, ligand_bond_dict)\n\n num_model = len(ms)\n if num_model > 1:\n num_model = num_model - 1\n PF_coor_ligand_dict = dict()\n interaction_dict = dict()\n model_idx = 0\n m_ligand = ms[model_idx]\n PF_coor_ligand = self.find_PF_coor(m_ligand, PF_dict_ligand, ligand_bond_dict)\n mba_coor = self.find_mba(m_ligand, is_protein=False)\n PF_coor_ligand['MBA'] = mba_coor\n\n PF_coor_ligand_dict[model_idx] = PF_coor_ligand\n interaction = self.find_interaction(PF_coor_protein, PF_coor_ligand,\n ligand_bond_dict)\n interaction_dict[model_idx] = interaction\n total_rec_pf_dict = self.count_interaction_receptor(interaction_dict)\n rec_pf_dict = total_rec_pf_dict[0]\n for feature_type_receptor in rec_pf_dict.keys():\n if not include_hydrophobic and feature_type_receptor == 'Hydrophobic':\n continue\n rec_pf = rec_pf_dict[feature_type_receptor]\n atom_idx_group_list = rec_pf.keys()\n for atom_idx_group in atom_idx_group_list:\n if atom_idx_group not in template_dict[feature_type_receptor]:\n template_dict[feature_type_receptor][atom_idx_group] = 0\n template_dict[feature_type_receptor][atom_idx_group] += 1\n return template_dict\n\n def select_template_protein(self, PF_coor_protein, template_dict,\n cut_num=0):\n \"\"\"\n select PF of PF_coor_protein in template\n input:\n PF_coor_protein: dict\n template_dict: dict\n output:\n PF_coor_info: dict\n \"\"\"\n type_list = self.feature_type_list + ['Metal']\n PF_coor_info = dict()\n for fea in type_list:\n if fea not in PF_coor_protein:\n continue\n if fea not in template_dict:\n continue\n fea_dict_list = PF_coor_protein[fea]\n PF_coor_info[fea] = list()\n for fea_dict in fea_dict_list:\n atom_idx_group = fea_dict['atom_idx_group']\n if atom_idx_group not in template_dict[fea]:\n continue\n num_in_template = template_dict[fea][atom_idx_group]\n if num_in_template < cut_num:\n continue\n PF_coor_info[fea] += [fea_dict]\n return PF_coor_info\n\n def find_interaction(self, PF_coor_protein, PF_coor_ligand,\n ligand_bond_dict):\n \"\"\"\n find pharmacophoric interaction\n input:\n PF_coor_protein: dict\n PF_coor_ligand: dict\n ligand_bond_dict: dict\n output:\n interaction: dict\n \"\"\"\n type_list = self.feature_type_list + ['MBA']\n# type_list = self.feature_type_list\n\n coor_ligand_list = list()\n for fea_ligand in type_list:\n if fea_ligand not in PF_coor_ligand:\n continue\n fea_dict_list_ligand = PF_coor_ligand[fea_ligand]\n for fea_dict_ligand in fea_dict_list_ligand:\n coor_ligand = fea_dict_ligand['pseudo_atom_coor']\n coor_ligand_list.append(coor_ligand)\n coor_ligand_list = np.array(coor_ligand_list)\n cmin = coor_ligand_list.min(axis=0) - self.cutoff\n cmax = coor_ligand_list.max(axis=0) + self.cutoff\n\n PF_coor_protein_box = self.box_protein(PF_coor_protein, cmin, cmax)\n\n interaction = dict()\n for fea_ligand in type_list:\n if fea_ligand not in interaction:\n interaction[fea_ligand] = dict()\n if fea_ligand not in PF_coor_ligand:\n continue\n fea_dict_list_ligand = PF_coor_ligand[fea_ligand]\n cfea_list = self.complementary_feature[fea_ligand]\n for fea_dict_ligand in fea_dict_list_ligand:\n idx_ligand = fea_dict_ligand['atom_idx_group']\n pattern_ligand = fea_dict_ligand['pattern_idx']\n coor_ligand = fea_dict_ligand['pseudo_atom_coor']\n for cfea_t in cfea_list:\n fea_protein = cfea_t[0]\n if fea_protein not in interaction[fea_ligand]:\n interaction[fea_ligand][fea_protein] = list()\n pair_cutoff = cfea_t[1]\n if fea_protein not in PF_coor_protein_box:\n continue\n fea_dict_list_protein = PF_coor_protein_box[fea_protein]\n for fea_dict_protein in fea_dict_list_protein:\n idx_protein = fea_dict_protein['atom_idx_group']\n pattern_protein = fea_dict_protein['pattern_idx']\n coor_protein = fea_dict_protein['pseudo_atom_coor']\n\n r_lp = coor_protein - coor_ligand\n dist_lp = np.linalg.norm(r_lp)\n# if dist_lp > self.cutoff:\n if dist_lp > pair_cutoff:\n continue\n\n interact_ij = dict()\n interact_ij['idx_ligand'] = idx_ligand\n interact_ij['idx_protein'] = idx_protein\n interact_ij['pattern_ligand'] = pattern_ligand\n interact_ij['pattern_protein'] = pattern_protein\n\n interact_ij['dist_lp'] = dist_lp\n interact_ij['chain_id'] = fea_dict_protein['chain_id']\n interact_ij['residue_name'] = fea_dict_protein['residue_name']\n interact_ij['residue_num'] = fea_dict_protein['residue_num']\n interact_ij['weight'] = fea_dict_protein['weight']\n\n if fea_ligand == 'HBD' and fea_protein == 'HBA':\n num_neighbor_atom = fea_dict_ligand['num_neighbor_atom']\n donor_hydrogen_list = fea_dict_ligand['h_atoms']\n if num_neighbor_atom <= 1:\n theta = 0\n interact_ij['theta'] = theta\n else:\n dist_ah = 100.0\n for donor_hydrogen in donor_hydrogen_list:\n hydrogen_coor0 = donor_hydrogen[1]\n dist_ah0 = np.linalg.norm(\n hydrogen_coor0 - coor_protein)\n if dist_ah0 < dist_ah:\n dist_ah = dist_ah0\n hydrogen_coor = hydrogen_coor0\n dist_dh = np.linalg.norm(\n hydrogen_coor - coor_ligand)\n theta = cal_angle_from_points(\n dist_lp, dist_dh, dist_ah)\n if theta < 0.6*np.pi:\n continue\n interact_ij['theta'] = theta\n\n elif fea_ligand == 'HBA' and fea_protein == 'HBD':\n num_neighbor_atom = fea_dict_protein['num_neighbor_atom']\n donor_hydrogen_list = fea_dict_protein['h_atoms']\n if num_neighbor_atom <= 1:\n theta = 0\n interact_ij['theta'] = theta\n else:\n dist_ah = 100.0\n for donor_hydrogen in donor_hydrogen_list:\n hydrogen_coor0 = donor_hydrogen[1]\n dist_ah0 = np.linalg.norm(\n hydrogen_coor0 - coor_ligand)\n if dist_ah0 < dist_ah:\n dist_ah = dist_ah0\n hydrogen_coor = hydrogen_coor0\n dist_dh = np.linalg.norm(\n hydrogen_coor - coor_protein)\n theta = cal_angle_from_points(\n dist_lp, dist_dh, dist_ah)\n if theta < 0.6*np.pi:\n continue\n interact_ij['theta'] = theta\n\n elif fea_ligand == 'Aromatic' and fea_protein == 'Cation':\n n_vector_ligand = fea_dict_ligand['v_n']\n n_vector_lp = r_lp/dist_lp\n theta = np.abs(cal_angle_from_vectors(\n n_vector_ligand, n_vector_lp))\n if theta > np.pi/2:\n theta = np.pi-theta\n if theta > 0.5*np.pi/2:\n continue\n interact_ij['theta'] = theta\n\n elif fea_ligand == 'Cation' and fea_protein == 'Aromatic':\n n_vector_protein = fea_dict_protein['v_n']\n n_vector_lp = r_lp/dist_lp\n theta = np.abs(cal_angle_from_vectors(\n n_vector_protein, n_vector_lp))\n if theta > np.pi/2:\n theta = np.pi-theta\n if theta > 0.5*np.pi/2:\n continue\n interact_ij['theta'] = theta\n\n elif fea_ligand == 'Aromatic' and fea_protein == 'Aromatic':\n n_vector_ligand = fea_dict_ligand['v_n']\n n_vector_protein = fea_dict_protein['v_n']\n n_vector_lp = r_lp/dist_lp\n theta = cal_angle_from_vectors(\n n_vector_ligand, n_vector_protein)\n if theta > np.pi/2:\n theta = np.pi-theta\n interact_ij['theta'] = theta\n\n alpha = np.abs(cal_angle_from_vectors(\n n_vector_ligand, n_vector_lp))\n# dist_v = dist_lp * np.cos(alpha)\n# dist_h = dist_lp * np.sin(alpha)\n# print(np.sqrt(dist_v*dist_v+dist_h*dist_h), dist_lp)\n# interact_ij['dist_v'] = dist_v\n# interact_ij['dist_h'] = dist_h\n if theta > 0.4*np.pi/2 and theta < 0.8*np.pi/2:\n continue\n interact_ij['alpha'] = alpha\n\n elif fea_ligand == 'MBA' and fea_protein == 'Metal':\n if pattern_ligand not in self.metal_interaction_cutoff:\n continue\n if pattern_protein not in self.metal_interaction_cutoff[pattern_ligand]:\n continue\n metal_cutoff = self.metal_interaction_cutoff[\n pattern_ligand][pattern_protein]\n if dist_lp > metal_cutoff:\n continue\n interaction[fea_ligand][fea_protein] += [interact_ij]\n\n if 'MBA' in interaction:\n if 'Metal' in interaction['MBA']:\n metal_interaction = interaction['MBA']['Metal']\n d_list = list()\n d_list = np.array([x['dist_lp'] for x in metal_interaction])\n idx_sorted = np.argsort(d_list)\n\n metal_interaction_new = list()\n batom_idx = list()\n for idx in idx_sorted:\n interact_ij = metal_interaction[idx]\n idx_ligand = interact_ij['idx_ligand'][0]\n# dist_lp = interact_ij['dist_lp']\n neighbor_atoms_idx = ligand_bond_dict[idx_ligand]\n neighbor_check = False\n for neighbor_atom_idx in neighbor_atoms_idx:\n\n if neighbor_atom_idx in batom_idx:\n neighbor_check = True\n if not neighbor_check:\n metal_interaction_new += [interact_ij]\n batom_idx += [idx_ligand]\n\n interaction['MBA']['Metal'] = metal_interaction_new\n\n return interaction\n\n def write_PF(self, PF_coor_dict, out_file, is_protein=False):\n \"\"\"\n write pharmacophoric feature\n input:\n PF_coor_dict: dict\n out_file: filename, str\n is_protein: bool\n \"\"\"\n\n if is_protein:\n feature_type_list = self.feature_type_list + ['Metal']\n else:\n feature_type_list = self.feature_type_list + ['MBA']\n fp = open(out_file, 'w')\n line_out = 'feature_type:atom_idx_group:pattern_idx:pseudo_atom_coor'\n line_out += ':atom_type:etc'\n if is_protein:\n line_out += ':chain_id:residue_name:residue_num:weight'\n line_out += '\\n'\n fp.write(line_out)\n model_idx_list = PF_coor_dict.keys()\n num_model = len(model_idx_list)\n for model_idx in model_idx_list:\n PF_coor = PF_coor_dict[model_idx]\n if num_model > 1:\n line_out = 'MODEL %d\\n' % (model_idx + 1)\n fp.write(line_out)\n for feature_type in feature_type_list:\n if feature_type not in PF_coor:\n continue\n fea_dict_list = PF_coor[feature_type]\n for fea_dict in fea_dict_list:\n line_out = '%s' % feature_type\n# line_out += ':%s' % (str(fea_dict['atom_idx_group']))\n idx_line = ''\n for atom_idx in fea_dict['atom_idx_group']:\n idx_line += '%d,' % atom_idx\n line_out += ':(%s)' % idx_line.strip(',')\n\n line_out += ':%s' % (fea_dict['pattern_idx'])\n coor = fea_dict['pseudo_atom_coor']\n line_out += ':(%.3f,%.3f,%.3f)' % (\n coor[0], coor[1], coor[2])\n line_out += ':%s' % (fea_dict['atom_type'])\n\n if 'h_atoms' in fea_dict:\n hatoms = fea_dict['h_atoms']\n hatom_line = ''\n if 'num_neighbor_atom' in fea_dict:\n num_neighbor_atom = fea_dict['num_neighbor_atom']\n hatom_line += '%d;' %num_neighbor_atom\n for hatom in hatoms:\n line_f = '%d=(%.3f,%.3f,%.3f);'\n hatom_line += line_f % (hatom[0], hatom[1][0],\n hatom[1][1], hatom[1][2])\n line_out += ':%s' % hatom_line.strip(';')\n\n elif 'v_n' in fea_dict:\n coor_v_n = fea_dict['v_n']\n line_out += ':(%.3f,%.3f,%.3f)' % (\n coor_v_n[0], coor_v_n[1], coor_v_n[2])\n\n else:\n line_out += ':'\n\n if is_protein:\n line_out += ':%s' % (fea_dict['chain_id'])\n line_out += ':%s' % (fea_dict['residue_name'])\n line_out += ':%d' % (fea_dict['residue_num'])\n line_out += ':%.3f' % (fea_dict['weight'])\n\n line_out += '\\n'\n fp.write(line_out)\n fp.close()\n\n def read_PF(self, feature_file, is_protein=False):\n PF_coor_dict = dict()\n fp = open(feature_file)\n lines = fp.readlines()\n fp.close()\n\n model_idx = 0\n PF_coor_dict[model_idx] = dict()\n\n for line in lines:\n if line.startswith('feature_type'):\n # title = line.strip().split(':')\n continue\n\n if line.startswith('MODEL'):\n model_idx = int(line.strip().split()[1]) - 1\n fea_dict = dict()\n if model_idx not in PF_coor_dict:\n PF_coor_dict[model_idx] = dict()\n continue\n lis = line.strip().split(':')\n if len(lis) < 1:\n continue\n fea_dict = dict()\n feature_type = lis[0]\n atom_idx_group = lis[1]\n pattern_idx = lis[2]\n pseudo_atom_coor = lis[3]\n atom_type = lis[4]\n etc = lis[5]\n if feature_type not in PF_coor_dict[model_idx]:\n PF_coor_dict[model_idx][feature_type] = list()\n\n fea_dict['feature_type'] = feature_type\n aline = atom_idx_group.lstrip('(').rstrip(')')\n fea_dict['atom_idx_group'] = np.array(aline.split(','), dtype=int)\n fea_dict['pattern_idx'] = int(pattern_idx)\n coor = pseudo_atom_coor.lstrip('(').rstrip(')').split(',')\n fea_dict['pseudo_atom_coor'] = np.array(coor, dtype=np.float32)\n fea_dict['atom_type'] = atom_type\n if feature_type == 'HBD':\n hline_list = etc.split(';')\n h_list = list()\n num_neighbor_atom = float(hline_list[0])\n fea_dict['num_neighbor_atom'] = num_neighbor_atom\n for hline in hline_list[1:]:\n aa = hline.split('=')\n h_idx = int(aa[0])\n h_coor = aa[1].lstrip('(').rstrip(')').split(',')\n h_list += [[h_idx, np.array(h_coor, dtype=np.float32)]]\n fea_dict['h_atoms'] = h_list\n if feature_type == 'Aromatic':\n v_n = etc.lstrip('(').rstrip(')').split(',')\n fea_dict['v_n'] = np.array(v_n, dtype=np.float32)\n if is_protein:\n chain_id = lis[6]\n residue_name = lis[7]\n residue_num = lis[8]\n fea_dict['chain_id'] = chain_id\n fea_dict['residue_name'] = residue_name\n fea_dict['residue_num'] = int(residue_num)\n if len(lis) >= 10:\n weight = lis[9]\n fea_dict['weight'] = float(weight)\n else:\n fea_dict['weight'] = 1.0\n\n PF_coor_dict[model_idx][feature_type] += [fea_dict]\n\n return PF_coor_dict\n\n def write_interaction(self, interaction_dict, out_file):\n \"\"\"\n write pharmacophoric interaction\n input:\n interaction_dict: dict()\n out_file: str\n \"\"\"\n fp = open(out_file, 'w')\n line_out = 'feature_type_ligand:feature_type_protein'\n line_out += ':atom_idx_group_ligand:atom_idx_group_protein'\n line_out += ':pattern_ligand:pattern_protein'\n line_out += ':chain_id:residue_name:residue_num'\n line_out += ':dist_lp:theta:alpha:weight\\n'\n fp.write(line_out)\n\n model_idx_list = interaction_dict.keys()\n num_model = len(model_idx_list)\n for model_idx in model_idx_list:\n interaction = interaction_dict[model_idx]\n if num_model > 1:\n line_out = 'MODEL %d\\n' % (model_idx + 1)\n fp.write(line_out)\n\n for feature_type_ligand in interaction.keys():\n inter_i = interaction[feature_type_ligand]\n for feature_type_protein in inter_i.keys():\n inter_ij_list = inter_i[feature_type_protein]\n for inter_ij in inter_ij_list:\n line_out = '%s' % feature_type_ligand\n line_out += ':%s' % feature_type_protein\n\n idx_line = ''\n for idx in inter_ij['idx_ligand']:\n idx_line += '%d,' % (idx)\n line_out += ':(%s)' % (idx_line.strip(','))\n\n idx_line = ''\n for idx in inter_ij['idx_protein']:\n idx_line += '%d,' % (idx)\n line_out += ':(%s)' % (idx_line.strip(','))\n line_out += ':%s' % (inter_ij['pattern_ligand'])\n line_out += ':%s' % (inter_ij['pattern_protein'])\n\n line_out += ':%s' % (inter_ij['chain_id'])\n line_out += ':%s' % (inter_ij['residue_name'])\n line_out += ':%d' % (inter_ij['residue_num'])\n line_out += ':%.3f' % (inter_ij['dist_lp'])\n if 'theta' in inter_ij:\n line_out += ':%.3f' % (inter_ij['theta'])\n else:\n line_out += ':'\n if 'alpha' in inter_ij:\n line_out += ':%.3f' % (inter_ij['alpha'])\n else:\n line_out += ':'\n line_out += ':%.3f' % (inter_ij['weight'])\n\n line_out += '\\n'\n fp.write(line_out)\n\n fp.close()\n\n def count_interaction_receptor(self, interaction_dict):\n\n total_rec_pf_dict = dict()\n model_idx_list = interaction_dict.keys()\n feature_type_list_receptor = self.feature_type_list + ['Metal']\n feature_type_list_ligand = self.feature_type_list + ['MBA']\n\n for model_idx in model_idx_list:\n line_out_title = 'Model_idx'\n interaction = interaction_dict[model_idx]\n\n rec_pf_dict = dict()\n for feature_type_ligand in feature_type_list_ligand:\n line_out_title += ' %s' % (feature_type_ligand)\n if feature_type_ligand not in interaction:\n continue\n inter_i = interaction[feature_type_ligand]\n for feature_type_protein in feature_type_list_receptor:\n if feature_type_protein not in rec_pf_dict:\n rec_pf_dict[feature_type_protein] = dict()\n if feature_type_protein not in inter_i.keys():\n continue\n inter_ij_list = inter_i[feature_type_protein]\n for inter_ij in inter_ij_list:\n idx_protein = inter_ij['idx_protein']\n if idx_protein not in rec_pf_dict[feature_type_protein]:\n rec_pf_dict[feature_type_protein][idx_protein] = 0\n rec_pf_dict[feature_type_protein][idx_protein] += 1\n total_rec_pf_dict[model_idx] = rec_pf_dict\n\n return total_rec_pf_dict\n\n def print_interaction_receptor(self, total_rec_pf_dict):\n line_out_total = ''\n model_idx_list = total_rec_pf_dict.keys()\n feature_type_list_receptor = self.feature_type_list + ['Metal']\n\n line_out_title = 'Model_idx'\n for feature_type_receptor in feature_type_list_receptor:\n line_out_title += ' %s' % (feature_type_receptor)\n line_out_total += line_out_title + '\\n'\n\n for model_idx in model_idx_list:\n line_out_value = '%d' % (model_idx + 1)\n rec_pf_dict = total_rec_pf_dict[model_idx]\n for feature_type_protein in feature_type_list_receptor:\n if feature_type_protein in rec_pf_dict:\n count = len(rec_pf_dict[feature_type_protein].keys())\n else:\n count = 0\n line_out_value += ' %d' % (count)\n line_out_total += line_out_value + '\\n'\n\n return line_out_total\n\n def count_interaction_ligand(self, interaction_dict):\n total_lig_pf_dict = dict()\n model_idx_list = interaction_dict.keys()\n feature_type_list = self.feature_type_list + ['MBA']\n\n for model_idx in model_idx_list:\n interaction = interaction_dict[model_idx]\n lig_pf_dict = dict()\n for feature_type_ligand in feature_type_list:\n if feature_type_ligand not in interaction:\n continue\n inter_i = interaction[feature_type_ligand]\n lig_pf_dict[feature_type_ligand] = dict()\n for feature_type_protein in inter_i.keys():\n inter_ij_list = inter_i[feature_type_protein]\n for inter_ij in inter_ij_list:\n idx_ligand = inter_ij['idx_ligand']\n if idx_ligand not in lig_pf_dict[feature_type_ligand]:\n lig_pf_dict[feature_type_ligand][idx_ligand] = 0\n lig_pf_dict[feature_type_ligand][idx_ligand] += 1\n total_lig_pf_dict[model_idx] = lig_pf_dict\n\n return total_lig_pf_dict\n\n def print_interaction_ligand(self, total_lig_pf_dict):\n line_out_total = ''\n model_idx_list = total_lig_pf_dict.keys()\n feature_type_list = self.feature_type_list + ['MBA']\n\n line_out_title = 'Model_idx'\n for feature_type_ligand in feature_type_list:\n line_out_title += ' %s' % (feature_type_ligand)\n line_out_total += line_out_title + '\\n'\n\n for model_idx in model_idx_list:\n line_out_value = '%d' % (model_idx + 1)\n lig_pf_dict = total_lig_pf_dict[model_idx]\n for feature_type_ligand in feature_type_list:\n if feature_type_ligand in lig_pf_dict:\n count = len(lig_pf_dict[feature_type_ligand].keys())\n else:\n count = 0\n line_out_value += ' %d' % (count)\n line_out_total += line_out_value + '\\n'\n\n return line_out_total\n\n def count_interaction(self, interaction_dict, use_weight_pis=True,\n include_hydrophobic=True):\n \"\"\"\n input:\n interaction_dict: dict()\n output:\n total_count_dict: dict()\n \"\"\"\n\n total_count_dict = dict()\n\n feature_type_list = self.feature_type_list + ['MBA']\n model_idx_list = interaction_dict.keys()\n for model_idx in model_idx_list:\n interaction = interaction_dict[model_idx]\n count_dict = dict()\n w_count_dict = dict()\n for feature_type_ligand in feature_type_list:\n cfea_list = self.complementary_feature[feature_type_ligand]\n for cfea in cfea_list:\n feature_type_protein = cfea[0]\n\n key = '%s:%s' % (feature_type_ligand, feature_type_protein)\n if key not in count_dict:\n count_dict[key] = 0\n w_count_dict[key] = 0\n if feature_type_ligand not in interaction:\n continue\n inter_i = interaction[feature_type_ligand]\n if feature_type_protein not in inter_i:\n continue\n if ((not include_hydrophobic)\n and feature_type_protein == 'Hydrophobic'):\n continue\n\n inter_ij_list = inter_i[feature_type_protein]\n for inter_ij in inter_ij_list:\n count_dict[key] += 1\n weight = inter_ij['weight']\n w_count_dict[key] += weight\n\n score = 0\n for key in self.interaction_feature:\n if use_weight_pis:\n score += w_count_dict[key]*self.weight_pis[key]\n else:\n score += w_count_dict[key]\n if use_weight_pis:\n score += self.bias_pis\n\n count_dict['Score'] = score\n\n total_count_dict[model_idx] = count_dict\n\n return total_count_dict\n\n def print_interaction(self, total_count_dict, total_count_info_dict,\n use_pinfo, print_option=1):\n \"\"\"\n input:\n total_count_dict: from count_interaction\n print_option:\n if 1, print interction in one line for one model.\n if 2, print interaction in multi lines.\n output:\n line_out_total: str\n \"\"\"\n\n line_out_total = ''\n\n model_idx_list = total_count_dict.keys()\n num_model = len(model_idx_list)\n if print_option == 1:\n line_out_title = 'Model_idx PIscore'\n if use_pinfo:\n line_out_title += ' Pinfo'\n for key in self.interaction_feature:\n line_out_title += ' %s' % (key)\n line_out_total += line_out_title + '\\n'\n\n for model_idx in model_idx_list:\n count_dict = total_count_dict[model_idx]\n if num_model > 1 and print_option == 2:\n line_out = 'MODEL %d' % (model_idx + 1)\n line_out_total += line_out + '\\n'\n if print_option == 1:\n line_out_value = '%d' % (model_idx + 1)\n line_out_value += ' %.4f' % (count_dict['Score'])\n if use_pinfo:\n count_info_dict = total_count_info_dict[model_idx]\n line_out_value += ' %.4f' % (count_info_dict['Score'])\n\n for key in self.interaction_feature:\n count = count_dict[key]\n if print_option == 1:\n line_out_value += ' %d' % (count)\n\n if count > 0 and print_option == 2:\n line_out = '%s %d\\n' % (key, count)\n line_out_total += line_out\n\n if print_option == 2:\n line_out = 'PIscore: %.4f\\n' % (count_dict['Score'])\n if use_pinfo:\n count_info_dict = total_count_info_dict[model_idx]\n line_out += 'Pinfo %.4f\\n' % (count_info_dict['Score'])\n\n line_out_total += line_out\n\n if print_option == 1:\n line_out_total += line_out_value + '\\n'\n\n return line_out_total\n\n def read_dock_config(self, dock_config):\n fp = open(dock_config)\n lines = fp.readlines()\n fp.close()\n\n for line in lines:\n lis = line.strip().split('=')\n if lis[0] == 'center_x':\n center_x = float(lis[1])\n elif lis[0] == 'center_y':\n center_y = float(lis[1])\n elif lis[0] == 'center_z':\n center_z = float(lis[1])\n elif lis[0] == 'size_x':\n size_x = float(lis[1])\n elif lis[0] == 'size_y':\n size_y = float(lis[1])\n elif lis[0] == 'size_z':\n size_z = float(lis[1])\n\n center = np.array((center_x, center_y, center_z), dtype=float)\n size = np.array((size_x, size_y, size_z), dtype=float)\n return center, size\n\n def cal_piscore(self, ligand_file, pf_ligand_file, interaction_file):\n\n ms = list(pybel.readfile('pdb', ligand_file))\n num_model = len(ms)\n if num_model > 1:\n num_model = num_model - 1\n if num_model < 1:\n return None\n\n m_ligand = ms[0]\n\n PF_coor_ligand_dict = dict()\n interaction_dict = dict()\n if self.use_pinfo:\n interaction_info_dict = dict()\n ligand_bond_dict = self.get_bond_info(m_ligand)\n PF_dict_ligand = self.find_PF(m_ligand, ligand_bond_dict)\n for model_idx in range(num_model):\n m_ligand = ms[model_idx]\n PF_coor_ligand = self.find_PF_coor(m_ligand, PF_dict_ligand, ligand_bond_dict)\n mba_coor = self.find_mba(m_ligand, is_protein=False)\n PF_coor_ligand['MBA'] = mba_coor\n PF_coor_ligand_dict[model_idx] = PF_coor_ligand\n interaction = self.find_interaction(self.PF_coor_protein,\n PF_coor_ligand,\n ligand_bond_dict)\n\n interaction_dict[model_idx] = interaction\n if self.use_pinfo:\n interaction_info = self.find_interaction(self.PF_coor_info,\n PF_coor_ligand,\n ligand_bond_dict)\n interaction_info_dict[model_idx] = interaction_info\n\n if pf_ligand_file is not None:\n self.write_PF(PF_coor_ligand_dict, pf_ligand_file)\n\n if interaction_file is not None:\n self.write_interaction(interaction_dict, interaction_file)\n\n total_count_dict = self.count_interaction(interaction_dict,\n use_weight_pis=True,\n include_hydrophobic=True)\n if self.use_pinfo:\n total_count_info_dict = self.count_interaction(\n interaction_info_dict,\n use_weight_pis=False,\n include_hydrophobic=True)\n else:\n total_count_info_dict = None\n return total_count_dict, total_count_info_dict\n\n\ndef set_pifinder(args):\n\n piscore_receptor = args.piscore_receptor\n pf_receptor = args.pf_receptor\n pinfo_ligand = args.pinfo_ligand\n pf_receptor_info = args.pf_receptor_info\n pi_cutoff = args.pi_cutoff\n include_hydrophobic = args.include_hydrophobic\n dock_config = args.dock_config\n\n params = dict()\n weight_pis = {\n 'HBD:HBA': 0.129,\n 'HBA:HBD': 0.129,\n 'Anion:Cation': 0.31,\n 'Cation:Anion': 0.31,\n 'Cation:Aromatic': 0.039,\n 'Hydrophobic:Hydrophobic': 0.00585,\n 'Aromatic:Cation': 0.039,\n 'Aromatic:Aromatic': 0.064,\n 'MBA:Metal': 1.0\n }\n params['weight_pis'] = weight_pis\n params['bias_pis'] = 4.0\n params['cutoff'] = pi_cutoff\n if dock_config is not None:\n params['dock_config'] = dock_config\n params['include_hydrophobic'] = include_hydrophobic\n params['piscore_receptor'] = piscore_receptor\n params['pf_receptor'] = pf_receptor\n params['pinfo_ligand'] = pinfo_ligand\n params['pf_receptor_info'] = pf_receptor_info\n\n pharma = Pharmacophore(params)\n\n return pharma\n\n\ndef main():\n\n import sys\n import argparse\n title_line = 'Fixer for ligand pdb which is converted from pdbqt'\n parser = argparse.ArgumentParser(description=title_line)\n parser.add_argument('-r', '--piscore_receptor', required=False,\n default=None,\n help='input receptor pdb file')\n parser.add_argument('-p', '--pf_receptor', required=False,\n default=None,\n help='output for pharmacophoric feature of receptor')\n parser.add_argument('-t', '--pinfo_ligand', required=False,\n default=None, help='pinfo_ligand')\n parser.add_argument('-u', '--pf_receptor_info', required=False,\n default=None,\n help='output for template feature of receptor')\n parser.add_argument('-v', '--dock_config', type=str, required=False,\n default=None, help='dock_config_file')\n parser.add_argument('-m', '--pi_cutoff', type=float, required=False,\n default=6.5,\n help='pharmacophoric interaction cutoff distance')\n parser.add_argument('-l', '--ligand_file', required=True,\n help='input ligand pdb file')\n parser.add_argument('-q', '--pf_ligand_file', required=False,\n default=None,\n help='write pharmacophoric feature of ligand')\n parser.add_argument('--include_hydrophobic', action='store_true',\n required=False,\n help='include hydrophobic feature for template')\n parser.add_argument('-i', '--interaction_file', required=False,\n default=None, help='write interaction')\n parser.add_argument('--print_option', type=int, required=False, default=0,\n help='print_option 0:None, 1: one_line, 2: multi_line')\n\n# draw_ligand = False\n args = parser.parse_args()\n if args.piscore_receptor is None and args.pf_receptor is None:\n parser.print_usage()\n print('error piscore_receptor and pf_receptor are None')\n sys.exit()\n\n pharma = set_pifinder(args)\n use_pinfo = pharma.use_pinfo\n\n ligand_file = args.ligand_file\n pf_ligand_file = args.pf_ligand_file\n interaction_file = args.interaction_file\n print_option = args.print_option\n\n result = pharma.cal_piscore(ligand_file, pf_ligand_file, interaction_file)\n total_count_dict, total_count_info_dict = result\n\n# if draw_ligand:\n# size = (200, 200)\n# fig_dir = 'fig'\n# output_name = fig_dir + '/%s.png' % (ligand_file[:-3])\n# m_rdkit_ligand = Chem.MolFromPDBFile(ligand_file, removeHs=True)\n# pharma.draw_ligand(m_rdkit_ligand, PF_dict_ligand, output_name, size)\n\n if print_option > 0:\n lines_count = pharma.print_interaction(total_count_dict,\n total_count_info_dict,\n use_pinfo,\n print_option=print_option)\n print(lines_count.rstrip())\n\n\nif __name__ == '__main__':\n main()\n", "meta": {"hexsha": "201967f4c3d5de52cd204a0e2e45a4acceec0486", "size": 58230, "ext": "py", "lang": "Python", "max_stars_repo_path": "pifinder/pifinder.py", "max_stars_repo_name": "gicsaw/PIFinder", "max_stars_repo_head_hexsha": "fe1dd1a04e9380522e4d201afffd79f7b947f3a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pifinder/pifinder.py", "max_issues_repo_name": "gicsaw/PIFinder", "max_issues_repo_head_hexsha": "fe1dd1a04e9380522e4d201afffd79f7b947f3a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pifinder/pifinder.py", "max_forks_repo_name": "gicsaw/PIFinder", "max_forks_repo_head_hexsha": "fe1dd1a04e9380522e4d201afffd79f7b947f3a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1228813559, "max_line_length": 100, "alphanum_fraction": 0.5093250902, "include": true, "reason": "import numpy", "num_tokens": 13410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.15405755492358, "lm_q1q2_score": 0.08063685915437716}} {"text": "![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true)\n\n\"Open\n\nfrom IPython.display import HTML\nhide_me = ''\nHTML('''\n
    ''')\n\nhide_me\n\nfrom ipywidgets import interact\nimport ipywidgets as widgets\nimport IPython\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nimport plotly as py\nimport plotly.graph_objs as go\n\nimport pylab\n\nfrom IPython.display import Image, HTML, YouTubeVideo\n\n# Data Representation in Graphs\n\n### Grade 8 curriculum\n\nData plays an ever-increasing role in our lives. Like it or not, we are faced with numerical information every day, and we use it to make decisions. Should I be glad that 9 out of 10 dentists recommend my toothpaste? What about the 10th? A new study says that going for a run at 5 a.m. every morning reduces my risk of catching some terrible disease by 15%. Is it worth getting out of bed?\n\nIt's often hard to find meaning in data if it's just a bunch of numbers on a page, so we make that easier by using graphs. Graphs take data and turn them into pictures—bars, lines, circles, and more. But not all graphs are created equal; some do their jobs better than others. A good graph is a perfect tool for understanding a problem. A bad graph can be confusing, or in some cases, intentionally misleading.\n\nGraphs are used every day by news media, politicians, and scientists to convey information. Some use them well; some do not. In this notebook, we'll explore good and bad examples of graphs. By working through the examples and exercises in this notebook, you'll learn:\n\n- how to decide which type of graph is best for a given set of data;\n- how to identify flawed or misleading graphs;\n- how some of those flaws can be corrected; and\n- most importantly, how to read a graph and apply its meaning to your everyday life.\n\n\n*Many of the examples of bad graphs you'll find below are from the media (and one source in particular). This notebook isn't trying to criticize these sources. They just happen to have given us a lot of examples to choose from.*\n\n## What makes a good graph?\n\nFirst and most importantly, a graph should allow a reader, at a glance, to understand the information it's meant to convey. A good graph is like a good movie scene; if it's set up well, you can tell exactly what you're supposed to know. Some basic parts of a successful graph are:\n\n1. A title\n2. Proper labels\n3. Axes that start at zero (if numerical)\n4. Percentages that add to 100%\n5. Easy to read\n6. Use of colours, *as long as they are meaningful* and not just for show\n\n*By the way: **axes** (ACK-sees) are the reference lines on a graph. They're where you find the names of the categories (usually at the bottom) and the number scale (usually on the left). One of these lines is called an **axis** (ACK-sis).*\n\nFor a quick overview of different types of graphs and simple examples, you might find this \n[Math Is Fun](https://www.mathsisfun.com/data/pictographs.html) article useful. We'll look at some of these kinds of graphs below. You'll notice many of them are eye-catching, and they also convey information really well.\n\nOne of the places you'll find a lot of graphs is in political coverage. The media (and many of their readers/viewers) love a good \"horse race\". For example, this [CBC federal poll tracking article](http://www.cbc.ca/news/politics/poll-tracker-federal-poll-averages-and-seat-projections-1.4171977) uses almost every type of graph you'll find in this notebook.\n\nWe'll also explore how a graph can be used to [mislead someone](http://teachersinstitute.yale.edu/curriculum/units/2008/6/08.06.06.x.html). We hope this notebook will help you learn how to avoid using misleading graphs, as well as how to avoid being misled yourself.\n\nThere's even a [wall of shame](http://bcuchta.com/wall_of_shame/) with some of the worst graphs and charts!\n\n## Let's look at bar graphs\n\n### What is a bar graph?\n\nA bar graph is a graph where data is separated into categories, and those categories are shown as bars with different heights. It's a very useful graph, but it can also easily be misleading.\n\n![picture](./images/bar-graph-fruit.svg)\n\nfrom [Math is Fun](https://mathsisfun.com/data/images/bar-graph-fruit.svg)\n\n### When are bar graphs good to use?\n\nBar graphs can be used in many ways, but they usually show one piece of information collected from many groups or categories. For example, they might show the number of hours worked by people in different age groups, or how many grey shirts each girl in a class owns.\n\n### What are some ways to misuse bar graphs?\n\n1. **Make the scale on the graph start above zero.** This makes small differences between bars look much bigger than they really are.\n2. **Change the width of the bars to make one category look more important.** This gives one bar more area, which looks like more data.\n3. **Remove the space between the bars** (that's a **histogram**). Histograms are used for a different kind of data set, and so they are read in a different way.\n\nHere's an example of a poorly made bar graph. It shows the total welfare (support money) received by people in the US from 2009 to 2011. Each year is divided into 4 three-month pieces called **quarters**.\n\n![picture](./images/fnc-an-20120809-welfarechart.jpg)\n\nfrom [MediaMatters](https://www.mediamatters.org/fox-news/today-dishonest-fox-charts-government-aid-edition)\n\nWhat makes this a bad bar graph?\n1. Their scale starts at 94 million insead of 0.\n2. The bars are in 3D, making their values harder to read.\n3. Their y-axis has 8 labels, but there are 10 levels on the graph (including the top and bottom).\n\nWhoever made this graph probably wanted the viewer to think welfare in the US is rising faster than it really is. Now, let's ask ourselves:\n\n- What can we change to make this a good graph?\n- How does it look after we make these changes?\n- Why might the original creators not want to use our new graph?\n\nOne way we can improve this graph is by changing where its scale starts. Play with the slider below to see how the graph looks with different scales.\n\n*Slide the slider below to change the starting point of the $y$-axis. The initial position corresponds to the graph in the image above. As you move the slider to the left, the starting point for the $y$-axis is reduced to zero.*\n\n*Warning: This graph is slow to respond, please be patient with it.*\n\nhide_me\n\ncolumns = ['09-Q1', '09-Q2', '09-Q3', '09-Q4', '10-Q1', '10-Q2','10-Q3', '10-Q4', '11-Q1', '11-Q2']\n#fig, ax = plt.subplots()\ndef plot(yaxis=94):\n y = [97, 98, 99, 101, 104, 105, 106, 107, 107.5, 108]\n x = np.arange(len(y))\n fig, ax = plt.subplots(figsize=(10,4))\n ax.bar(x, y, width=0.5)\n ax.set_xticks(x)\n ax.set_xticklabels(columns)\n ax.set_ylim((yaxis,110))\n ax.set_title(\"Federal Welfare Received in the US\")\n \ninteract(plot, yaxis=(0,90), continuous_update = True, wait = False)\n#plt.show()\n\n## Let's look at pictographs\n\n### What is a pictograph?\n\nA pictograph is a way to show data using images, where each image represents a certain number of things that are being measured. They look a lot like bar graphs and they can be horizontal or vertical too.\n\n![picture](./images/pictograph-tennis.svg)\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/pictograph-tennis.svg)\n\n### Why do people like to use pictographs?\n\nThe main reason is because the pictures offer something for readers to connect with other than just a row of coloured bars.\n\nAlso, pictographs often work best to show data with small numbers. If everything can be easily expressed with a simple scale like the one above, then a pictograph might be the right choice to represent the data.\n\n### When are pictographs not a good choice?\n\nIn the example above, what if Sam played 46 games instead of 45? This pictogram counts games in steps of 5, so numbers in between these steps might be hard or impossible to show.\n\nA reader might also make a connection with a pictograph that wasn't intended. Let's show this with an example.\n\nOn Halloween, Shayna and Michael went trick-or-treating. Shayna got 18 pieces of candy, and Michael got 36. Their totals are shown in this pictograph:\n\n![picture](./images/halloween-candy-collected.jpg)\n\nfrom [teachersinstitute.yale.edu](http://teachersinstitute.yale.edu/curriculum/units/2008/6/08.06.06.x.html)\n\nAt first, is looks like a fine way to show how much candy each child got. The heights of the candy corn pieces are being used to mark the two amounts. But as a viewer, we don't see just the height—we also see the width. Not only is the second candy corn twice as high, it's also twice as wide, giving it four times the area as the first candy corn. This makes it *look like* Michael got 4 times as much candy as Shayna, even though he only got twice as much.\n\nClick the \"Display\" button below to show a better, more accurate way to represent the same data:\n\nhide_me\n\npic = Image('images/CandyCornGraph.png')\nclicker = widgets.Checkbox(value=False, description='Display', disabled=False)\n\ndef checking(a):\n if clicker.value == True:\n IPython.display.display(pic)\n else:\n IPython.display.clear_output()\n IPython.display.display(clicker)\n\nIPython.display.display(clicker)\nclicker.observe(checking, 'value')\n\n## Let's look at line graphs\n\n### What is a line graph?\n\nA line graph is a way to show how the measurement of one value responds to changes in another, like how something may change over time. In fact, time is one of the most common variables with a line graph.\n\n![picture](./images/line-graph-example.svg)\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/line-graph-example.svg)\n\n### Why are line graphs useful?\n\nThey show a moving trend with a line that's easy to follow, instead of just dots on a graph. They work best when the trend involves the change of one variable (jobs, temperature, debt) with respect to another (usually time).\n\nIn some cases it can also be useful to plot multiple lines on one graph, usually with different colours to help tell them apart. For example, one might plot polling results for different political parties over time, as with this graph from the CBC:\n\n![federal polling averages](./images/poll-averages.jpg)\n\nfrom [cbc.ca](http://www.cbc.ca/polopoly_fs/1.3265490!/fileImage/httpImage/image.jpg)\n\n\n### How can line graphs go wrong?\n\nA common error with line graphs is unlabelled axes. A graph might show a line that slopes upwards, but without labels, we wouldn't know what is growing or how fast. Also, line graphs can trick us into thinking a trend is linear by spacing out the ticks unevenly on one axis, so that the data points neatly line up. Like this example:\n\n![Picture](./images/job-loss-by-quarter.png)\n\nfrom [Online Stat Book](http://onlinestatbook.com/2/graphing_distributions/graphics/graph2.png)\n\nhide_me\n\nfix = widgets.SelectionSlider(options=['original', 'fixed'], value ='original', description='Slide to fix',\n continuous_update=True, orientation='horizontal',)\n\ndef fixing(a):\n if fix.value == 'fixed':\n IPython.display.clear_output()\n IPython.display.display(fix)\n f, ax1 = plt.subplots(1,1,figsize=(10,5))\n ax1.set_title(\"Job Loss by Quarter\")\n ax1.set_xlabel('Months from November 07',fontsize=15)\n ax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\n x1 = [1, 10, 16, 29]\n y1 = [7,9,13.5,15]\n ax1.plot(x1, y1,\"bo-\")\n plt.legend()\n plt.show()\n else:\n IPython.display.clear_output()\n IPython.display.display(fix)\n f, ax1 = plt.subplots(1,1,figsize=(10,5))\n ax1.set_title(\"Job Loss by Quarter\")\n ax1.set_xlabel('Months from November 07',fontsize=15)\n ax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\n x1 = [0,7,23,29]\n y1 = [7,9,13.5,15]\n ax1.plot(x1, y1,\"bo-\")\n plt.legend()\n plt.show()\n \nIPython.display.display(fix) \nfix.observe(fixing, 'value')\n\nIPython.display.clear_output()\nIPython.display.display(fix)\nf, ax1 = plt.subplots(1,1,figsize=(10,5))\nax1.set_title(\"Job Loss by Quarter\")\nax1.set_xlabel('Months from November 07',fontsize=15)\nax1.set_ylabel(\"Jobs Lost in Millions\",color='b',fontsize=15)\nx1 = [0,7,23,29]\ny1 = [7,9,13.5,15]\nax1.plot(x1, y1,\"bo-\")\nplt.legend()\nplt.show()\n\n## Let's look at circle graphs\n\n### What is a circle graph?\n\nAlso known as a pie chart, a circle graph is used to show how a total is split into different groups. The whole pie represents the total, and each slice of the pie represents a different group. Each slice gets as much of the pie as its group has of the total—the bigger the slice, the more of the total that group represents.\n\n![picture](./images/pie-chart-movies.svg)\n\nfrom [Math is Fun](https://www.mathsisfun.com/data/images/pie-chart-movies.svg)\n\n### Why are circle graphs useful?\n\nThey make it easy to compare group sizes; if there's a biggest or smallest group, that's easy to see, since group sizes are shown as pieces of a whole.\n\n### Why might people not use circle graphs?\n\nTo be displayed as a circle graph, data must be converted into percentages of the total, then into slices of a circle, which is more work than other graphs need. Plus, it's easy to mess up if the data are not converted properly (or at all). Circle graphs are also hard to draw accurately on paper, since you need a protractor to ensure your angles are correct. Some people might even say that any time a circle graph would do, a bar graph would do better, and that the pie chart below is the only acceptable one.\n\n![picture](./images/Pie-I-have-Eaten.jpg)\n\nfrom [Flowing Data](https://i1.wp.com/flowingdata.com/wp-content/uploads/2008/09/Pie-I-have-Eaten.jpg)\n\n********************\n\n### What's wrong with these graphs?\n\n![Picture](./images/unemployment-rate.jpg)\n\n[Business Insider](https://amp.businessinsider.com/images/51cb26c469beddf14c000015-750-453.jpg)\n\n![Picture](./images/candidates-pie.png)\n\n[Flowing Data](http://flowingdata.com/wp-content/uploads/yapb_cache/app15725951258947184.acq6gmp0hf4sowckg80ssc8wg.2xne1totli0w8s8k0o44cs0wc.th.png)\n\n![Picture](./images/130207SuperBowlPoll.jpg)\n\n[Flowing Data](https://i0.wp.com/flowingdata.com/wp-content/uploads/2013/03/130207SuperBowlPoll.jpg?fit=500%2C430&ssl=1)\n\n\n## What was wrong with these graphs?\n\n1. Mislabeled/Missing axes\n2. Plotted wrong\n3. Hard to read\n4. Numbers don't add to 100%\n5. Wrong data shown\n\nThe video below goes through several examples of bad/misleading graphs (some of them shown in this notebook) and why they are not good representations of the original data.\n\nhide_me\n\nYouTubeVideo('1F7gm_BG0iQ')\n\n*************\n\n## Practice Questions\n\n### Question 1\n\nA group of kids was asked **what they do first** when they get home from school. The data are shown in the table below. [Data source here](http://www.ur.umich.edu/9900/Apr03_00/7.htm)\n\n| Activity | Percent|\n|-----------------|-----|\n| Eat | 27% |\n| Personal Care | 19% |\n| Watch TV | 15% |\n| Study | 13% |\n| Play | 9% |\n| Other | 17% |\n\nhide_me\n\nanswer = widgets.RadioButtons(options=['','circle graph', 'line graph', 'bar graph', 'pictograph'],\n value='', description='Answer:')\nlabels = ['Eat', 'Personal Care', 'Watch TV', 'Study', 'Play', 'Other']\ndata = [0.27, 0.19, 0.15, 0.13, 0.09, 0.17]\n\ndef display():\n print('What would be the best graph to display this set of data?')\n IPython.display.display(answer)\n\ndef check(a):\n IPython.display.clear_output(wait=False)\n display()\n if answer.value == 'circle graph':\n print(\"Correct! Circle graphs are used for percentages.\")\n print(\"Let's see this data in a circle graph.\")\n patches, texts = plt.pie(data, labels=labels)\n plt.axis('equal')\n plt.tight_layout()\n plt.show()\n else:\n if answer.value == 'bar graph':\n print(\"A Bar graph would work, but there's a better option. Try again.\")\n else:\n if answer.value == 'line graph':\n print(\"Line graphs are good for change over time, not percentages. Try again.\")\n else:\n print(\"A pictograph would work if the data was in amounts instead of percentages. Try again.\")\n\ndisplay()\nanswer.observe(check, 'value')\n\n### Question 2\n\nA group of kids was asked **how much time** they spend doing different activities after school. The data are shown in the table below. [Data source here](http://www.ur.umich.edu/9900/Apr03_00/7.htm)\n\n| Activity | Time spent (minutes)|\n|-----------------|-----|\n| Reading | 30 |\n| Chores | 30 |\n| Watch TV | 100 |\n| Study | 60 |\n| Play | 74 |\n| Sports | 60 |\n\nhide_me\n\nanswer2 = widgets.RadioButtons(options=['','circle graph', 'line graph', 'bar graph', 'pictograph'],\n value='', description='Answer:')\nlabels2 = ['Reading', 'Chores', 'Watch TV', 'Study', 'Play', 'Sports']\ndata2 = [30, 30, 100, 60, 74, 60]\nx = np.arange(len(data2))\n\ndef display2():\n print('What would be the best graph to display this set of data?')\n IPython.display.display(answer2)\n\ndef check(a):\n IPython.display.clear_output(wait=False)\n display2()\n if answer2.value == 'circle graph':\n print(\"A circle graph is used for percentages. Try again.\")\n else:\n if answer2.value == 'bar graph':\n print(\"Correct! A bar graph shows the relation between both parameters in an easy to read format.\")\n print(\"Let's see what that looks like.\")\n plt.bar(x, data2, width = .3)\n plt.xticks(x, labels2)\n plt.ylabel('Time in Minutes')\n plt.title('Time Spent on Afterschool Activities')\n plt.show()\n else:\n if answer2.value == 'line graph':\n print(\"Line graphs are good for change over time. Try again.\")\n else:\n print(\"A pictograph would work, but there's a better option to be more accurate. Try again.\")\n\ndisplay2()\nanswer2.observe(check, 'value')\n\nNow that we have seen many examples of both good and bad graphs, let's look at [the worst graphs in science literature](https://www.biostat.wisc.edu/~kbroman/topten_worstgraphs/) and try to figure out why each graph is on the list.\n\n(You can click on a graph to make it bigger. See if you can point out the flaws in these graphs on your own, then click the \"Discussion\" links to learn what's wrong with each graph and why it made it to the list!)\n\n*Even top academic institutions sometimes produce images that, while they might look impressive, do very little to help us understand the numbers involved in an issue. Try to figure out what's wrong with these\n[infographics from Princeton](http://www.princeton.edu/~ina/infographics/index.html) on your own.*\n\n## What have we learned?\n\nIn this notebook, we have learned:\n\n* Graphs are great at conveying numerical information\n* Not all types of graphs are created equal\n* Graphs can be manipulated to be misleading\n* How to identify misleading parts of graphs \n* There are steps to create truthful graphs\n\nWith this knowledge, you are able to be more informed when you see any kind of data displayed in a graph. You are also able to create truthful graphs of your own. Keep trying to identify good and bad graphs in your every day life.\n\n[![Callysto.ca License](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-bottom.jpg?raw=true)](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)", "meta": {"hexsha": "3ec2b33745f0d083c39ad0e29c2eae94791bc2cf", "size": 20668, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.py", "max_stars_repo_name": "BryceHaley/curriculum-jbook", "max_stars_repo_head_hexsha": "d1246799ddfe62b0cf5c389394a18c2904383437", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-18T18:19:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:19:40.000Z", "max_issues_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.py", "max_issues_repo_name": "callysto/curriculum-jbook", "max_issues_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/curriculum-notebooks/Mathematics/DataRepresentation/data-representation.py", "max_forks_repo_name": "callysto/curriculum-jbook", "max_forks_repo_head_hexsha": "ffb685901e266b0ae91d1250bf63e05a87c456d9", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0797266515, "max_line_length": 512, "alphanum_fraction": 0.7155022257, "include": true, "reason": "import numpy", "num_tokens": 5169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.2309197576365038, "lm_q1q2_score": 0.08050905015246083}} {"text": "\"\"\"Module for compiling codegen output, and wrap the binary for use in\npython.\n\n.. note:: To use the autowrap module it must first be imported\n\n >>> from sympy.utilities.autowrap import autowrap\n\nThis module provides a common interface for different external backends, such\nas f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are\nimplemented) The goal is to provide access to compiled binaries of acceptable\nperformance with a one-button user interface, i.e.\n\n >>> from sympy.abc import x,y\n >>> expr = ((x - y)**(25)).expand()\n >>> binary_callable = autowrap(expr)\n >>> binary_callable(1, 2)\n -1.0\n\nThe callable returned from autowrap() is a binary python function, not a\nSymPy object. If it is desired to use the compiled function in symbolic\nexpressions, it is better to use binary_function() which returns a SymPy\nFunction object. The binary callable is attached as the _imp_ attribute and\ninvoked when a numerical evaluation is requested with evalf(), or with\nlambdify().\n\n >>> from sympy.utilities.autowrap import binary_function\n >>> f = binary_function('f', expr)\n >>> 2*f(x, y) + y\n y + 2*f(x, y)\n >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})\n 0.e-110\n\nThe idea is that a SymPy user will primarily be interested in working with\nmathematical expressions, and should not have to learn details about wrapping\ntools in order to evaluate expressions numerically, even if they are\ncomputationally expensive.\n\nWhen is this useful?\n\n 1) For computations on large arrays, Python iterations may be too slow,\n and depending on the mathematical expression, it may be difficult to\n exploit the advanced index operations provided by NumPy.\n\n 2) For *really* long expressions that will be called repeatedly, the\n compiled binary should be significantly faster than SymPy's .evalf()\n\n 3) If you are generating code with the codegen utility in order to use\n it in another project, the automatic python wrappers let you test the\n binaries immediately from within SymPy.\n\n 4) To create customized ufuncs for use with numpy arrays.\n See *ufuncify*.\n\nWhen is this module NOT the best approach?\n\n 1) If you are really concerned about speed or memory optimizations,\n you will probably get better results by working directly with the\n wrapper tools and the low level code. However, the files generated\n by this utility may provide a useful starting point and reference\n code. Temporary files will be left intact if you supply the keyword\n tempdir=\"path/to/files/\".\n\n 2) If the array computation can be handled easily by numpy, and you\n don't need the binaries for another project.\n\n\"\"\"\n\nfrom __future__ import print_function, division\n\n_doctest_depends_on = { 'exe': ('f2py', 'gfortran'), 'modules': ('numpy',)}\n\nimport sys\nimport os\nimport shutil\nimport tempfile\nfrom subprocess import STDOUT, CalledProcessError\n\nfrom sympy.core.compatibility import check_output\nfrom sympy.utilities.codegen import (\n get_code_generator, Routine, OutputArgument, InOutArgument,\n CodeGenArgumentListError, Result\n)\nfrom sympy.utilities.lambdify import implemented_function\nfrom sympy.utilities.decorator import doctest_depends_on\nfrom sympy import C\n\n\nclass CodeWrapError(Exception):\n pass\n\n\nclass CodeWrapper:\n \"\"\"Base Class for code wrappers\"\"\"\n _filename = \"wrapped_code\"\n _module_basename = \"wrapper_module\"\n _module_counter = 0\n\n @property\n def filename(self):\n return \"%s_%s\" % (self._filename, CodeWrapper._module_counter)\n\n @property\n def module_name(self):\n return \"%s_%s\" % (self._module_basename, CodeWrapper._module_counter)\n\n def __init__(self, generator, filepath=None, flags=[], verbose=False):\n \"\"\"\n generator -- the code generator to use\n \"\"\"\n self.generator = generator\n self.filepath = filepath\n self.flags = flags\n self.quiet = not verbose\n\n @property\n def include_header(self):\n return bool(self.filepath)\n\n @property\n def include_empty(self):\n return bool(self.filepath)\n\n def _generate_code(self, main_routine, routines):\n routines.append(main_routine)\n self.generator.write(\n routines, self.filename, True, self.include_header,\n self.include_empty)\n\n def wrap_code(self, routine, helpers=[]):\n\n workdir = self.filepath or tempfile.mkdtemp(\"_sympy_compile\")\n if not os.access(workdir, os.F_OK):\n os.mkdir(workdir)\n oldwork = os.getcwd()\n os.chdir(workdir)\n try:\n sys.path.append(workdir)\n self._generate_code(routine, helpers)\n self._prepare_files(routine)\n self._process_files(routine)\n mod = __import__(self.module_name)\n finally:\n sys.path.remove(workdir)\n CodeWrapper._module_counter += 1\n os.chdir(oldwork)\n if not self.filepath:\n shutil.rmtree(workdir)\n\n return self._get_wrapped_function(mod)\n\n def _process_files(self, routine):\n command = self.command\n command.extend(self.flags)\n try:\n retoutput = check_output(command, stderr=STDOUT)\n except CalledProcessError as e:\n raise CodeWrapError(\n \"Error while executing command: %s. Command output is:\\n%s\" % (\n \" \".join(command), e.output))\n if not self.quiet:\n print(retoutput)\n\n\nclass DummyWrapper(CodeWrapper):\n \"\"\"Class used for testing independent of backends \"\"\"\n\n template = \"\"\"# dummy module for testing of SymPy\ndef %(name)s():\n return \"%(expr)s\"\n%(name)s.args = \"%(args)s\"\n%(name)s.returns = \"%(retvals)s\"\n\"\"\"\n\n def _prepare_files(self, routine):\n return\n\n def _generate_code(self, routine, helpers):\n with open('%s.py' % self.module_name, 'w') as f:\n printed = \", \".join(\n [str(res.expr) for res in routine.result_variables])\n # convert OutputArguments to return value like f2py\n inargs = filter(lambda x: not isinstance(\n x, OutputArgument), routine.arguments)\n retvals = []\n for val in routine.result_variables:\n if isinstance(val, Result):\n retvals.append('nameless')\n else:\n retvals.append(val.result_var)\n\n print(DummyWrapper.template % {\n 'name': routine.name,\n 'expr': printed,\n 'args': \", \".join([str(arg.name) for arg in inargs]),\n 'retvals': \", \".join([str(val) for val in retvals])\n }, end=\"\", file=f)\n\n def _process_files(self, routine):\n return\n\n @classmethod\n def _get_wrapped_function(cls, mod):\n return mod.autofunc\n\n\nclass CythonCodeWrapper(CodeWrapper):\n \"\"\"Wrapper that uses Cython\"\"\"\n\n setup_template = \"\"\"\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\n\nsetup(\n cmdclass = {'build_ext': build_ext},\n ext_modules = [Extension(%(args)s)]\n )\n\"\"\"\n\n @property\n def command(self):\n command = [sys.executable, \"setup.py\", \"build_ext\", \"--inplace\"]\n return command\n\n def _prepare_files(self, routine):\n pyxfilename = self.module_name + '.pyx'\n codefilename = \"%s.%s\" % (self.filename, self.generator.code_extension)\n\n # pyx\n with open(pyxfilename, 'w') as f:\n self.dump_pyx([routine], f, self.filename,\n self.include_header, self.include_empty)\n\n # setup.py\n ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]\n with open('setup.py', 'w') as f:\n print(CythonCodeWrapper.setup_template % {\n 'args': \", \".join(ext_args)}, file=f)\n\n @classmethod\n def _get_wrapped_function(cls, mod):\n return mod.autofunc_c\n\n def dump_pyx(self, routines, f, prefix, header=True, empty=True):\n \"\"\"Write a Cython file with python wrappers\n\n This file contains all the definitions of the routines in c code and\n refers to the header file.\n\n :Arguments:\n\n routines\n List of Routine instances\n f\n File-like object to write the file to\n prefix\n The filename prefix, used to refer to the proper header file.\n Only the basename of the prefix is used.\n empty\n Optional. When True, empty lines are included to structure the\n source files. [DEFAULT=True]\n \"\"\"\n for routine in routines:\n prototype = self.generator.get_prototype(routine)\n\n # declare\n print('cdef extern from \"%s.h\":' % prefix, file=f)\n print(' %s' % prototype, file=f)\n if empty:\n print(file=f)\n\n # wrap\n ret, args_py = self._split_retvals_inargs(routine.arguments)\n args_c = \", \".join([str(a.name) for a in routine.arguments])\n print(\"def %s_c(%s):\" % (routine.name,\n \", \".join(self._declare_arg(arg) for arg in args_py)), file=f)\n for r in ret:\n if not r in args_py:\n print(\" cdef %s\" % self._declare_arg(r), file=f)\n rets = \", \".join([str(r.name) for r in ret])\n if routine.results:\n call = ' return %s(%s)' % (routine.name, args_c)\n if rets:\n print(call + ', ' + rets, file=f)\n else:\n print(call, file=f)\n else:\n print(' %s(%s)' % (routine.name, args_c), file=f)\n print(' return %s' % rets, file=f)\n\n if empty:\n print(file=f)\n dump_pyx.extension = \"pyx\"\n\n def _split_retvals_inargs(self, args):\n \"\"\"Determines arguments and return values for python wrapper\"\"\"\n py_args = []\n py_returns = []\n for arg in args:\n if isinstance(arg, OutputArgument):\n py_returns.append(arg)\n elif isinstance(arg, InOutArgument):\n py_returns.append(arg)\n py_args.append(arg)\n else:\n py_args.append(arg)\n return py_returns, py_args\n\n def _declare_arg(self, arg):\n t = arg.get_datatype('c')\n if arg.dimensions:\n return \"%s *%s\" % (t, str(arg.name))\n else:\n return \"%s %s\" % (t, str(arg.name))\n\n\nclass F2PyCodeWrapper(CodeWrapper):\n \"\"\"Wrapper that uses f2py\"\"\"\n\n @property\n def command(self):\n filename = self.filename + '.' + self.generator.code_extension\n command = [\"f2py\", \"-m\", self.module_name, \"-c\", filename]\n return command\n\n def _prepare_files(self, routine):\n pass\n\n @classmethod\n def _get_wrapped_function(cls, mod):\n return mod.autofunc\n\n\ndef _get_code_wrapper_class(backend):\n wrappers = { 'F2PY': F2PyCodeWrapper, 'CYTHON': CythonCodeWrapper,\n 'DUMMY': DummyWrapper}\n return wrappers[backend.upper()]\n\n\n@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))\ndef autowrap(\n expr, language='F95', backend='f2py', tempdir=None, args=None, flags=[],\n verbose=False, helpers=[]):\n \"\"\"Generates python callable binaries based on the math expression.\n\n expr\n The SymPy expression that should be wrapped as a binary routine\n\n :Optional arguments:\n\n language\n The programming language to use, currently 'C' or 'F95'\n backend\n The wrapper backend to use, currently f2py or Cython\n tempdir\n Path to directory for temporary files. If this argument is supplied,\n the generated code and the wrapper input files are left intact in the\n specified path.\n args\n Sequence of the formal parameters of the generated code, if ommited the\n function signature is determined by the code generator.\n flags\n Additional option flags that will be passed to the backend\n verbose\n If True, autowrap will not mute the command line backends. This can be\n helpful for debugging.\n helpers\n Used to define auxillary expressions needed for the main expr. If the\n main expression need to do call a specialized function it should be put\n in the ``helpers`` list. Autowrap will then make sure that the compiled\n main expression can link to the helper routine. Items should be tuples\n with (, , ). It is\n mandatory to supply an argument sequence to helper routines.\n\n >>> from sympy.abc import x, y, z\n >>> from sympy.utilities.autowrap import autowrap\n >>> expr = ((x - y + z)**(13)).expand()\n >>> binary_func = autowrap(expr)\n >>> binary_func(1, 4, 2)\n -1.0\n\n \"\"\"\n\n code_generator = get_code_generator(language, \"autowrap\")\n CodeWrapperClass = _get_code_wrapper_class(backend)\n code_wrapper = CodeWrapperClass(code_generator, tempdir, flags, verbose)\n try:\n routine = Routine('autofunc', expr, args)\n except CodeGenArgumentListError as e:\n # if all missing arguments are for pure output, we simply attach them\n # at the end and try again, because the wrappers will silently convert\n # them to return values anyway.\n new_args = []\n for missing in e.missing_args:\n if not isinstance(missing, OutputArgument):\n raise\n new_args.append(missing.name)\n routine = Routine('autofunc', expr, args + new_args)\n\n helps = []\n for name, expr, args in helpers:\n helps.append(Routine(name, expr, args))\n\n return code_wrapper.wrap_code(routine, helpers=helps)\n\n\n@doctest_depends_on (exe=('f2py', 'gfortran'), modules=('numpy',))\ndef binary_function(symfunc, expr, **kwargs):\n \"\"\"Returns a sympy function with expr as binary implementation\n\n This is a convenience function that automates the steps needed to\n autowrap the SymPy expression and attaching it to a Function object\n with implemented_function().\n\n >>> from sympy.abc import x, y\n >>> from sympy.utilities.autowrap import binary_function\n >>> expr = ((x - y)**(25)).expand()\n >>> f = binary_function('f', expr)\n >>> type(f)\n \n >>> 2*f(x, y)\n 2*f(x, y)\n >>> f(x, y).evalf(2, subs={x: 1, y: 2})\n -1.0\n \"\"\"\n binary = autowrap(expr, **kwargs)\n return implemented_function(symfunc, binary)\n\n@doctest_depends_on (exe=('f2py', 'gfortran'), modules=('numpy',))\ndef ufuncify(args, expr, **kwargs):\n \"\"\"\n Generates a binary ufunc-like lambda function for numpy arrays\n\n ``args``\n Either a Symbol or a tuple of symbols. Specifies the argument sequence\n for the ufunc-like function.\n\n ``expr``\n A SymPy expression that defines the element wise operation\n\n ``kwargs``\n Optional keyword arguments are forwarded to autowrap().\n\n The returned function can only act on one array at a time, as only the\n first argument accept arrays as input.\n\n .. Note:: a *proper* numpy ufunc is required to support broadcasting, type\n casting and more. The function returned here, may not qualify for\n numpy's definition of a ufunc. That why we use the term ufunc-like.\n\n References\n ==========\n [1] http://docs.scipy.org/doc/numpy/reference/ufuncs.html\n\n Examples\n ========\n\n >>> from sympy.utilities.autowrap import ufuncify\n >>> from sympy.abc import x, y\n >>> import numpy as np\n >>> f = ufuncify([x, y], y + x**2)\n >>> f([1, 2, 3], 2)\n [ 3. 6. 11.]\n >>> a = f(np.arange(5), 3)\n >>> isinstance(a, np.ndarray)\n True\n >>> print a\n [ 3. 4. 7. 12. 19.]\n\n \"\"\"\n y = C.IndexedBase(C.Dummy('y'))\n x = C.IndexedBase(C.Dummy('x'))\n m = C.Dummy('m', integer=True)\n i = C.Dummy('i', integer=True)\n i = C.Idx(i, m)\n l = C.Lambda(args, expr)\n f = implemented_function('f', l)\n\n if isinstance(args, C.Symbol):\n args = [args]\n else:\n args = list(args)\n\n # first argument accepts an array\n args[0] = x[i]\n return autowrap(C.Equality(y[i], f(*args)), **kwargs)\n", "meta": {"hexsha": "6a47099c356afd3593e1d5d364c0b970357577ec", "size": 16352, "ext": "py", "lang": "Python", "max_stars_repo_path": "sympy/utilities/autowrap.py", "max_stars_repo_name": "lidavidm/sympy", "max_stars_repo_head_hexsha": "971aa94ee6d0774eacfb4aed6965195c4a59e104", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-03-12T02:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T02:52:16.000Z", "max_issues_repo_path": "sympy/utilities/autowrap.py", "max_issues_repo_name": "lidavidm/sympy", "max_issues_repo_head_hexsha": "971aa94ee6d0774eacfb4aed6965195c4a59e104", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sympy/utilities/autowrap.py", "max_forks_repo_name": "lidavidm/sympy", "max_forks_repo_head_hexsha": "971aa94ee6d0774eacfb4aed6965195c4a59e104", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5770020534, "max_line_length": 80, "alphanum_fraction": 0.624694227, "include": true, "reason": "import numpy,from sympy", "num_tokens": 3879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.17553807362342935, "lm_q1q2_score": 0.08024490125093564}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Visualização de dados com _seaborn_\n\n# No capítulo [Plotagem e formatação de gráficos](09-plotagem-matplot.ipynb), fizemos uma breve introdução à _visualização de dados_ e aprendemos a utilizar o _matplotlib_ para realizar plotagens básicas de gráficos. Neste capítulo, exploraremos a visualização de dados utilizando o módulo _seaborn_. \n# \n# O _seaborn_ estende as potencialidades do _matplotlib_ em, praticamente, dois aspectos: i) provendo melhor estilização dos gráficos e tornando-os visualmente \"belos\"; ii) compactando funções de plotagem do _matplotlib_, de modo que plotagens robustas sejam obtidas com menos instruções de código.\n\n# Vamos começar importando as bibliotecas que utilizaremos.\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# Vamos reconstruir e importar alguns *DataFrames*.\n\n# In[2]:\n\n\nserie_Idade = pd.Series({'Ana':20, 'João': 19, 'Maria': 21, 'Pedro': 22, 'Túlio': 20}, name=\"Idade\")\nserie_Peso = pd.Series({'Ana':55, 'João': 80, 'Maria': 62, 'Pedro': 67, 'Túlio': 73}, name=\"Peso\")\nserie_Altura = pd.Series({'Ana':162, 'João': 178, 'Maria': 162, 'Pedro': 165, 'Túlio': 171}, name=\"Altura\")\n\n\n# In[3]:\n\n\ndicionario_series_exemplo = {'Idade': serie_Idade, 'Peso': serie_Peso, 'Altura': serie_Altura}\n\n\n# In[4]:\n\n\ndf_dict_series = pd.DataFrame(dicionario_series_exemplo);df_dict_series\n\n\n# In[5]:\n\n\ndf_exemplo = pd.read_csv('../database/exemplo_data.csv', index_col=0)\ndf_exemplo['coluna_3'] = pd.Series([1,2,3,4,5,6,7,8,np.nan,np.nan],index=df_exemplo.index)\ndf_exemplo.index = pd.to_datetime(df_exemplo.index)\ndf_exemplo\n\n\n# In[6]:\n\n\ncovid_PB = pd.read_csv('https://superset.plataformatarget.com.br/superset/explore_json/?form_data=%7B%22slice_id%22%3A1550%7D&csv=true', \n sep=',', index_col=0)\ncovid_PB.head()\n\n\n# In[7]:\n\n\ncovid_BR = pd.read_excel('../database/HIST_PAINEL_COVIDBR_25jul2020.xlsx')\ncovid_BR.head()\n\n\n# ## Gráficos de Linha e de Dispersão\n# \n# Através da função `relplot`, podemos alterar o valor do parâmetro `kind` para\n# obter gráficos do linha, com `kind = 'line'`, ou gráficos de dispersão, com `kind = 'scatter'`. De modo alternativo, poderíamos também utilizar as funções `lineplot` e `scatterplot`. Entretanto, com `relplot`, diversos elementos de construção de figura existentes no *matplotlib* já são pré-configurados no _seaborn_. Isto é chamado no *seaborn* de *figure-level plot*.\n\n# Inicialmente, vejamos como a função `lineplot` se comporta como qualquer outra do `matplotlib.pyplot`.\n\n# In[8]:\n\n\nfig, ax = plt.subplots()\nax = sns.lineplot(x=\"index\", y=\"coluna_1\", data=df_exemplo.reset_index(), label = 'Coluna 1')\nax = sns.lineplot(x=\"index\", y=\"coluna_2\", data=df_exemplo.reset_index(), label = 'Coluna 2')\nax = sns.lineplot(x=\"index\", y=\"coluna_3\", data=df_exemplo.reset_index(), label = 'Coluna 3')\nax.set_xlabel('Data')\nax.set_ylabel('Valor')\nfig.autofmt_xdate() # auto-formata xticks tipo \"data\"\n\n\n# Para utilizar a função `relplot`, precisaremos reorganizar o banco de dados de modo que haja apenas uma coluna de valores no eixo _y_ (`Valor`) e uma coluna com um identificador de cor/tonalidade (`Coluna`).\n\n# In[9]:\n\n\n# reorganiza para 'Coluna 1'\ndf_exemplo_px = pd.DataFrame(df_exemplo['coluna_1']).rename({'coluna_1':'Valor'}, axis=1)\ndf_exemplo_px['Coluna'] = 'Coluna 1' \n\n# concatena 'Coluna 2'\ndf_exemplo_px_temp = pd.DataFrame(df_exemplo['coluna_2']).rename({'coluna_2':'Valor'}, axis=1)\ndf_exemplo_px_temp['Coluna'] = 'Coluna 2'\ndf_exemplo_px = pd.concat([df_exemplo_px, df_exemplo_px_temp])\n\n# concatena 'Coluna 3'\ndf_exemplo_px_temp = pd.DataFrame(df_exemplo['coluna_3']).rename({'coluna_3':'Valor'}, axis=1)\ndf_exemplo_px_temp['Coluna'] = 'Coluna 3'\ndf_exemplo_px = pd.concat([df_exemplo_px, df_exemplo_px_temp])\n\ndf_exemplo_px.head()\n\n\n# In[10]:\n\n\n# 'hue' atribui as tonalidades de cor com base no identificador \np = sns.relplot(x = 'index', y='Valor', hue = 'Coluna', data=df_exemplo_px.reset_index().dropna(), kind='line')\np.fig.autofmt_xdate()\np.ax.set_xlabel('Data')\np.fig.set_size_inches(8,4) # largura, altura\n\n\n# Vamos agora plotar o gráfico de óbitos por COVID-19 na Paraíba juntamente com a média aritmética móvel de 7 dias e com a média geométrica móvel de 7 dias.\n# \n# Utilizaremos o método `rolling` de uma *Series* ou *DataFrame* do *pandas*. Este método cria janelas móveis onde podemos aplicar uma função agregadora (tal como média ou média geométrica).\n\n# Comentários: \n# \n# - A média aritmética tem a desvantagem de linearizar o efeito do crescimento ou decrescimento do número de óbitos, onde sabemos que o efeito é exponencial.\n# - A média geométrica móvel tem a desvantagem de se anular se o número de óbitos em algum dos dias da janela for zero.\n# - Em geral, as duas médias ficam muito próximas.\n\n# In[11]:\n\n\n# função que calcula a média geométrica\nfrom scipy.stats import gmean \n\n# série\ncovid_PB_obitos = covid_PB.obitosNovos\ncovid_PB_obitos = covid_PB_obitos.sort_index()\ncovid_PB_obitos.name = 'Óbitos'\n\n# dataframe\ncovid_PB_obitos_df = pd.DataFrame(covid_PB_obitos)\ncovid_PB_obitos_df['Tipo'] = 'Valor nominal'\n\n# média aritmética móvel\ncovid_PB_obitos_df_temp = pd.DataFrame(covid_PB_obitos.rolling(7).mean().dropna())\ncovid_PB_obitos_df_temp['Tipo'] = 'MM:arit - 7d'\ncovid_PB_obitos_df = pd.concat([covid_PB_obitos_df, covid_PB_obitos_df_temp])\n\n# média geométrica móvel\ncovid_PB_obitos_df_temp = pd.DataFrame(covid_PB_obitos.rolling(7).aggregate(gmean).dropna())\ncovid_PB_obitos_df_temp['Tipo'] = 'MM:geom - 7d'\ncovid_PB_obitos_df = pd.concat([covid_PB_obitos_df, covid_PB_obitos_df_temp])\n\ncovid_PB_obitos_df.index = pd.to_datetime(covid_PB_obitos_df.index)\n\ncovid_PB_obitos_df.tail()\n\n\n# In[12]:\n\n\np = sns.relplot(x = 'data', y='Óbitos', \n hue = 'Tipo', \n data=covid_PB_obitos_df.reset_index(), \n kind='line')\np.fig.autofmt_xdate()\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# Vamos agora construir um gráfico de dispersão com o _DataFrame_ `df_exemplo_px`.\n\n# In[13]:\n\n\n# 'scatter' é padrão\np = sns.relplot(x = 'index', y='Valor', \n hue = 'Coluna', \n data=df_exemplo_px.reset_index().dropna())\np.fig.autofmt_xdate()\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# Vamos forçar os limites de datas a ficarem dentro do mínimo (menos um dia) e do máximo (mais um dia):\n\n# In[14]:\n\n\np = sns.relplot(x = 'index', y='Valor', \n hue = 'Coluna', \n data=df_exemplo_px.reset_index().dropna())\n\n# offset de data\np.ax.set_xlim((df_exemplo_px.reset_index()['index'].min()\n - pd.DateOffset(days=1)),\n (df_exemplo_px.reset_index()['index'].max()\n + pd.DateOffset(days=1)))\n\np.fig.autofmt_xdate()\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# In[15]:\n\n\n# especifica cores e tamanhos\np = sns.relplot(x = 'index', y='coluna_1', \n hue = 'coluna_2', \n size = 'coluna_3', \n data=df_exemplo.reset_index().dropna())\n\np.ax.set_xlim((df_exemplo.reset_index()['index'].min()\n - pd.DateOffset(days=1)), \n (df_exemplo.reset_index()['index'].max()\n + pd.DateOffset(days=1)))\n\np.fig.autofmt_xdate()\np.ax.set_xlabel('')\np.fig.set_size_inches(8,4)\n\n\n# In[16]:\n\n\ncovid_PB_casos_obitos = covid_PB[['obitosNovos', 'casosNovos']].sort_index()\ncovid_PB_casos_obitos.index = pd.to_datetime(covid_PB_casos_obitos.index)\n\n# cor: óbitos novos\np = sns.relplot(x = 'data', y = 'casosNovos', \n hue = 'obitosNovos', \n data=covid_PB_casos_obitos.reset_index())\n\np.ax.set_xlim((covid_PB_casos_obitos.reset_index()['data'].min()\n - pd.DateOffset(days=5)),\n (covid_PB_casos_obitos.reset_index()['data'].max()\n + pd.DateOffset(days=5)))\n\np.fig.autofmt_xdate()\np.ax.set_xlabel('')\np.ax.set_ylabel('Casos COVID-19 - PB')\np.ax.set_title('Casos e Óbitos de COVID-19 na Paraíba')\np.fig.set_size_inches(8,4)\n\n\n# ## Gráficos de dispersão em dados categóricos\n# \n# Quando há muitos valores repetidos em uma variável, os gráficos de dispersão podem não ilustrar efetivamente o comportamento dos dados. Neste caso, é interessante que o gráfico considere a repetição dos valores dentro de uma mesma categoria.\n\n# Comentários:\n# \n# - Isto acontece quando o eixo horizontal contém variáveis categóricas e, assim, tem-se repetição de valores dentro de uma mesma categoria.\n\n# Para gráficos deste tipo, utilizaremos os dados de óbitos por COVID-19 no Brasil. Agruparemos o número de óbitos por dia da semana.\n\n# In[17]:\n\n\ncovid_BR_obitos = covid_BR.query('regiao == \"Brasil\"')[['obitosNovos','data']]\n\ncovid_BR_obitos.data = pd.to_datetime(covid_BR_obitos.data)\n\ncovid_BR_obitos['Dia'] = covid_BR_obitos.data.dt.weekday.map(\n {0:'Segunda-Feira',\n 1:'Terça-Feira',\n 2:'Quarta-Feira',\n 3:'Quinta-Feira',\n 4:'Sexta-Feira',\n 5:'Sábado',\n 6:'Domingo'})\n\ncovid_BR_obitos = covid_BR_obitos.set_index('data')\ncovid_BR_obitos\n\n\n# Se quisermos determinar a ordem do eixo _x_, `relplot` não é a função ideal. Além disso, devido à sobreposição dos dados, ela definitivamente não é a ideal para variáveis categóricas. Vejamos:\n\n# In[18]:\n\n\np = sns.relplot(x='Dia', y='obitosNovos', data=covid_BR_obitos)\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# ## O gráfico *stripplot*\n# \n# O *stripplot* é um gráfico de dispersão onde a cada observação é colocado um deslocamento aleatório para evitar a sobreposição e fornecer uma ideia mais precisa da quantidade de dados.\n# \n# Vamos construir o *stripplot* através da função `catplot`. O *stripplot* é o gráfico padrão do `catplot` (tem o argumento `kind = 'strip'`).\n# \n# Podemos determinar a ordem das variáveis categóricas com o argumento *order*.\n\n# In[19]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos', \n data=covid_BR_obitos, order = \n ['Segunda-Feira', 'Terça-Feira',\n 'Quarta-Feira', 'Quinta-Feira',\n 'Sexta-Feira', 'Sábado', 'Domingo'])\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Se colocarmos `jitter=False`, obteremos o gráfico de dispersão usual (com o detalhe de que podemos definir a ordem dos rótulos do eixo *x*).\n\n# In[20]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos', \n jitter = False,\n data=covid_BR_obitos,\n order = ['Segunda-Feira', 'Terça-Feira',\n 'Quarta-Feira', 'Quinta-Feira',\n 'Sexta-Feira', 'Sábado', 'Domingo'])\n\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# ## O gráfico *swarmplot*\n# \n# O *swarmplot* é um gráfico de dispersão onde, diferentemente do *stripplot*, nenhum dado pode ficar sobreposto. Desta forma, também fornece uma ideia mais precisa da quantidade de dados.\n# \n# Construiremos o *swarmplot* através da função `catplot` com o argumento `kind = 'swarm'`. Como o *swarmplot* também é um tipo do `catplot`, podemos determinar a ordem das variáveis categóricas com o argumento `order`.\n\n# In[21]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos',\n kind = 'swarm',\n data=covid_BR_obitos, \n order = ['Segunda-Feira', 'Terça-Feira',\n 'Quarta-Feira', 'Quinta-Feira',\n 'Sexta-Feira', 'Sábado', 'Domingo'])\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# ## Gráficos de Barras e Colunas\n# \n# Para criar gráficos de barras e colunas com o *seaborn* utilizaremos a função `catplot` com o argumento `kind=bar`. Se a variável categórica estiver no eixo *x*, o gráfico será de coluna; se a variável categórica estiver no eixo *y*, o gráfico será de barra.\n\n# In[22]:\n\n\ncovid_Regioes = covid_BR[['regiao','obitosNovos']].groupby('regiao').sum().query('regiao != \"Brasil\"')/2\n\np = sns.catplot(x='regiao', y='obitosNovos',\n kind = 'bar',data=covid_Regioes.reset_index())\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# In[23]:\n\n\ncovid_Regioes = covid_BR[['regiao','obitosNovos']].groupby('regiao').sum().query('regiao != \"Brasil\"')/2\n\np = sns.catplot(x='obitosNovos', y='regiao',\n kind = 'bar',data=covid_Regioes.reset_index())\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# In[24]:\n\n\ndf_dict_series_sns = pd.DataFrame(df_dict_series.Idade).rename({'Idade':'Valor'}, axis=1)\ndf_dict_series_sns['Dado'] = 'Idade'\n\ndf_dict_series_sns_temp = pd.DataFrame(df_dict_series.Altura).rename({'Altura':'Valor'}, axis=1)\ndf_dict_series_sns_temp['Dado'] = 'Altura'\ndf_dict_series_sns = pd.concat([df_dict_series_sns, df_dict_series_sns_temp])\n\ndf_dict_series_sns_temp = pd.DataFrame(df_dict_series.Peso).rename({'Peso':'Valor'}, axis=1)\ndf_dict_series_sns_temp['Dado'] = 'Peso'\ndf_dict_series_sns = pd.concat([df_dict_series_sns, df_dict_series_sns_temp])\n\ndf_dict_series_sns\n\n\n# In[25]:\n\n\np = sns.catplot(x='index', y='Valor', \n hue='Dado',\n data = df_dict_series_sns.reset_index(),\n kind='bar')\n\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# ## _Box Plot_ e plots alternativos\n# \n# Tanto o *BoxPlot* quanto os plots alternativos que apresentaremos aqui (*violinplot* e *boxenplot*) fazem parte do `catplot`. Para construir um \n# \n# - *Box Plot* utiliza-se o argumento `kind='box'`;\n# - *Violin Plot* utiliza-se o argumento `kind='violin'`;\n# - *Boxen Plot* (ou *letter-value plot*) utiliza-se o argumento `kind='boxen'`.\n# \n# ```{note}\n# O *boxenplot* foi criado por Hadley Wickham (criador do *ggplot2* e da maioria dos pacotes do *tidyverse* do *R*) e colaboradores e é uma generalização do *BoxPlot* que apresenta mais quantis. Foi introduzido como [letter-value plots](https://vita.had.co.nz/papers/letter-value-plot.html). O *violinplot* recebe este nome, pois seu gráfico assemelha-se a um violino.\n# ```\n\n# In[26]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos',\n kind = 'box',\n data=covid_BR_obitos,\n order = ['Segunda-Feira', 'Terça-Feira',\n 'Quarta-Feira', 'Quinta-Feira',\n 'Sexta-Feira', 'Sábado', 'Domingo'])\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# In[27]:\n\n\ncovid_regioes_diarios_px = covid_BR.set_index(\n 'data').query('regiao != \"Brasil\"')[['obitosNovos', 'regiao']].reset_index().rename(\n {'obitosNovos':'Óbitos','regiao':'Região','data':'Data'},axis=1)\n\ncovid_regioes_diarios_px = covid_regioes_diarios_px.groupby(['Região','Data']).sum()/2\ncovid_regioes_diarios_px = covid_regioes_diarios_px.reset_index().set_index('Data')\n\ncovid_regioes_diarios_px\n\n\n# In[28]:\n\n\np = sns.catplot(x='Região', y='Óbitos',\n kind = 'box',\n data=covid_regioes_diarios_px)\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Na presença de muitos *outliers*, como é o caso do gráfico anterior, é interessante considerar uma alternativa ao *Box Plot*.\n# \n# Vamos ver agora o *Boxen Plot* (ou *letter-value plots*). Este plot considera os quantis: ..., 0.8%, 1.56%, 3.13%, 6.25%, 12.5%, 25%, 50%, 75%, 87.5%, 93.75%, 96.88%, 98.44%, 99.24%, ...\n\n# In[29]:\n\n\np = sns.catplot(x='Região', y='Óbitos',\n kind = 'boxen',\n data=covid_regioes_diarios_px)\n\np.ax.set_xlabel(''); \np.fig.set_size_inches(8,4)\n\n\n# Porém, em um gráfico sem muitos *outliers*, o *Boxen Plot* não difere muito do *Box Plot*.\n\n# In[30]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos',\n kind = 'boxen', \n data=covid_BR_obitos, \n order = ['Segunda-Feira', 'Terça-Feira',\n 'Quarta-Feira', 'Quinta-Feira',\n 'Sexta-Feira', 'Sábado', 'Domingo'])\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Na presença de muitos *outliers*, também é preferível um *Violin Plot* em vez de um *Box Plot*, para tornar visível o que está ocorrendo.\n\n# In[31]:\n\n\np = sns.catplot(x='Região', y='Óbitos',\n kind = 'violin',\n data=covid_regioes_diarios_px)\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# Muitas vezes, é interessante sobrepor um *Violin Plot* a um *Swarm Plot* para evidenciar o comportamento da distribuição dos dados.\n\n# In[32]:\n\n\np = sns.catplot(x='Região', y='Óbitos',\n kind = 'violin',\n data=covid_regioes_diarios_px)\n\nsns.swarmplot(x='Região', y='Óbitos',\n data=covid_regioes_diarios_px,\n ax = p.ax,\n size=4, color='k')\n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# In[33]:\n\n\np = sns.catplot(x='Dia', y='obitosNovos',\n kind = 'violin',\n data=covid_BR_obitos)\n\nsns.swarmplot(x='Dia', y='obitosNovos',\n data=covid_BR_obitos,\n ax = p.ax, size=4, color='k') \n\np.ax.set_xlabel('');\np.fig.set_size_inches(8,4)\n\n\n# ## Histogramas\n# \n# O *seaborn* constrói histogramas a partir da função `histplot`, ou da função obsoleta `distplot`. \n# \n# Incluímos um estimador de densidade baseado em núcleo Gaussiano (_Gaussian kernel_) utilizando o argumento `kde=True`.\n\n# In[34]:\n\n\nfig, ax = plt.subplots(figsize=(8,4))\n_ = sns.histplot(covid_regioes_diarios_px.query('Região==\"Nordeste\"')['Óbitos'],kde=True)\n\n\n# Para remover o estimador, selecionamos `kde=False`.\n\n# In[35]:\n\n\nfig, ax = plt.subplots(figsize=(8,4))\n_ = sns.histplot(covid_regioes_diarios_px.query('Região==\"Nordeste\"')['Óbitos'],kde=False)\n\n\n# Para plotarmos apenas o estimador de densidade sem o histograma, usamos `distplot` com a opção `hist=False`.\n\n# In[36]:\n\n\nfig, ax = plt.subplots(figsize=(8,4))\n_ = sns.distplot(covid_regioes_diarios_px.query('Região==\"Nordeste\"')['Óbitos'],hist=False)\n\n\n# É possível plotar o histograma com o estimador para qualquer série do _DataFrame_.\n\n# In[37]:\n\n\nfig, ax = plt.subplots(figsize=(8,4))\n_ = sns.histplot(df_exemplo['coluna_1'],kde=True)\n\n\n# ## Distribuição conjunta e marginal\n# \n# O histograma permite que verifiquemos a distribuição de uma ou mais variáveis, mas sem levar outras em consideração. Para plotarmos uma distribuição conjunta, bem como a distribuição individual (marginal) de cada variável, podemos utilizar a função `jointplot`.\n\n# In[38]:\n\n\n_ = sns.jointplot(x = 'coluna_1', y = 'coluna_2', data=df_exemplo, height=7)\n\n\n# O próximo exemplo usa a função `jointplot` para plotar distribuições conjuntas relativas ao número de óbitos por Covid-19 por região do Brasil durante uma certa janela temporal.\n\n# In[39]:\n\n\ncovid_regioes_diarios = pd.DataFrame()\n\nregioes = covid_BR.query('regiao != \"Brasil\"')['regiao'].drop_duplicates().array\n\nfor regiao in regioes:\n temp_series = covid_BR.set_index('data').query('regiao == @regiao')['obitosNovos'].groupby('data').sum()/2\n temp_series.name = 'obitos_' + regiao\n covid_regioes_diarios = pd.concat([covid_regioes_diarios, temp_series], axis=1)\n \ncovid_regioes_diarios.index = pd.to_datetime(covid_regioes_diarios.index)\ncovid_regioes_diarios.head()\n\n\n# In[40]:\n\n\n_ = sns.jointplot(x='obitos_Nordeste', y='obitos_Sudeste',\n data = covid_regioes_diarios, height=7)\n\n\n# ## Estilos e cores\n# \n# O *seaborn* disponibiliza 5 estilos pré-definidos: *darkgrid*, *whitegrid*, *dark*, *white* e *ticks*. Vejamos cada um deles.\n\n# In[41]:\n\n\nimport matplotlib.dates as mdates\nfrom matplotlib.ticker import FuncFormatter\n\n\n# In[42]:\n\n\nsns.set_style(\"darkgrid\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[43]:\n\n\nsns.set_style(\"whitegrid\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[44]:\n\n\nsns.set_style(\"dark\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[45]:\n\n\nsns.set_style(\"white\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[46]:\n\n\nsns.set_style(\"ticks\") # A diferença com o anterior são os \"ticks\" no eixo x\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# ### Molduras\n# \n# Utilizamos a função `despine` para adicionar ou remover molduras em plotagens com o *seaborn*. Podemos especificar lados para adicionar e remover molduras utilizando os booleanos `True` e `False`.\n\n# In[47]:\n\n\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) \np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) \np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y'))\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\nsns.despine(right=False, top=False)\n\n\n# Podemos criar um tipo de \"acolchoamento\" aumentando a distância entre o gráfico e a moldura utilizando `offset`. Atribuindo um valor para este argumento, as bordas serão afastadas naturalmente. Um tipo de \"corte estético\" pode ser adicionado à moldura com `trim=False`.\n\n# In[48]:\n\n\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos',\n hue = 'Tipo',\n data=covid_PB_obitos_df.reset_index(),\n kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\nsns.despine(right=False, top=False, offset=30)\n\n\n# In[49]:\n\n\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos',\n hue = 'Tipo',\n data=covid_PB_obitos_df.reset_index(),\n kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\nsns.despine(offset=30, trim=True)\n\n\n# ### Contextos e escala\n# \n# O *seaborn* possui contextos pré-definidos que mudam a escala do gráfico para melhor satisfazer a aplicação de interesse. Para definir o contexto, utilizamos a função `set_context`. Há 4 contextos pré-definidos: *paper*, *notebook*, *talk* e *poster*.\n\n# In[50]:\n\n\nsns.set_context(\"poster\")\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', \n hue = 'Tipo',\n data=covid_PB_obitos_df.reset_index(),\n kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[51]:\n\n\nsns.set_context(\"talk\")\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[52]:\n\n\nsns.set_context(\"notebook\")\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[53]:\n\n\nsns.set_context(\"paper\")\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', hue = 'Tipo', data=covid_PB_obitos_df.reset_index(), kind='line')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# ### Paletas e mapas de cores\n# \n# É possível personalizar a paleta de cores a ser utilizada ou escolher uma da lista (extremamente extensa) de paletas disponíveis utilizando a função `set_palette`. Duas formas usuais de selecionar a paleta de cores são:\n# \n# - no escopo de uma instrução `with` por meio da função `color_palette`;\n# - pelo argumento `palette` nas funções de construção gráfica.\n# \n# A função `color_palette()` aceita nomes de uma paleta do _seaborn_ (_deep_, _muted_, _bright_, _pastel_,_dark_,_colorbind_), um mapa de cores (_colormap_) do _matplotlib_, uma sequência de cores em qualquer formato aceitável pelo _matplotlib_, entre outras opções.\n# \n# ```{note}\n# Para uma lista ampla de paletas, veja a discussão neste [post](https://medium.com/@morganjonesartist/color-guide-to-seaborn-palettes-da849406d44f) ou a [_Colormap reference_](https://matplotlib.org/stable/gallery/color/colormap_reference.html) do _matplotlib_.\n# ```\n\n# Abaixo temos alguns exemplos de paletas nativas do _seaborn_\n\n# In[54]:\n\n\nsns.color_palette()\n\n\n# In[55]:\n\n\nsns.color_palette('colorblind')\n\n\n# In[56]:\n\n\nsns.color_palette('bright')\n\n\n# e de mapas do cores do _matplotlib_.\n\n# In[57]:\n\n\nsns.color_palette('Greens')\n\n\n# In[58]:\n\n\nsns.color_palette('turbo')\n\n\n# In[59]:\n\n\nsns.color_palette('cividis')\n\n\n# Nos exemplos a seguir, plotamos alguns gráficos novamente com paletas diferentes.\n\n# In[60]:\n\n\n# paleta: 'BuPu'\nsns.set_context(\"paper\")\nsns.set_style(\"ticks\")\np = sns.relplot(x = 'data', y='Óbitos', \n hue = 'Tipo', \n data=covid_PB_obitos_df.reset_index(), kind='line',\n palette = 'BuPu')\np.fig.autofmt_xdate()\np.ax.xaxis.set_minor_locator(mdates.DayLocator(interval=7)) #Intervalo entre os tracinhos\np.ax.xaxis.set_major_locator(mdates.DayLocator(interval=21)) #Intervalo entre as datas\np.ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y')) #Formato da data\np.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[61]:\n\n\n# paleta: 'mako_r'\nwith sns.color_palette('mako_r'):\n p = sns.catplot(x='Região', y='Óbitos', \n kind = 'violin',\n data=covid_regioes_diarios_px)\n p.ax.set_xlabel(''); p.fig.set_size_inches(12,4)\n\n\n# In[62]:\n\n\n# paleta: icefire_r\nsns.set_palette('icefire_r')\n_ = sns.jointplot(x='obitos_Nordeste', y='obitos_Sudeste', \n data = covid_regioes_diarios, \n height=6)\n\n\n# ## Nota\n# \n# Este capítulo baseia-se nas notas de aula da Profa. Andrea Rocha (CI/UFPB), elaboradas para o mini-curso [FMECD](https://gcpeixoto.github.io/FMECD/ipynb/01a-introducao.html).\n", "meta": {"hexsha": "6769bc52a96e5cb1358b18a8a3c0b7181f167be9", "size": 28798, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/ipynb/16-visualizacao-dados-seaborn.py", "max_stars_repo_name": "gcpeixoto/ICD", "max_stars_repo_head_hexsha": "bae7d02cd467240649c89b0ba4440966fba18cc7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-09T01:56:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T01:56:56.000Z", "max_issues_repo_path": "_build/jupyter_execute/ipynb/16-visualizacao-dados-seaborn.py", "max_issues_repo_name": "gcpeixoto/ICD", "max_issues_repo_head_hexsha": "bae7d02cd467240649c89b0ba4440966fba18cc7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/ipynb/16-visualizacao-dados-seaborn.py", "max_forks_repo_name": "gcpeixoto/ICD", "max_forks_repo_head_hexsha": "bae7d02cd467240649c89b0ba4440966fba18cc7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-23T14:24:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T14:24:03.000Z", "avg_line_length": 32.6878547106, "max_line_length": 372, "alphanum_fraction": 0.6954302382, "include": true, "reason": "import numpy,from scipy", "num_tokens": 8590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.16885695632426873, "lm_q1q2_score": 0.07784589266996432}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # NAM 2019 pMuTT Workshop\n# \n# Instructions and materials for the \"Theory, Applications, and Tools for Kinetic Modeling\" workshop can be found on [our documentation page](https://vlachosgroup.github.io/pMuTT/nam_2019.html).\n# \n\n# # Table of Contents\n# \n# | **1\\. [Virtual Kinetic Laboratory Ecosystem](#section_1)**\n# \n# | **2\\. [Useful Links](#section_2)**\n# \n# | **3\\. [Constants](#section_3)**\n# \n# |-- **3.1. [Access common constants in appropriate units](#section_3_1)**\n# \n# |-- **3.2. [Convert between units](#section_3_2)**\n# \n# |-- **3.3. [Convert between equivalent quantities](#section_3_3)**\n# \n# | **4\\. [Exercise 1](#section_4)**\n# \n# | **5\\. [Creating statistical mechanical objects using StatMech](#section_5)**\n# \n# |-- **5.1. [Supported StatMech models](#section_5_1)**\n# \n# |--|-- **5.1.1 [Translations](#section_5_1_1)**\n# \n# |--|-- **5.1.2. [Vibrations](#section_5_1_2)**\n# \n# |--|-- **5.1.3. [Rotations](#section_5_1_3)**\n# \n# |--|-- **5.1.4. [Electronic](#section_5_1_4)**\n# \n# |--|-- **5.1.5. [Miscellaneous](#section_5_1_5)**\n# \n# |-- **5.2. [Initializing StatMech modes individually](#section_5_2)**\n# \n# |-- **5.3. [Initializing StatMech modes using presets](#section_5_3)**\n# \n# | **6\\. [Plot Thermodynamic Quantities](#section_6)**\n# \n# | **7\\. [Exercise 2](#section_7)**\n# \n# | **8\\. [Creating empirical objects](#section_8)**\n# \n# |-- **8.1. [Inputting a NASA polynomial directly](#section_8_1)**\n# \n# |-- **8.2. [Fitting an empirical object to a StatMech object](#section_8_2)**\n# \n# | **9\\. [Input/Output](#section_9)**\n# \n# |-- **9.1. [Input via Excel](#section_9_1)**\n# \n# |-- **9.2. [Output via Thermdat](#section_9_2)**\n# \n# | **10\\. [Reactions](#section_10)**\n# \n# | **11\\. [Exercise 3](#section_11)**\n# \n# | **12\\. [Solutions](#section_12)**\n# \n# |-- **12.1. [Solution 1](#section_12_1)**\n# \n# |-- **12.2. [Solution 2](#section_12_2)**\n# \n# |-- **12.3. [Solution 3](#section_12_3)**\n\n# \n\n# # 1. Virtual Kinetic Laboratory Ecosystem\n# \n# \n# \n# \n# \n# \n# - Estimates thermochemical and kinetic parameters using statistical mechanics, transition state theory\n# - Writes input files for kinetic models and eases thermodynamic analysis\n# - Implemented in Python\n# - Easy to learn\n# - Heavily used in scientific community\n# - Object-oriented approach is a natural analogy to chemical phenomenon\n# - Library approach allows users to define the starting point and end point\n# \n# \n# \n\n# \n\n# # 2. Useful Links\n# \n# - [Documentation](https://vlachosgroup.github.io/pMuTT/): find the most updated documentation\n# - [Issues](https://github.com/VlachosGroup/pmutt/issues): report bugs, request features, receive help\n# - [Examples](https://vlachosgroup.github.io/pMuTT/examples.html): see examples\n\n# \n\n# # 3. Constants\n# \n# The [constants module](https://vlachosgroup.github.io/pMuTT/constants.html) has a wide variety of functions for constants and unit conversion.\n\n# \n\n# ## 3.1. Access common constants in appropriate units\n# Below, we access Planck's constant in J s.\n\n# In[1]:\n\n\nfrom pmutt import constants as c\n\nh1 = c.h('eV s', bar=True)\nprint('h = {} eV s'.format(h1))\n\n\n# \n\n# ## 3.2. Convert between units\n# Below, we convert 12 atm of pressure to psi.\n\n# In[2]:\n\n\nfrom pmutt import constants as c\n\nP_atm = 12. # atm\nP_psi = c.convert_unit(num=P_atm, initial='atm', final='psi')\n\nprint('{} atm = {} psi'.format(P_atm, P_psi))\n\n\n# \n\n# ## 3.3. Convert between equivalent quantities\n# Below, we convert 1000 wavenumbers (cm-1) to frequency.\n\n# In[3]:\n\n\nfrom pmutt import constants as c\n\nwave_num = 1000. # cm-1\nfreq = c.wavenumber_to_freq(wave_num) # Hz\n\nprint('{} cm-1 = {} Hz'.format(wave_num, freq))\n\n\n# \n\n# # 4. Exercise 1\n# \n# Using `pmutt.constants`, calculate the dimensionless enthalpy (H/RT) using the following information:\n# - H = 0.5 eV\n# - T = 77 F\n\n# In[4]:\n\n\n# Fill in your answer for Exercise 1 here\n\n\n# \n\n# # 5. Creating statistical mechanical objects using StatMech\n# \n# Molecules show translational, vibrational, rotational, electronic, and nuclear modes.\n# \n# \n\n# \n\n# ## 5.1. Supported StatMech modes\n# \n# \n# \n# The StatMech object allows us to specify translational, vibrational, rotational, electronic and nuclear modes independently, which gives flexibility in what behavior you would like. Below are the available modes.\n\n# \n\n# ### 5.1.1. Translations\n# - [``FreeTrans``](https://vlachosgroup.github.io/pMuTT/statmech.html#freetrans) - Translations assuming no intermolecular interactions\n\n# \n\n# ### 5.1.2. Vibrations\n# - [``HarmonicVib``](https://vlachosgroup.github.io/pMuTT/statmech.html#harmonicvib) - Harmonic vibrations\n# - [``QRRHOVib``](https://vlachosgroup.github.io/pMuTT/statmech.html#harmonicvib) - Quasi rigid rotor harmonic oscillator. Low frequency modes are treated as rigid rotations.\n# - [``EinsteinVib``](https://vlachosgroup.github.io/pMuTT/statmech.html#einsteinvib) - Each atom in the crystal vibrates as independent 3D harmonic oscillators\n# - [``DebyeVib``](https://vlachosgroup.github.io/pMuTT/statmech.html#debyevib) - Improves upon ``EinsteinVib`` by considering simultaneous vibrations. Improves accuracy at lower temperatures.\n\n# \n\n# ### 5.1.3. Rotations\n# - [``RigidRotor``](https://vlachosgroup.github.io/pMuTT/statmech.html#rigidrotor) - Molecule can be rotated with no change in bond properties\n\n# \n\n# ### 5.1.4. Electronic\n# - [``GroundStateElec``](https://vlachosgroup.github.io/pMuTT/statmech.html#groundstateelec) - Electronic ground state of the system\n# - [``LSR``](https://vlachosgroup.github.io/pMuTT/statmech.html#linear-scaling-relationships-lsrs) - Linear Scaling Relationship to estimate binding energies using reference adsorbate\n\n# \n\n# ### 5.1.5. Miscellaneous\n# - [``EmptyMode``](https://vlachosgroup.github.io/pMuTT/statmech.html#empty-mode) - Default mode if not specified. Does not contribute to any properties\n# - [``ConstantMode``](https://vlachosgroup.github.io/pMuTT/statmech.html#constant-mode) - Specify arbitrary values to thermodynamic quantities\n# \n# Using a ``StatMech`` mode gives you access to all the common thermodynamic properties.\n# \n# \n# \n# For this example, we will use a hydrogen molecule as an ideal gas:\n# - translations with no interaction between molecules\n# - harmonic vibrations\n# - rigid rotor rotations\n# - ground state electronic structure\n# - no contribution from nuclear modes.\n# \n# \n\n# \n\n# ## 5.2. Initializing StatMech modes individually\n\n# In[5]:\n\n\nfrom ase.build import molecule\nfrom pmutt.statmech import StatMech, trans, vib, rot, elec\n\nH2_atoms = molecule('H2')\n\n'''Translational'''\nH2_trans = trans.FreeTrans(n_degrees=3, atoms=H2_atoms)\n\n'''Vibrational'''\nH2_vib = vib.HarmonicVib(vib_wavenumbers=[4342.]) # vib_wavenumbers in cm-1\n\n'''Rotational'''\nH2_rot = rot.RigidRotor(symmetrynumber=2, atoms=H2_atoms)\n\n'''Electronic'''\nH2_elec = elec.GroundStateElec(potentialenergy=-6.77,spin=0) # potentialenergy in eV\n\n'''StatMech Initialization'''\nH2_statmech = StatMech(name='H2',\n trans_model=H2_trans,\n vib_model=H2_vib,\n rot_model=H2_rot,\n elec_model=H2_elec)\n\n'''Calculate thermodynamic properties'''\nH_statmech = H2_statmech.get_H(T=298., units='kJ/mol')\nS_statmech = H2_statmech.get_S(T=298., units='J/mol/K')\nprint('H_H2(T=298 K) = {:.1f} kJ/mol'.format(H_statmech))\nprint('S_H2(T=298 K) = {:.2f} J/mol/K'.format(S_statmech))\n\n\n# \n\n# ## 5.3. Initializing StatMech modes using presets\n# \n# Commonly used models can be accessed via [``presets``](https://vlachosgroup.github.io/pMuTT/statmech.html#presets). The currently supported models are:\n# \n# - [``idealgas``](https://vlachosgroup.github.io/pMuTT/statmech.html#ideal-gas-idealgas) - Ideal gases\n# - [``harmonic``](https://vlachosgroup.github.io/pMuTT/statmech.html#harmonic-approximation-harmonic) - Typical for surface species\n# - [``electronic``](https://vlachosgroup.github.io/pMuTT/statmech.html#electronic-electronic) - Only has electronic modes\n# - [``placeholder``](https://vlachosgroup.github.io/pMuTT/statmech.html#placeholder-placeholder) - No contribution to any property\n# - [``constant``](https://vlachosgroup.github.io/pMuTT/statmech.html#constant-constant) - Use arbitrary constants to thermodynamic properties\n# \n\n# In[6]:\n\n\nfrom ase.build import molecule\nfrom pmutt.statmech import StatMech, presets\n\nH2_statmech = StatMech(atoms=molecule('H2'),\n vib_wavenumbers=[4342.], # cm-1\n symmetrynumber=2,\n potentialenergy=-6.77, # eV\n spin=0.,\n **presets['idealgas'])\n\n'''Calculate thermodynamic properties'''\nH_statmech = H2_statmech.get_H(T=298., units='kJ/mol')\nS_statmech = H2_statmech.get_S(T=298., units='J/mol/K')\nprint('H_H2(T=298 K) = {:.1f} kJ/mol'.format(H_statmech))\nprint('S_H2(T=298 K) = {:.2f} J/mol/K'.format(S_statmech))\n\n\n# \n\n# # 6. Plot Thermodynamic Quantities\n# Use [`pmutt.plot_1D`](https://vlachosgroup.github.io/pMuTT/visual.html#plot-1d) and [`pmutt.plot_2D`](https://vlachosgroup.github.io/pMuTT/visual.html#plot-2d) to plot any function with respect to 1 or 2 variables.\n\n# In[7]:\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom pmutt import plot_1D, plot_2D\n\nT = np.linspace(300., 500.)\n\nf1, ax1 = plot_1D(H2_statmech,\n x_name='T', x_values=T,\n methods=('get_H', 'get_S', 'get_G'),\n get_H_kwargs={'units': 'kcal/mol'},\n get_S_kwargs={'units': 'cal/mol/K'},\n get_G_kwargs={'units': 'kcal/mol'})\nf1.set_size_inches(6, 6)\nf1.set_dpi(200)\nplt.show()\n\n\n# \n\n# # 7. Exercise 2\n# \n# 1. Create a ``StatMech`` object for ideal gas-phase H2O. The necessary inputs are given below.\n# \n# | Parameter | Value |\n# |--------------------------------|------------------------------|\n# | atoms | `molecule('H2O')` |\n# | Potential Energy (eV) | -6.7598 |\n# | Symmetry number | 2 |\n# | Spin | 0 |\n# | Vibrational Wavenumbers (cm-1) | 3825.434, 3710.264, 1582.432 |\n# \n# 2. Calculate the Gibbs energy in eV for H2O at T = 500 K and P = 2 bar.\n# \n# 3. Create a ``StatMech`` object for a Cu crystal using the ``DebyeVib`` model for the vibration mode and ``GroundStateElec`` model for electronic mode. The necessary inputs are given below.\n# \n# | Parameter | Value |\n# |------------------------|------------|\n# | Debye Temperature (K) | 310 |\n# | Interaction energy (eV)| 0 |\n# | Potential energy (eV) | -14.922356 |\n# \n# 4. Plot the H (in eV) and S (in eV/K) for Cu between T = 300 - 700 K.\n\n# In[8]:\n\n\n# Fill in your answer for Exercise 2 here\n\n# 1.\n\n\n# 2.\n\n\n# 3.\n\n\n# 4.\n\n\n# \n\n# # 8. Creating empirical objects\n# Currently, pMuTT supports [NASA polynomials](https://vlachosgroup.github.io/pMuTT/empirical.html#nasa) and [Shomate polynomials](https://vlachosgroup.github.io/pMuTT/empirical.html#shomate). They can be initialized in three ways:\n# - passing in the polynomials directly\n# - from a model (e.g. ``StatMech``, ``Shomate``) (``from_model``)\n# - from heat capacity, enthalpy and entropy data (``from_data``)\n# \n# \n\n# \n\n# ## 8.1. Inputting a NASA polynomial directly\n# \n# The H2 NASA polynomial from the [Burcat database](http://combustion.berkeley.edu/gri_mech/version30/files30/thermo30.dat) is represented as:\n# \n# ```\n# H2 TPIS78H 2 G 200.000 3500.000 1000.000 1\n# 3.33727920E+00-4.94024731E-05 4.99456778E-07-1.79566394E-10 2.00255376E-14 2\n# -9.50158922E+02-3.20502331E+00 2.34433112E+00 7.98052075E-03-1.94781510E-05 3\n# 2.01572094E-08-7.37611761E-12-9.17935173E+02 6.83010238E-01 4\n# ```\n# \n# This can be translated to pMuTT syntax using:\n\n# In[9]:\n\n\nfrom pmutt.empirical.nasa import Nasa\n\n# Initialize NASA polynomial\nH2_nasa = Nasa(name='H2',\n elements={'H': 2},\n phase='G',\n T_low=200., T_mid=1000., T_high=3500.,\n a_low=[2.34433112E+00, 7.98052075E-03, -1.94781510E-05,\n 2.01572094E-08, -7.37611761E-12, -9.17935173E+02,\n 6.83010238E-01],\n a_high=[3.33727920E+00, -4.94024731E-05, 4.99456778E-07,\n -1.79566394E-10, 2.00255376E-14, -9.50158922E+02,\n -3.20502331E+00])\n\n# Calculate thermodynamic quantities using the same syntax as StatMech\nH_H2 = H2_nasa.get_H(units='kcal/mol', T=298.)\nprint('H_H2(T=298 K) = {} kcal/mol'.format(H_H2))\n\n# Show thermodynamic quantities vs. T\nT = np.linspace(200., 3500.)\nf2, ax2 = plot_1D(H2_nasa,\n x_name='T', x_values=T,\n methods=('get_H', 'get_S', 'get_G'),\n get_H_kwargs={'units': 'kcal/mol'},\n get_S_kwargs={'units': 'cal/mol/K'},\n get_G_kwargs={'units': 'kcal/mol'})\nf2.set_size_inches(6, 6)\nf2.set_dpi(200)\nplt.show()\n\n\n# \n\n# ## 8.2. Fitting an empirical object to a StatMech object\n# Empirical objects can be made directly using ``StatMech`` objects and the ``from_model`` method.\n\n# In[10]:\n\n\nH2_nasa = Nasa.from_model(name='H2',\n T_low=200.,\n T_high=3500.,\n model=H2_statmech)\n\n# Compare the statistical mechanical model to the empirical model\nf3, ax3 = H2_nasa.plot_statmech_and_empirical(Cp_units='J/mol/K',\n H_units='kJ/mol',\n S_units='J/mol/K',\n G_units='kJ/mol')\nf3.set_size_inches(6, 8)\nf3.set_dpi(200)\nplt.show()\n\n\n# \n\n# # 9. Input/Output\n# pMuTT has more IO functionality than below. See this page for [supported IO functions](https://vlachosgroup.github.io/pMuTT/io.html).\n\n# \n\n# ## 9.1. Input via Excel\n# \n# Encoding each object in Python can be tedious. You can read several species from Excel spreadsheets using [``pmutt.io.excel.read_excel``](https://vlachosgroup.github.io/pmutt/io.html?highlight=read_excel#pmutt.io.excel.read_excel). Note that this function returns a list of dictionaries. This output allows you to initialize whichever object you want using kwargs syntax. There are also [special rules that depend on the header name](https://vlachosgroup.github.io/pMuTT/io.html#special-rules).\n# \n# Below, we show an example importing species data from a spreadsheet and creating a series of NASA polynomials.\n\n# In[11]:\n\n\nimport os\nfrom pprint import pprint\nfrom pathlib import Path\nfrom pmutt.io.excel import read_excel\nfrom pmutt.empirical.nasa import Nasa\n\n# Find the location of Jupyter notebook\n# Note that normally Python scripts have a __file__ variable but Jupyter notebook doesn't.\n# Using pathlib can overcome this limiation\ntry:\n notebook_folder = os.path.dirname(__file__)\nexcept NameError:\n notebook_folder = Path().resolve()\nos.chdir(notebook_folder)\n\n# Read the data from Excel\nab_initio_data = read_excel(io='./input/NH3_Input_Data.xlsx', sheet_name='species')\npprint(ab_initio_data)\n\n\n# In[12]:\n\n\n# Create NASA polynomials using **kwargs syntax\nnasa_species = []\nfor species_data in ab_initio_data:\n single_nasa_species = Nasa.from_model(T_low=100.,\n T_high=1500.,\n **species_data)\n nasa_species.append(single_nasa_species)\n\n# Print out a table using enthalpy, entropy, Gibbs energy at 298 K for each species\nprint('Name Enthalpy (kcal/mol) Entropy (cal/mol/K) Gibbs energy (kcal/mol)')\nprint('--------------------------------------------------------------------------------')\nfor single_nasa_species in nasa_species:\n name = single_nasa_species.name\n H = single_nasa_species.get_H(units='kcal/mol', T=298.)\n S = single_nasa_species.get_S(units='cal/mol/K', T=298.)\n G = single_nasa_species.get_G(units='kcal/mol', T=298.)\n print('{:12} {:10.1f} {:15.1f} {:15.1f}'.format(name, H, S, G))\n \n\n\n# \n\n# ## 9.2. Output via Thermdat\n# The thermdat format uses NASA polynomials to represent several species. It has a very particular format so doing it manually is error-prone. You can write a list of ``Nasa`` objects to thermdat format using [``pmutt.io.thermdat.write_thermdat``](https://vlachosgroup.github.io/pmutt/io.html#pmutt.io.thermdat.write_thermdat). \n# \n# Below, we write a thermdat file using the species imported from the spreadsheet.\n\n# In[13]:\n\n\nfrom pmutt.io.thermdat import write_thermdat\n\nwrite_thermdat(filename='./output/thermdat', nasa_species=nasa_species)\n\n\n# Similarly, a list of ``Nasa`` objects can be read from a thermdat using [``pmutt.io.thermdat.read_thermdat``](https://vlachosgroup.github.io/pMuTT/io.html#pmutt.io.thermdat.read_thermdat). \n\n# In[14]:\n\n\nfrom pmutt.io.thermdat import read_thermdat\n\nnasa_species = read_thermdat('./output/thermdat')\n\n\n# \n\n# # 10. Reactions\n# \n# \n# \n# ``Reaction`` objects can be created by putting together ``Nasa``, ``Shomate`` and ``StatMech`` objects.\n# \n# \n# \n# \n# The ``from_string`` method is the easiest way to create a ``Reaction`` object. It requires the relevant species to be in a dictionary and a string to describe the reaction.\n# \n# \n# \n# We will demonstrate its use for the formation of NH3.\n\n# In[15]:\n\n\nfrom pmutt.empirical.nasa import Nasa\nfrom pmutt.empirical.shomate import Shomate\nfrom pmutt.reaction import Reaction\n\n# Create species. Note that you can mix different types of species\nspecies = {\n 'H2': StatMech(name='H2', atoms=molecule('H2'),\n vib_wavenumbers=[4342.], # cm-1\n symmetrynumber=2,\n potentialenergy=-6.77, # eV\n spin=0.,\n **presets['idealgas']),\n 'N2': Nasa(name='N2', T_low=300., T_mid=643., T_high=1000.,\n a_low=[3.3956319945669633, 0.001115707689025668,\n -4.301993779374381e-06, 6.8071424019295535e-09,\n -3.2903312791047058e-12, -191001.55648623788,\n 3.556111439828502],\n a_high=[4.050329990684662, -0.0029677854067980108,\n 5.323485005316287e-06, -3.3518122405333548e-09,\n 7.58446718337381e-13, -191086.2004520406,\n 0.6858235504924011]),\n 'NH3': Shomate(name='NH3', T_low=300., T_high=1000.,\n a=[18.792357134351683, 44.82725349479501,\n -10.05898449447048, 0.3711633831565547,\n 0.2969942466370908, -1791.225746924463,\n 203.9035662274934, 1784.714638346206]),\n}\n\n# Define the formation of water reaction\nrxn = Reaction.from_string('1.5H2 + 0.5N2 = NH3', species)\n\n# Calculate forward change in enthalpy\nH_rxn_fwd = rxn.get_delta_H(units='kcal/mol', T=300.)\nprint('Delta H_fwd(T = 300 K) = {:.1f} kcal/mol'.format(H_rxn_fwd))\n\n# Calculate reverse change in enthalpy\nH_rxn_rev = rxn.get_delta_H(units='kcal/mol', T=300., rev=True)\nprint('Delta H_rev(T = 300 K) = {:.1f} kcal/mol'.format(H_rxn_rev))\n\n# Calculate enthalpy of reactants\nH_react = rxn.get_H_state(units='kcal/mol', T=300., state='reactants')\nprint('H_reactants(T = 300 K) = {:.1f} kcal/mol'.format(H_react))\n\n\n# \n\n# ## 11. Exercise 3\n# \n# 1. Use [``pmutt.io.thermdat.read_thermdat``](https://vlachosgroup.github.io/pMuTT/io.html#pmutt.io.thermdat.read_thermdat) to read the thermdat from './output/thermdat'.\n# \n# 2. Convert the list of ``Nasa`` to a dictionary of ``Nasa`` using ``pmutt.pmutt_list_to_dict``. The syntax to use the function is shown below.\n# \n# ```\n# from pmutt import pmutt_list_to_dict\n# \n# species_dict = pmutt_list_to_dict(species_list)\n# ```\n# \n# 3. Create a ``Reaction`` from the string: ``NH3(S) + RU(S) = TS1_NH3(S) = NH2(S) + H(S)`` and the dictionary from step 2.\n# \n# 4. Calculate the forward reaction enthalpy in kcal/mol at 298 K using [``Reaction.get_delta_H``](https://vlachosgroup.github.io/pMuTT/reactions.html#pmutt.reaction.Reaction.get_E_act).\n# \n# 5. Calculate the forward activation energy in kcal/mol at 298 K using [``Reaction.get_E_act``](https://vlachosgroup.github.io/pMuTT/reactions.html#pmutt.reaction.Reaction.get_E_act).\n\n# In[16]:\n\n\n# Fill in your answer for Exercise 3\n\n# 1.\n\n\n# 2.\n\n\n# 3. \n\n\n# 4.\n\n\n# 5.\n\n\n# \n\n# # 12. Solutions\n\n# \n\n# ## 12.1. Solution to Exercise 1\n# [Link to Exercise 1](#section_4)\n\n# In[17]:\n\n\nfrom pmutt import constants as c\n\n# Define information given\nH = 0.5 # eV\nT = 77 # F\n\n# Calculate H/RT\nHoRT = H/c.R('eV/K')/c.convert_unit(77, initial='F', final='K')\nprint('H/RT = {}'.format(HoRT))\n\n\n# \n\n# ## 12.2. Solution to Exercise 2\n# [Link to Exercise 2](#section_7)\n\n# In[18]:\n\n\nfrom ase.build import molecule\nfrom pmutt import plot_1D\nfrom pmutt.statmech import StatMech, presets\nfrom pmutt.statmech.vib import DebyeVib\nfrom pmutt.statmech.elec import GroundStateElec\n\n# 1. Create H2O molecule\nH2O_statmech = StatMech(atoms=molecule('H2O'),\n potentialenergy=-6.7598,\n symmetrynumber=2,\n spin=0,\n vib_wavenumbers=[3825.434, 3710.264, 1582.432],\n **presets['idealgas'])\n\n\n# 2. Calculate Gibbs energy of H2O at T = 500 K and P = 2 bar\nT = 500. # K\nP = 2. # bar\nG_H2O = H2O_statmech.get_G(units='eV', T=T, P=P)\nprint('G_H2O(T = 500 K, P = 2 bar) = {} eV'.format(G_H2O))\n\n\n# 3. Create Cu crystal\nCu_vib = DebyeVib(debye_temperature=310., interaction_energy=0.)\nCu_elec = GroundStateElec(potentialenergy=-14.922356)\nCu_statmech = StatMech(vib_model=Cu_vib, elec_model=Cu_elec)\n\n\n# 4. Plot the 1D profile for H and S between 300 K and 700 K\nT = np.linspace(300., 700.) # K\nf2, ax2 = plot_1D(Cu_statmech,\n x_name='T', x_values=T,\n methods=('get_H', 'get_S'),\n get_H_kwargs={'units': 'eV'},\n get_S_kwargs={'units': 'eV/K'})\nf2.set_size_inches(6, 6)\nf2.set_dpi(200)\nplt.show()\n\n\n# \n\n# ## 12.3. Solution to Exercise 3\n# [Link to Exercise 3](#section_11)\n\n# In[19]:\n\n\nfrom pmutt.io.thermdat import read_thermdat\nfrom pmutt import pmutt_list_to_dict\nfrom pmutt.reaction import Reaction\n\n# 1. Read the thermdat file\nspecies_list = read_thermdat('./output/thermdat')\n\n# 2. Convert the list of Nasa to a dictionary of Nasa\nspecies_dict = pmutt_list_to_dict(species_list)\n\n# 3. Create a Reaction from the specified string\nrxn = Reaction.from_string('NH3(S) + RU(S) = TS1_NH3(S) = NH2(S) + H(S)', species_dict)\n\n# 4. Calculate the reaction enthalpy\nH_rxn = rxn.get_delta_H(units='kcal/mol', T=298.)\nprint('H_rxn = {:.1f} kcal/mol'.format(H_rxn))\n\n# 5. Calculate the forward activation energy\nEa = rxn.get_E_act(units='kcal/mol', T=298.)\nprint('Ea_fwd = {:.1f} kcal/mol'.format(Ea))\n\n", "meta": {"hexsha": "548253ec6e02040f75c65ffd18ea5f2f32689835", "size": 24071, "ext": "py", "lang": "Python", "max_stars_repo_path": "docs/source/examples_jupyter/nam2019/NAM_2019_Workshop.py", "max_stars_repo_name": "wittregr/pMuTT", "max_stars_repo_head_hexsha": "1678fd3d3a10d8ef5389c02970a7ebaa92fc7344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-10-29T17:44:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:20:16.000Z", "max_issues_repo_path": "docs/source/examples_jupyter/nam2019/NAM_2019_Workshop.py", "max_issues_repo_name": "wittregr/pMuTT", "max_issues_repo_head_hexsha": "1678fd3d3a10d8ef5389c02970a7ebaa92fc7344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 101, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:49:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T10:59:57.000Z", "max_forks_repo_path": "docs/source/examples_jupyter/nam2019/NAM_2019_Workshop.py", "max_forks_repo_name": "wittregr/pMuTT", "max_forks_repo_head_hexsha": "1678fd3d3a10d8ef5389c02970a7ebaa92fc7344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2018-12-15T17:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T17:42:23.000Z", "avg_line_length": 32.8390177353, "max_line_length": 496, "alphanum_fraction": 0.651323169, "include": true, "reason": "import numpy", "num_tokens": 7437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.1732882059293266, "lm_q1q2_score": 0.07720501381553461}} {"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\"\"\"-------------------------------------------------------------------------------------------------------------------------------------------------------------- \"\"\"\r\n\r\n\"\"\"\r\n자료구조 : 1. sequence 자료구조 (순서있음)\r\n 2. 딕셔너리, 세트 (순서없음)\r\n\r\n인덱싱 : 리스트에서 하나의 요소를 인덱스 연산자를 통하여 참조(접근)하는 것\r\n\r\n슬라이싱 : 리스트 안에서 범위를 지정하여서 원하는 요소들을 선택하는 연산\r\n\r\n리스트 : 여러 개의 데이터가 저장되어 있는 자료구조\r\n리스트가 필요한 이유 : 여러 개의 데이터가 저장되어 있는 자료구조\r\n\"\"\"\r\n\r\n# 문자열 인덱싱 & 슬라이싱\r\n\r\ntext = \"IT Will is power.\"\r\nprint(text[:-2]) # IT Will is powe\r\nprint(text[:8], text[-1])\r\n\r\n# 인덱싱\r\nflist = [\"apple\", \"banana\", \"tomato\", \"peach\", \"pear\" ]\r\nprint(flist[0], flist[3], flist[-1])\r\n\r\n# 슬라이싱\r\na = [0,1,4,9,16,25,36,49]\r\na[3:6]\r\n\r\n# 리스트 (append로 추가해서 리스트를 만들어보는 것)\r\n\r\nscores = [ ]\r\nfor i in range(10):\r\n scores.append(int(input(\"성적을 입력하시오:\")))\r\nprint(scores)\r\n\r\nscores[0] = 80\r\n\r\nscores[i] = 10;\r\nscores[i+2] = 20;\r\n\r\n# 리스트의 요소갯수만큼 리스트가 반복되어 출력\r\nfor element in scores:\r\n print(scores)\r\n\r\n# 복잡한 리스트\r\nlist1 = [12,\"dog\",180.14] # 혼합자료형\r\nlist2 = [[\"Seoul\", 10], [\"Paris\", 12], [\"London\", 50]] # 내장 리스트\r\n\r\n# 리스트 기초연산\r\nmarvel_heroes = [ \"스파이더맨\", \"헐크\", \"아이언맨\" ]\r\ndc_heroes = [ \"슈퍼맨\", \"배트맨\", \"원더우먼\" ]\r\n\r\nheros = marvel_heroes + dc_heroes\r\nheros\r\n# 리스트에 곱하기\r\nvalues = [1,2,3]*3\r\nvalues # [1, 2, 3, 1, 2, 3, 1, 2, 3]\r\nlen(values)\r\n \r\n# 요소추가하기\r\ndevelopteam = []\r\ndevelopteam.append(\"이유현\")\r\ndevelopteam.append(\"성민승\")\r\ndevelopteam.append(\"김동완\")\r\n\r\ndevelopteam\r\n\r\n# 리스트 안의 내용 조회\r\nif \"이유현\" in developteam:\r\n print(\"내부인원\")\r\n \r\n# 리스트 인덱스 확인\r\ndevelopteam.index(\"이유현\") # 0\r\ndevelopteam.index(\"김동완\") # 2\r\n\r\n# 리스트 최소값 최대값\r\nvalues = [ 100, 20, 31, 45, 15, 6, 7, 8, 9, 10 ]\r\nmin(values)\r\nmax(values)\r\n\r\n# 리스트에서 sort 쓰기 정렬~~~\r\nvalues.sort()\r\nvalue2=sorted(values)\r\nprint(value2)\r\n\r\n# 리스트 내의 조건문\r\nlist1 = [3,4,5]\r\nlist2 = [x*2 for x in list1]\r\nprint(list2)\r\n\r\n# 2차원 리스트\r\ns = [ \r\n[ 1, 2, 3, 4, 5 ] ,\r\n[ 6, 7, 8, 9, 10 ], \r\n[11, 12, 13, 14, 15 ] \r\n]\r\n\r\nprint(s)\r\n\r\n# 동적으로 2차원 리스트 생성\r\n\r\nrows = 3\r\ncols = 5\r\n\r\ns = []\r\nfor row in range(rows):\r\n s += [[3]*cols]\r\n \r\nprint(\"s=\",s) # s= [[3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 3, 3, 3, 3]]\r\n\r\nrows = len(s)\r\ncols = len(s[0])\r\ncols\r\nfor r in range(rows):\r\n for c in range(cols):\r\n print(s[r][c], end=\",\")\r\n print()\r\n\r\n\"\"\"\r\n tuple!! \r\n 튜플은 변경될 수 없는 리스트 + 순서가 없다!!\r\n \r\n tuple('listname') \r\n : 리스트를 튜플로 변경한다.\r\n\"\"\"\r\n# tuple을 변경하려고 해보자\r\n\r\nt1 = (1,2,3,4,5);\r\nt2 = (1,2,3,4,5);\r\n\r\nt1[0] =100; # TypeError: 'tuple' object does not support item assignment\r\n\r\n# 튜플 대입 연산\r\nstudent1 = (\"철수\",19,\"CS\")\r\n(name,age,major) = student1\r\nname # '철수'\r\n\r\n\"\"\"\r\n set!!\r\n 세트는 중복되지 않은 항목들이 모인것 + 순서가 없다!!\r\n \r\n\"\"\"\r\n\r\nnumbers = {1,2,2,3,3,3,4}\r\n\r\nnumbers # {1, 2, 3, 4}\r\n\r\n# 요소 추가\r\nnumbers.add(5)\r\n\r\n\r\n\"\"\"\r\n\r\n dictionary\r\n 딕셔너리는 키(key)와 값(value)의 쌍을 저장할 수 있는 객체\r\n \r\n\r\n\"\"\"\r\n\r\n# 형태\r\ndictionary = {'name':'이유현','phone':'01091597160','score':100}\r\ndictionary['score']\r\n# 추가하기\r\n\r\ndictionary['speed'] = '1000'\r\nprint(dictionary)\r\n\r\n# 항목 순회하며 출력하기.\r\n\r\nfor item in dictionary.items():\r\n print(item)\r\n\"\"\"\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n plot 문제로 정리하기\r\n 1. matplotlib\r\n 1) 한글 및 음수 부호 지원\r\n 2) 기본차트 시각화 - 기본 선 스타일과 색상, x축 y축 스타일&색상, color와 marker 이용\r\n 3) 산점도, 히스토그램, 상자그래프\r\n 3) 이산형 변수 시각화 - 가로막대 그래프, 세로막대 차트, 원차트\r\n 4) subplot 차트\r\n 5) 시계열차트\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\ndata3= np.random.randn(50) # 난수\r\ndata4= np.random.randn(50).cumsum() # 난수\r\n\r\nchart.plot(data3, color='r', label='step', \r\ndrawstyle=\"steps-post\")\r\n\r\nchart.plot(data4, color='g', label='line')\r\nplt.legend(loc='best')\r\nplt.ylabel('y label')\r\nplt.xlabel('x label')\r\nplt.title('chart title')\r\nplt.show()\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sn\r\n\r\n# 문3) seaborn의 titanic 데이터셋을 이용하여 다음과 같이 단계별로 시각화하시오.\r\ntitanic = sn.load_dataset('titanic')\r\nprint(titanic.info())\r\n\r\n# <단계1> 'total_bill','tip','sex','size' 칼럼으로 서브셋 만들기 \r\ntitanic_df = titanic[['survived','pclass', 'age','fare']]\r\nprint(titanic_df.info())\r\n#sn.pairplot(data=DataFrame, hue='집단변수', kind='scatter')\r\n\r\n# <단계2> 성별(sex) 칼럼을 집단변수로 산점도행렬 시각화\r\nsn.pairplot(data=titanic_df, hue='survived')\r\nplt.show()\r\n\r\n# <단계3> 산점도행렬의 시각화 결과 해설하기\r\n'''\r\npclass : 3등석 일수록 사망비율 매우 높음 \r\npclass vs fare : 1등석 일수록 고 요금 \r\nage : 25~50세 사이에서 가장 높은 빈도, 사망과 생존 비율 비슷 \r\nage vs fare : 대체적으로 나이가 많고, 요금이 낮은 경우 사망 비율 높음\r\nfare : 비용이 저렴한 경우가 상대적으로 많은 분포\r\nfare vs age : 대체적으로 요금이 낮고, 나이가 50대 이상인 경우 사망 비율 높음 \r\n'''\r\n\r\n# survived vs age \r\n# 연령대 생존비율 : 20~40 \r\ntitanic[titanic['survived'] == 1].age.plot(kind = 'hist', color = 'blue')\r\n# 연령대 사망비율 : 20~40\r\ntitanic[titanic['survived'] == 0].age.plot(kind = 'hist', color = 'green')\r\n\r\n\r\n# 문4) seaborn의 tips 데이터셋을 이용하여 다음과 같이 단계별로 시각화하시오.\r\ntips = sn.load_dataset('tips')\r\nprint(tips.info())\r\n\r\n# <단계1> 'total_bill','tip','sex','size' 칼럼으로 서브셋 만들기\r\ntips_df = tips[['total_bill','tip','sex','size']]\r\n\r\n# <단계2> 성별(sex) 칼럼을 집단변수로 산점도행렬 시각화 \r\nsn.pairplot(data=tips_df, hue='sex')\r\nplt.show()\r\n\r\n# <단계3> 산점도행렬의 시각화 결과 해설하기\r\n\"\"\"\r\ntotal_bill : 총금액 15~20 사이가 가장 높은 빈도, 금액이 클 수록 남자 지불 \r\ntotal_bill vs tip : 대체적으로 비례관계, 총금액과 팁이 많은 경우 남자 지불\r\ntip : 팁은 1~5 사이가 가장 높은 빈도, 팁 금액이 클 수록 남자 지불 \r\ntotal_bill vs size : 행사규모가 작은 경우 여성 지불\r\nsize : 행사규모 2가 가장 높은 빈도, 특히 4일때 남자 지불 \r\nsize vs total_bill : 대체적으로 비례관계, 규모가 큰 경우 총금액이 많음 \r\n\r\n\"\"\"\r\nimport pandas as pd # object\r\nimport numpy as np # dataset\r\nimport matplotlib.pyplot as plt # plt.show() \r\n\r\n# 1. 기본 차트 시각화 \r\nser = pd.Series(np.random.randn(10)) # 1d \r\nprint(ser)\r\n\r\n# 1차원 객체 : 기본차트 - 선 그래프 \r\nser.plot(color='g')\r\nplt.show()\r\n\r\n# 2차원 객체 \r\ndf = pd.DataFrame(np.random.randn(10, 4),\r\n columns=('one','two','three','fore'))\r\n\r\nprint(df)\r\n\r\n# 기본차트 : 선 그래프\r\ndf.plot() \r\nplt.show()\r\n\r\n# 막대차트 : 세로 \r\ndf.plot(kind='bar', title = 'bar chart')\r\nplt.show()\r\n\r\n\r\n# 막대차트 : 가로 \r\ndf.plot(kind='barh', title = 'bar chart')\r\nplt.show()\r\n\r\n\r\n# 막대차트 : 가로, 누적형 \r\ndf.plot(kind='barh', title = 'barh chart', stacked=True)\r\nplt.show() \r\n\r\n\r\n# 2. dataset 이용 \r\nimport os\r\n\r\nos.chdir('C:/ITWILL/4_Python-II/data')\r\ntips = pd.read_csv('tips.csv')\r\nprint(tips.info())\r\n\r\n# 교차분할표 : 집단변수 이용 \r\n# 요일(day):행 vs 규모(size):열\r\ntips['day'].unique() # ['Sun', 'Sat', 'Thur', 'Fri']\r\ntips['size'].unique()# [2, 3, 4, 1, 6, 5]\r\n\r\ntab = pd.crosstab(index=tips['day'], columns=tips['size'])\r\nprint(tab)\r\n\r\n# 테이블 정보 \r\ntab.shape # (4, 6)\r\ntab.index # 행 이름 \r\ntab.columns # 열 이름 \r\n\r\n#tab.index = 수정 이름 \r\ntype(tab) # pandas.core.frame.DataFrame\r\n\r\nhelp(tab.plot)\r\n\r\n# size : 1, 6 제외 -> subset\r\n#obj.loc[행, 열]\r\nnew_tab = tab.loc[:, 2:5]\r\nprint(new_tab)\r\n\r\n\r\nnew_tab.plot(kind='barh', stacked=True,\r\n title = 'day and size')\r\nplt.show()\r\n\r\n\r\n\r\n\"\"\"\r\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\nplot 예제 끝~~\r\n\"\"\"\r\n\r\n\"\"\"\r\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n1. Group by : 머 대강 칼럼들을 특정 변수의 조건에 맞게 그룹화 시키는거다\r\n2. apply :\r\n3. Pivot table ---> df.pivot(index='x',columns='y',values='z')\r\n - 좌측 index(행)를 어떤 칼럼으로 설정할지\r\n - 칼럼(열)쪽을 y칼럼으로 세우고\r\n - 안에 채울 values 값 z로 설정\r\n\r\n\r\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\n\"\"\"\r\n\r\nNUMPY!!!!!!!!!!!!!\r\n 1. 배열 생성 array()\r\n - arange() : 배열 객체 반환\r\n - linspace() : 시작점과 끝점을 균일 간격으로 나눈 점들을 생성\r\n - reshape() : 행수와 열수를 조절\r\n 2. 특수 행렬 생성 zeros() : 0으로 채워진 배열, ones() : 1로 채워진 배열 ,eye() : 항등행렬\r\n \r\n 3. 난수 생성 numpy.random.normal(size = 개수)\r\n 4. 산술연산 \r\n\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n# Series Pandas의 Series는 1차원 데이터를 다루는 데 효과적인 자료구조\r\nvalues 속성을 호출하면 데이터의 배열 원소가 리턴\r\nindex 속성을 호출하면 인덱스의 정보가 리턴\r\n각각의 데이터는 [인덱스]를 이용해서 접근이 가능\r\nnumpy 함수 사용 가능\r\ndict 객체로 생성 가능\r\n\"\"\"\r\n# code 1\r\n\r\nfrom pandas import Series, DataFrame\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nprice = Series([4000, 3000, 3500, 2000])\r\nprint(price)\r\nprint(price.index)\r\nprint(price.values)\r\nprint('====================')\r\nfruit = Series([4000, 3000, 3500, 2000], \r\nindex=['apple', 'mellon','orange', 'kiwi'])\r\nprint(fruit)\r\nprint(fruit[0]) # 순번 이용 데이터 접근\r\nprint(fruit['apple']) # 인덱스 이용 데이터 접근\r\nprint(fruit[fruit>3000]) # 부울리언 식\r\nprint(\"=================\")\r\n\r\n# code 2\r\nfrom pandas import Series, DataFrame\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ngood1 = Series([4000,3500,None,2000],index = ['apple','mango','orange','kiwi'])\r\n\r\ngood2 = Series([3000,3000,3500,2000],index = ['apple','mango','orange','kiwi'])\r\n\r\nprint(pd.isnull(good1)) # NaN값 검출 none이면 True를 반환\r\nprint (good1+good2)\r\n\r\n\r\n# DataFrame\r\n\r\n\"\"\"\r\n# DataFrame은 행과 열로 구성된 2차원 데이터를 다루는 데 효과적인 자료구조\r\n일반적으로 딕셔너리 활용해서 생성\r\n입력가능한 데이터\r\n1. 2차원 ndarray\r\n2. 리스트, 튜플,dict, Series의 dict\r\n3. dict, Series의 list\r\n4. 리스트, 튜플의 리스트\r\n5. 칼럼 뽑는 방법\r\n 1) data.iloc[[행]],[열] # 행은 index\r\n\r\n\"\"\"\r\n# code 1\r\nfrom pandas import Series, DataFrame\r\n\r\nitems = {'code': [1,2,3,4,5,6],\r\n'name': ['apple','watermelon','oriental melon', 'banana', 'lemon', 'mango'],\r\n'manufacture': ['korea', 'korea', 'korea','philippines','korea', 'taiwan'],\r\n'price':[1500, 15000,1000,500,1500,700]}\r\n\r\ndata = DataFrame(items)\r\nprint(data)\r\n\r\n# 특정 컬럼만 뽑기\r\ndata1 = DataFrame(items, columns = ['code', 'price'])\r\nprint(data1)\r\nprint(data.loc[0]) # 0 행 출력 가로로 나옴\r\nprint(data.loc[:0]) # 0 행 출력 세로로 나옴\r\nprint(data.loc[[2],['name']])\r\n\r\n\r\n# 데이터 프레임 변경해보기\r\ndata.index = np.arange(1,7,1) # 1~6까지 인덱스 설정\r\ndata.columns\r\ndata = data.reindex(['1','2','3','4','5','7'],columns = ['code', 'name', 'manufacture', 'price'])\r\nprint(data.index)\r\nprint(data);\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"-------------------------------------------------------------------------------------------------------------------------------------------------------------- \"\"\"\r\n# 정규분포 생성 알고리즘\r\n\"\"\" 정규분포란? 가우시안 정규 분포 :\r\n 자연 현상에서 나타나는 숫자를 확률 모형으로 모형화할 때 가장 많이 사용되는 모형\r\n 표준편차 1배안에 전체 데이터의 약 70% 이상이 몰려있고\r\n 1.96배 안에 95% 이상이 분포된 경우\r\n \"\"\"\r\nfrom pandas import Series, DataFrame\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import font_manager, rc \r\nfrom scipy import stats\r\nimport scipy as sp \r\nfont_name = font_manager.FontProperties(fname=\"c:/Windows/Fonts/malgun.ttf\").get_name()\r\nrc('font', family=font_name)\r\nmu = 0 \r\nstd = 1\r\nrv = sp.stats.norm(mu, std) \r\nxx = np.linspace(-5, 5, 100)\r\nplt.plot(xx, rv.pdf(xx))\r\nplt.ylabel(\"확률\")\r\nplt.title(\"정규분포곡선\")\r\nplt.show() \r\nx = rv.rvs(100) # rvs 메서드로 시뮬레이션해 샘플을 얻는것\r\n\r\nprint(x)\r\n\r\n# 검정통계 , 유의확률(p-value)\r\n\"\"\"\r\n 검정(testing)은 데이터 뒤에 숨어있는 확률 변수의 분포와 모수에 대한 가설의 진 위를 정량적(quantitatively)으로 증명하는 작업\r\n \r\n 실제 모집단에서 표본 몇 십 개 또는 몇 백 개를 추출해서 그것의 분산(표본분산)이나 평균(표본평균)을 사용해야 하는 경우가 대 부분입니다.\r\n 표본수가 크지 않을 때 표본분산(표본표준편차)을 사용한 테스트는 t-분포를 이용 한다고 해서 T-test라고 합니다.\r\n 가설 증명 즉 검정의 기본적인 논리는 다음과 같습니다.\r\n 만약 가설이 맞다면 즉, 모수 값이 특정한 조건을 만족한다면 해당 확률 변수로부터 만 들어진 표본(sample) 데이터들은 어떤 규칙을 따르게 된다.\r\n 해당 규칙에 따라 표본 데이터 집합에서 어떤 숫자를 계산하면 계산된 숫자는 특정한 확률 분포를 따르게 된다. 이 숫자를 검정 통계치(test statistics)라고 하며 확률 분포를 검정 통계 분포(test statistics distribution)라고 한다. 검정 통계 분포의 종류 및 모수의 값은 처음에 정한 가설에 의해 결정된다. 이렇게 검정 통계 분포를 결정하는 최초의 가 설을 귀무 가설(Null hypothesis)이라고 한다.\r\n 데이터에 의해서 실제로 계산된 숫자, 즉, 검정 통계치가 해당 검정 통계 분포에서 나올 수 있는 확률을 계산한다. 이를 유의 확률(p-value)라고 한다.\r\n 만약 유의 확률이 미리 정한 특정한 기준 값보다 작은 경우를 생각하자. 이 기준 값을 유의 수준(significance level)이라고 하는 데 보통 1% 혹은 5% 정도의 작은 값을 지정한 다. 유의 확률이 유의 수준으로 정한 값(예 1%)보다도 작다는 말은 해당 검정 통계 분포 에서 이 검정 통계치가 나올 수 있는 확률이 아주 작다는 의미이므로 가장 근본이 되는 가설 즉, 귀무 가설이 틀렸다는 의미이다. 따라서 이 경우에는 귀무 가설을 기각(reject) 한다.\r\n 만약 유의 확률이 유의 수준보다 크다면 해당 검정 통계 분포에서 이 검정 통계치가 나 오는 것이 불가능하지만은 않다는 의미이므로 귀무 가설을 기각할 수 없다. 따라서 이 경우에는 귀무 가설을 채택(accept)한다.\r\n \r\n linspace 함수는 numpy모듈의 1차원 배열 만드는 함수\r\n x = np.linspace(start,stop,num) # num은 요소의 개수 그 사이에 몇개를 만들것인가.\r\n np.random.randit : 균일 분포의 정수 난수 1개 생서\r\n np.random.rand : 0부터 1사이의 난수 matrix array 생성\r\n np.random.randn : 가우시안 표준 정규 분포에서 난수 matrix array 생성\r\n plt.fill_between() : 두 수평 방향의 곡선 사이를 채웁니다.\r\n plt.fill_betweenx() : 두 수평 방향의 곡선 사이를 채웁니다.\r\n plt.fill() : 다각형 영역을 채웁니다.\r\n \r\n \r\n 파이썬 플랏 상세 설명 : https://blog.naver.com/nach3012/222419686483\r\n \r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import font_manager, rc \r\nfrom scipy import stats\r\nimport scipy as sp\r\n\r\nfont_name = font_manager.FontProperties(fname=\"c:/Windows/Fonts/malgun.ttf\").get_name() \r\nrc('font', family=font_name)\r\n\r\nxx1 = np.linspace(-4, 4, 100) \r\nxx2 = np.linspace(-4, -2, 100) \r\nxx3 = np.linspace(2, 4, 100)\r\n\r\nplt.fill_between(xx1, sp.stats.norm.pdf(xx1), facecolor='green', alpha=0.1)\r\nplt.fill_between(xx2, sp.stats.norm.pdf(xx2), facecolor='blue', alpha=0.35)\r\nplt.fill_between(xx3, sp.stats.norm.pdf(xx3), facecolor='blue', alpha=0.35)\r\nplt.text(-3, 0.1, \"p-value=%5.3f\" % (2*sp.stats.norm.cdf(-2)), horizontalalignment='center')\r\nplt.title(\"유의확률:0.046\") \r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "a1d71f23fcce75e8776076eaa8c1e4d4dbc5c4e2", "size": 13360, "ext": "py", "lang": "Python", "max_stars_repo_path": "basic.py", "max_stars_repo_name": "LYH-93/LYH-93.github.io", "max_stars_repo_head_hexsha": "bc40cb18c94b6781e6df37a8c6b67625ae8ae3df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic.py", "max_issues_repo_name": "LYH-93/LYH-93.github.io", "max_issues_repo_head_hexsha": "bc40cb18c94b6781e6df37a8c6b67625ae8ae3df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic.py", "max_forks_repo_name": "LYH-93/LYH-93.github.io", "max_forks_repo_head_hexsha": "bc40cb18c94b6781e6df37a8c6b67625ae8ae3df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4797891037, "max_line_length": 323, "alphanum_fraction": 0.5420658683, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 6063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.17106119801750538, "lm_q1q2_score": 0.07687364243178466}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Useful Introduction to Python, GitHub, and LaTex\n# Questions that you may be asking:\n# - What is Python?\n# - Why should I use it?\n# - Is it venemous?\n# - Why am I talking to myself?\n# \n# In this chapter, you are going to learn the answers to some of these questions and develop some basic skills. These skills will be useful in later chapters and will form a springboard so that you can dive into the ocean that is Computational Physics. The first thing that you may need is motivation, which lies in the history of scientific computing.\n# \n# ## A History\n# \n# A **computer** is a machine that can carryout sequences of arithmetic or logical operations. It requires instructions in a specific order (i.e., syntax), and space to hold intermediate/final results (i.e., memory). Prior to the 20th Century, a computer was a mechanical device that allowed users to perform arithmetic calculations quickly. An abacus is one such device:\n# \n# | ![abacus](https://upload.wikimedia.org/wikipedia/commons/a/af/Abacus_6.png) |\n# |:--:| \n# |The Chinese suanpan. The number represented on this abacus is 6,302,715,408. (wikipedia:abacus)|\n# \n# The principle of the modern computer was proposed by **Alan Turing** (1936) in his paper On Computable Numbers. Turing proposed a \"Universal Computing machine\" that is capable of computing anything that is computable by executing instructions (program) stored on tape, allowing the machine to be programmable. The fundamental concept of Turing's design is the stored program, where all the instructions for computing are stored in memory. **Von Neumann** acknowledged that the central concept of the modern computer was due to this paper.\n# \n# **Colossus** was the world's first electronic digital programmable computer, where it used a large number of valves (vacuum tubes). It had paper-tape input and was capable of being configured to perform a variety of boolean logical operations on its data. The **ENIAC** (Electronic Numerical Integrator and Computer) was the first electronic programmable computer built in the United States. Like the Colossus, a \"program\" on the ENIAC was defined by the states of its patch cables and switches. Once a program was written, it had to be mechanically set into the machine with the manual resetting of plugs and switches. \n# \n# | ![ENIAC](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Eniac.jpg/1280px-Eniac.jpg)\n# |:--:| \n# |ENIAC was the first electronic device in the U.S. and performed ballistics trajectory calculations for the United States Army. (wikipedia:computer)|\n# \n# Along with military applications, computers became the catalyst for many scientific and engineering breakthroughs. In the 1950s, IBM developed the programming language **FORTRAN** (Formula Translation) as a general-purpose, compiled imperative programming language that is especially suited to numeric computation and scientific computing. Many scientific programs were developed in FORTRAN and are still in use today in computationally intensive areas such as numerical weather prediction, finite element analysis, computational fluid dynamics, geophysics, **computational physics**, crystallography and computational chemistry.\n# \n# Before the development of disk files, text editors and terminals, programs were most often entered on a keypunch keyboard onto 80-column punched cards, one line to a card. The resulting deck of cards would be fed into a card reader to be compiled. Punched card codes included no lower-case letters or many special characters, and special versions of the IBM 026 keypunch were offered that would correctly print the re-purposed special characters used in FORTRAN. Reflecting punched card input practice, FORTRAN programs were originally written in a fixed-column format, with the first 72 columns read into twelve 36-bit words.\n# \n# | ![Punchcard](https://upload.wikimedia.org/wikipedia/commons/5/58/FortranCardPROJ039.agr.jpg)\n# |:--:| \n# |FORTRAN code on a punched card, showing the specialized uses of columns 1–5, 6 and 73–80. (wikipedia:fortran)|\n# \n\n# ## Why Python?\n# \n# Fast-forwarding from punchcards to the modern era, other computer languages (C, C++, Java) were developed to improve upon FORTRAN in terms of their usage (i.e., easier to code) and compilation speed. FORTRAN has also changed over many versions that migrated it from punchcards to completely digital files. The programming language C rivals FORTRAN for speed and has become the backbone of modern computing. Back to Python. What is it?\n# \n# Python is a scripting language, which means it takes commands in a more human-like language and translates those commands into machine code (zeros and ones). The Python interpreter does this one line at a time, but its translation into machine code is less efficient than C or FORTRAN. For applications where speed is key, Python is used as an interface while portions of the code are passed into the speedier languages. Alternatively, one can develop their Python code using C extensions for Python (or Cython).\n# \n# Scientists are quickly adopting Python within a range of fields because it is open-source (i.e., free) and much easier for students to learn. Especially if you have any prior experience in programming, where Python strips away many of the quirks from legacy languages. Due to the simplified structure of Python programs, you can easily begin programming and get to your results. \n# \n\n# ## Python Basics\n# \n# ### Create a Jupyter Notebook\n# \n# **To create a Jupyter notebook in Microsoft VS Code**: open the command palette (Windows: Ctrl + Shift + P, iOS: Command + Shift + P) and select the command \"Jupyter: Create New Blank Notebook\".\n# \n# Python programs include 3 elements: 1) import statements/libraries, 2) custom functions, and 3) regular statements. Although this document has flowing text, most Python programs are written to be as short as possible. For these examples, we are using an interactive Python mode, where code blocks are designated with \n# > In [ ]:\n# \n# for input. These codeblocks can be run and re-run with tweaks, but you need to watch out for dependencies (i.e., assumptions that some other code exists in memory). Let's start by importing a commonly used modules **numpy** and **matplotlib**\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# These import statements will allow us to use functions with the respective modules. The numpy module was developed to make managing data structures easier, while the matplotlib library introduces functions from the Matlab Plotting Library so that we can visualize our results. To produce a graph, let's first generate some data:\n\n# In[2]:\n\n\nx = np.arange(1,5,0.5)\ny = 3*x + 2\n\n\n# The first line uses the 'arange' function from numpy, where we use 'np' as a shortcut label. The 'arange' function takes in up to 3 values as input: starting value, stopping value, and step size to generate a numpy array with an interated sequence:\n# \n# >x = np.array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])\n# \n# Note that the generated values are floats (i.e., real numbers) and the final value of the array is 4.5 and **not** 5.0. Python generators typically exclude the end point. If we wanted to use integers (i.e., whole numbers) instead, then we could have used the 'range' function from pure Python without refferring to the numpy module and excluded the step size as input (e.g., range(0,5)).\n# \n# The second line generates another numpy array using the values stored in 'x'. More precisely, it makes a temporary copy of 'x', where it performs a multiplication by 3 and addition of 2 to each element of the copied array. Finally, the temporary copied array is stored as a variable called 'y'.\n# \n# >y = np.array([ 5. , 6.5, 8. , 9.5, 11. , 12.5, 14. , 15.5])\n\n# Now, we are going to make a plot of the data that we generated. To create a canvas in matplotlib, we start with the figure function and store it in a container called 'fig'. The suptitle function uses a string (i.e., array of characters) as input and sets the keyword argument fontsize equal to 16 pt font. We also introduce a container 'ax' that holds the axes for the canvas through the add_subplot function that takes a three digit number (row column index) as input.\n\n# In[3]:\n\n\nfig = plt.figure()\nfig.suptitle('My first graph', fontsize=16)\nax = fig.add_subplot(111)\nax.plot(x,y,'k.',ms=18)\n\n\n# To plot our generated data, we simply used the plot function on the axes (the Axes class inherits the plot function from the matplotlib module). The plot function used the x and y arrays to generate the points, but we also had to tell it that we wanted black points ('k.') with a markersize (ms) equal to 18 pts.\n# \n# However, we may want to make a lot of plots and do not want to copy/paste a bunch of times. To reuse our commands, we define a custom function 'create_plot' that takes the parameters we may want to vary as input.\n\n# In[4]:\n\n\ndef create_plot(x,y,color,marker,ms):\n fig = plt.figure()\n fig.suptitle('My first graph', fontsize=16)\n ax = fig.add_subplot(111)\n ax.plot(x,y,marker=marker,color=color,ms=18,lw=0)\n\n\n# Notice that Python uses a tab to delineate what should be included in the function. Now let's change the color to blue ('b'), the marker to squares ('s') and the markersize to 12 points.\n\n# In[5]:\n\n\ncreate_plot(x,y,'b','s',12)\n\n\n# We can even change the x,y values to something more complicated.\n\n# In[6]:\n\n\nx = np.arange(0,2*np.pi,0.5)\ny = 3*np.sin(x+1)-2\ncreate_plot(x,y,'r','^',1)\n\n\n# There are many options within matplotlib, where you will find some more useful than others over time. If in doubt, you can always check the **matplotlib gallery** (https://matplotlib.org/stable/gallery/index.html) or stackexchange (https://stackexchange.com/). It is likely that someone has already run into your problem/customization and other people have provided a 'possible' solution (not all solutions are good!). The last bit of customization for this section is to:\n# \n# 1. add axis labels\n# - ax.set_xlabel(*string,fontsize=22) or ax.set_ylabel(*string,fontsize=22)\n# 2. modify tick marks \n# - ax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)\n# 3. modify tick labels\n# - using ```$``` opens the latex interpreter for custom symbols (e.g., ```$\\pi$``` = $\\pi$)\n# - ax.set_xticklabels(['0','$\\pi$/2','$\\pi$','$3\\pi/2$','2$\\pi$'])\n# 4. set sensible axis limits\n# - ax.set_xlim(0,2*np.pi)\n# 5. add a legend\n# - add the keyword 'label' to the plot command and set equal to a string\n# - ax.legend(loc='upper right',fonstize=20)\n\n# In[7]:\n\n\nfig = plt.figure()\nfig.suptitle('My first graph', fontsize=16)\nax = fig.add_subplot(111)\nax.plot(x,y,marker='*',color='orange',ms=18,lw=0,label='SHO')\n\nax.set_xlabel(\"Angle (rad.)\",fontsize=22)\nax.set_ylabel(\"Amplitude (ft/s)\",fontsize=22)\nax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)\nax.set_xlim(0,2*np.pi)\nax.set_xticks([0,np.pi/2,np.pi,3.*np.pi/2.,2*np.pi])\nax.set_xticklabels(['0','$\\pi$/2','$\\pi$','$3\\pi/2$','2$\\pi$'])\nax.legend(loc='upper center',fontsize=20)\n\n\n# Figures can be saved to file using the `savefig` function, which takes the filename as an argument. Additional keyword arguments (kwargs) can be applied that alter the display of the figure (e.g., dpi = 300 sets the dots per inch to 300).\n\n# In[ ]:\n\n\nfig.savefig(\"SHO.png\",bbox_inches='tight',dpi=300)\n\n\n# ### Modules to solve problems\n# \n# There are many modules within modules, where object-oriented notation is used to access them. For example, you can generate a random number between 0--1 using the rand() function within the random module within the numpy module (i.e., np.random.rand()).\n\n# In[ ]:\n\n\nnp.random.rand()\n\n\n# Another extremely useful library for physicists is the linear algebra package in numpy. This package provides very fast routines for calculating anything having to do with matrices: eigenvalues, eigenvectors, solutions of systems of linear equations, and so on.\n# \n# >Example 1: In electronics, Kirchhoff's laws are used to solve for the currents through components in circuit networks. Applying these laws gives us systems of linear equations, which can then be expressed as matrix equations, such as:\n# \n# ![Kirchoff](Kirchoff_matrix.png)\n\n# In[ ]:\n\n\nA = np.matrix([[-13,2,4],[2,-11,6],[4,6,-15]]) #matrix is an array of an array\nB = np.array([5,-10,5])\nnp.linalg.solve(A,B)\n\n\n# ### Reading and writing data from a file\n\n# Python allows for many forms of input. There are commands to request user input manually via the terminal window, where this can be a direct request or by command line arguments. For computational physics, it is likely that you want to know how the output of a program changes with slightly different inputs or to visualize a data set. At this point manual input is impractical and cumbersome. In this section, you will learn how to read and write to data files so that you can save your work for later or prepare it for others to use. Files are created using the open() function that takes a filename and a mode as input. Here's a table detailing the different modes available to the open() function.\n# \n# | Character | Meaning |\n# | ----------- | :-----------: |\n# | 'r' | reading from a file; returns error if not found |\n# | 'w' | writing to a file; creates a new file/overwrites existing file) |\n# | 'x' | open for exclusive creation; failing if the file already exists |\n# | 'a' | open for writing; appending to the end of the file if it exists |\n# | 'b' | binary mode |\n# | 't' | text mode (default) |\n# | '+' | open for updating (reading and writing) |\n# \n# Let's generate some data using the equation for a simple pendulum:\n# \n# $\\ddot{\\theta} = \\sqrt{\\frac{g}{l}} \\theta$,\n# \n# which has the solution\n# \n# $\\theta(t) = \\theta_{max} \\sin \\left(\\sqrt{\\frac{g}{l}} t \\right)$,\n# \n# where $g$ represents the acceleration due to gravity, $l$ is the length, and $t$ is the time. Now let's define some variables.\n# \n\n# In[ ]:\n\n\ng = 9.81 #m/s^2 Earth gravity near the surface\nl = 1 #meter long string\nt = np.arange(0,10.5,0.01) #10 seconds with 0.5 sec increments\ntheta_max = 45 #maximum amplitude in degrees\nfname = \"Simple_Pendulum.txt\"\n\ntheta = theta_max*np.sin(np.sqrt(g/l)*t)\nout = open(fname,'w') #create a text file and open it for writing\nout.write(\"#time (s), theta (deg)\\n\") #write a header\n\nfor i in range(0,len(t)):\n out.write(\"%1.2f, %1.3f\\n\" % (t[i],theta[i]))\nout.close()\n\n\n# The data is written to \"Simple_Pendulum.txt\", which exists in the same directory as this Jupyter notebook. In practice, you may want to include an absolute path in the filename. Using our code from before, we will read the data from the file. Notice that we formatted the header with a \\# symbol and the lines are comma delimited. We are going to take advantage of this using the 'genfromtxt' function from numpy.\n\n# In[ ]:\n\n\nx,y = np.genfromtxt(\"Simple_Pendulum.txt\",delimiter=',',comments='#',unpack=True)\n\nfig = plt.figure()\nfig.suptitle('Simple Pendulum', fontsize=16)\nax = fig.add_subplot(111)\nax.plot(x,y,'r-',lw=3)\n\nax.set_xlabel(\"Time (s)\",fontsize=22)\nax.set_ylabel(\"Amplitude (deg)\",fontsize=22)\nax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)\nax.set_xlim(0,10)\nax.set_xticks(np.arange(0,12,2))\n\n\n# ## GitHub\n# \n# GitHub is a platform used by many disciplines to make code easier to develop, track, store, and share. The platform provides a series of [guides](https://guides.github.com/) that introduce new users through common practices on GitHub. In this section, we will focus on the [Hello World](https://guides.github.com/activities/hello-world/) guide. Throughout the course, you will develop scripts to perform different tasks and a good way to organize your work is through a GitHub repository. Repositories are free to create (as long as they are < 50 MB) and can serve as a useful place to backup your code. To start this guide, you will need to have a GitHub.com account already created.\n# \n# ### Create a repository (**repo**)\n# A repository (or repo) can contain any kind of code (python, C++, Fortran, etc), spreadsheets, data files, Jupyter notebooks, and most types of files that you can think of. To create a repository:\n# - In the upper right corner, click + and then select **New Repository**.\n# - Name your repo `hello-world` for this exercise.\n# - Adding a short description is helpful for you (and others) to get a quick idea what the repo contains.\n# - **Public** repos can be seen by anyone on the internet. Select this option once your repo is ready for the world to see. **Private** repos allow the creator more control about who is able to view the repo, where users are allowed access one-by-one.\n# - Select **Initialize this repository with a README**. Since your repos will likely be private, there is no need to add a license. A license tells others what they may or *may not* do with your public work. Academic researchers use a Creative Commons (CC) or MIT License that allow for pretty broad usage, where scientists within industry are more selective.\n# - Click **Create repository**.\n# \n# ### Create a Branch\n# Branching is the way to work on experimental parts of your repo. By default your repo has a new branch named *main*, which is what each branch eventually converges to. To create a new branch:\n# \n# - Go to your repo `hello-world`\n# - Click the drop down that says **branch:main**.\n# - Type a branch name, `readme-edits`, into the new branch text box.\n# - Select the blue **Create branch** box.\n# \n# Now you have two branches, `main` and `readme-edits`. These two branches are identical right now, but the changes you make to the `readme-edits` branch will not directly affect the `main` branch.\n# \n# ### Make and commit changes\n# \n# After creating your *readme-edits* branch, you should now be on the code-view for that branch. Let's make some edits and see what happens. Saved changes on GitHub are called commits. Each commit also contains a description explaining why a particular change was made. This is particurly useful for developing code over large periods of time or within groups. Let's make some changes to the **README.md** file and commit those to the repo:\n# - Click the **README.md** file.\n# - Click the pencil icon in the upper right corner to edit.\n# - In the editor, write a bit about yourself. What are your research interests?\n# - Write a commite message that describes your changes (e.g., \"I'm super awesome because I can make changes to my very own GitHub repo!\")\n# - Click the **Commit changes** button.\n# \n# The changes are now saved to the `readme-edits` branch, so now this branch is different than the `main` branch*.\n# \n# ### Open a Pull Request\n# \n# A pull request is a way for you (and others) to suggest changes to the *main* branch. Since you made changes to the `readme-edits` branch, you can now issue a `pull request`. A pull request will show the differences between both branches. The changes, addition, and subtraction are shown in green and red. In this process, you can also use the @mention system with other GitHub users to have discussions about the pull request and receive feedback. Now we'll open a pull request so that you can see how to review changes (although you may not do this as often for your own repos).\n# \n# - Click the **Pull Request** tab, then click the green **New pull request** button.\n# - In the **Example Comparisons** box, select the `readme-edits` branch to compare with `main`.\n# - Look over the changes between branches and make sure they are what you want. Then click the green **Create Pull Request** button.\n# - Give your pull request a title and write a brief description of your changes. Logging the changes in your edits will make it easier to diagnose problems later.\n# - Click **Create pull request**!\n# \n# ### Merge your Pull Request\n# \n# In the previous 2 sections, you made a new branch of `hello-world`, edited the branch, and submitted a pull request. The final step is to bring the changes to the `main` branch. To merge your `readme-edits` branch into `main`:\n# \n# - Click the green **Marge pull request** button to merge the changes into `main`.\n# - Click **Confirm merge**.\n# - Delete the `readme-edits` branch, since its changes have been incorporated with the **Delete branch** button in the purple box.\n# \n# ### GitHub Desktop\n# \n# The above guide can be used to create a repository through the web interface of GitHub. When working with your own repos, it is a little easier to use **GitHub Desktop**, which is a desktop application that simplifies pushing changes to the `main` branch. This requires a software install, which can be found [here](https://desktop.github.com/). After installing the software, your can:\n# \n# - Clone your repository to your local path (File --> Clone repository).\n# - Open your repo from your local path and edit your files. \n# - After saving your files in the local path, the changes will appear in GitHub Desktop (simliar to a pull request).\n# - Add a description of the changes and click commit to the *main* branch (blue button)\n# - Click the **Push origin** button (update all your changes back to the web version of GitHub)\n# \n\n# ## LaTex (Preparing your work)\n# \n# In the past, scientists had to learn two skills: scientific inquiry and typesetting. However, mathematicians developed a typesetting software, LaTex, that was more programattic, which made it easier to typeset equations within a document. In this course, you will need to communicate your results to others (especially your instructor), where you will use LaTex. To make it easier, we will use the online platform **Overleaf**. Similar to the guide for GitHub, it is assumed that you have successfully created an Overleaf account. Note that Overleaf provides its own guides that can be found [here](https://www.overleaf.com/learn/how-to/Creating_a_document_in_Overleaf).\n# \n# ### Creating a project\n# \n# Creating a project in Overleaf can be accomplished in **two** ways: 1) start a project from scratch or 2) start a project from a template. To start a project from scratch:\n# \n# - Click the green **New Project** button\n# - Select **Blank Project**\n# - Name your project\n# - Click **Create** and then the editor will open\n# \n# To start a project from a template:\n# \n# - Click the green **New Project** button\n# - Select **Academic Journal** from the Templates\n# - Find the **RevTex** tag at the bottom (collection of green tags) and Click it\n# - Select the **RevTex 4.2** template from the American Physical Society\n# \n# When preparing your class assignments, you can build your project from scratch so that you can learn more about the LaTex environment. To submit each of your projects, you will need to build from the **RevTex** template because it will import the default style for a Journal like *Physical Review*.\n# \n# ### Your 1st Document\n# \n# Open the blank project that you created in the previous section. In this project, we will create a simple working example (look [here](https://www.overleaf.com/learn/latex/Creating_a_document_in_LaTeX)). A LaTex document contains some *front* matter, a *body*, and some *back* matter. The front matter tells the LaTex compiler what kind of document you are trying to create, how should the document be formatted *globally*. The body will have the text, figures, and tables in a manner similar to most word processors. The back matter will tell the LaTex compiler how to format references or setup an Appendix.\n# \n# Here's a simple working example: \n# \n# >\\documentclass{article}\n# \n# >\\begin{document}\n# \n# >First document. This is a simple example, with no extra parameters or packages included.\n# \n# >\\end{document}\n# \n# This example will create an **article** document, adds the text, and compiles it as a *pdf* file in the right window.\n# \n# ### The Front Matter\n# \n# The *front* matter is everything before the *>\\begin{document}* line. Here, we will replace the *\\documentclass{article}* with the following:\n# \n# >\\documentclass[12pt, letterpaper]{article}\n# \n# >\\usepackage[margin=1.0in]{geometry}\n# \n# >\\usepackage[utf8]{inputenc}\n# >\n# >\\title{First document}\n# \n# >\\author{Your Name \\thanks{funded by the Overleaf team}}\n# \n# >\\date{\\today}\n# \n# Here's an explanation of what we just added:\n# \n# >\\documentclass[12pt, letterpaper]{article}\n# \n# \n# This defines the type of document with some additional parameters inside brackets that are comma-separated can be passed to the command. The extra parameters set the font size (12pt) and the paper size (letterpaper). Note that Overleaf uses a European LaTeX distribution, which produces documents in A4 size by default, so letterpaper is important. Another important parameter that can be passed to the \\documentclass command is twocolumn if you want your text in a two-column format and twoside for two-side paper sheet printing. \n# \n# \n# >\\usepackage[margin=1.0in]{geometry}\n# \n# \n# This defines the page margins. Everything you submit should have 1 inch margins. More detail about paper size, orientation, and margins can be found [here](https://www.overleaf.com/learn/latex/Page_size_and_margins)\n# \n# >\\usepackage[utf8]{inputenc}\n# \n# \n# This is the encoding for the document to allow special characters beyond ASCII to be used in the text. It can be omitted or changed to another encoding but utf-8 is recommended. \n# \n# The next three lines are self-descriptive. But you will need the *\\maketitle* **after** the \\begin{document} for those items to appear.\n# \n# ### The Body\n# \n# The body is similar to what you would find in a normal word processor. The first element to add to the body is the *abstract*. An abstract informs the reader what will follow in the rest of the document. For your class projects, this will be a <250 word summary of your work. In your class assignments, you can write a summary of what you learned so that when *future* you comes back to it, it will hopefully make sense. To create an abstract:\n# \n# >\\begin{abstract}\n# \n# >This is a simple paragraph at the beginning of the document. A brief introduction to the main subject.\n# \n# >\\end{abstract}\n# \n# you must create an abstract environment. Environments (e.g., abstract, figure, table, equation) always have a \\begin and an \\end statement to tell the LaTex compiler that it needs to do something different here and for how long.\n# \n# There are other elements that in the body that **don't** need an environment because they are self explanatory to the compiler when to stop. For example, you can organize the body using sections, subsections, subsubsections, etc. Although an environment is not required, you do need a `\\` to tell the compiler that it isn't really text either.\n# \n# >\\section{Introduction}\n# \n# >\\section{Methods}\n# \n# >\\subsection{Newton's 1st Law}\n# \n# >\\subsubsection{Einstein's Theory of General Relativity}\n# \n# >\\section{Results}\n# \n# In the above examples:\n# \n# - The first section is the Introduction and it will be enumerated starting from 1. The LaTex compiler will know when the Introduction ends when it encounters the next \\section command.\n# - The second section called Methods (enumerated with 2) has a subsection called Newton's 1st Law. Subsections are then enumerated with a \".#\", where the above subsection is 2.1. Subsubsections will gain an additional \".#\" so that it will numbered 2.1.1. \n# - The third section (enumerated with 3) tells the compiler to go back to the previous level in the tree.\n# \n# Between section commands, this is where the main text will appear. In contrast to a word processor (like Word), LaTex allows for inline commands. The most common inline commands are:\n# \n# - Enter math mode with \\$ signs. Suppose you need the greek letter $\\alpha$, then you can easily add it to your text by placing the \\alpha between \\$ \\$. This is less cumbersome than having to define a macro in Word. Anything that you could do in an equation, can be done in math mode (e.g., \\frac{1}{2}x^2 in between \\$ signs appears as $\\frac{1}{2}x^2$)\n# - Cite a reference. This will be explained more later.\n# - Add a comment to the writer using \\%. Everything on a line that comes after \\% will not appear in the pdf document, but can serve as a note for later.\n# - You can add text formatting for **bold**, *italics*, or $\\texttt{texttype}$ using: \\textbf, \\textit, or \\texttt.\n# \n# Figures and tables are created using an environment (recall that this means begin and end statements). For many of the extra features for figures, you will need to add `\\usepackage{graphicx}` to the front matter. Figures and tables have similar structures as you can see in these basic examples:\n# \n# >\\begin{figure}[!h]\n# \n# >\\centering\n# \n# >\\includegraphics[width=\\linewidth]{filename.png}\n# \n# >\\caption{This is the figure caption, which describes basic aspects of the figure to the reader. \\label{fig:Fig1}}\n# \n# >\\end{figure}\n# \n# and\n# \n# >\\begin{table}[!h]\n# \n# >\\centering\n# \n# >\\begin{tabular}{c|c|c}\n# \n# >\\hline\n# \n# >cell11 & cell12 & cell13 \\ \\\n# \n# >cell21 & cell22 & cell23 \\ \\\n# \n# >cell31 & cell32 & cell33 \n# \n# >\\end{tabular}\n# \n# >caption{This is a table caption, which describes the basic apsects of the table or gives the table a title. \\label{tab:Tab1}}\n# \n# >\\end{table}\n# \n# The figure and table environment have a [] after the begin statement, where positioning arguments are placed (e.g., !=override default, h=here, t=top of page, b=bottom of page). This is followed by \\centering, which tells the LaTeX compiler to place the figure/table in the center of the page (<------center------->). The figure environment relies on the `\\includegraphics` command from the graphicx package, which this has a [] for arguments that tell the LaTeX compiler how to scale the figure. In the above example, the figure is scaled so that the width of the figure spans an entire line. The {} after \\includegraphics holds the filename of the image (e.g., `filename.png`), where LaTex can handle many filetypes (e.g., png, jpg, and pdf are the most common). The table environment is different in that it holds *tabular* environment within *table* environment. The tabular environment has arguments {} that tell the LateX compiler: \n# \n# - the number of columns (implicitly),\n# - the alignment within columns (explicitly), and\n# - the borders between columns. \n# \n# The columns can be left (l), center (c), or (r) aligned, where the total number of these characters indicates the number of columns (3l's = 3 columns left aligned). The \\hline command draws a horizontal line that spans the width of the table. The data within the table is separated using the `&` symbol and a row is terminated with `\\\\`. The last row **doesn't** need to be terminated with `\\\\` and the `\\end{tabular}` must follow on the next line.\n# \n# Both figures and tables use the *caption* environment to hold the description and a *label* environment so that the figure/table can be dynamically referenced in the text (using `\\ref{fig:Fig1}` or `\\ref{tab:Tab1}`). The beauty of LaTex is that the referencing system keeps track of the figure and table numbering so that if the order of tables are switched, then the numbering is updated with the next compilation. Finally, both figures and tables **require** an \\end statement.\n# \n# The LaTex compiler will abort or crash if a given environment does not have matching {} or begin/end statements. This is usually indicated in the compilation log (upper right button **View Logs**).\n# \n# ### The Back Matter\n# \n# The back matter contains supplementary information to the body (e.g., acknowledgments, references, appendices). The acknowledgments (**note the spelling**) is an environment so it needs a \\begin{acknowledgments} and an \\end{ackowledgments}, where this section is where you would thank particular individuals/institutions that aided in the completion of the project (e.g., converstations, resources, proofing). \n# \n# An appendix is started with the `\\appendix` command, which behaves much like the body but includes supplementary material (e.g., a derivation of an equation, how a new method was verified) and it's labeled with letters (A,B,C,...). For you, this is where you can put the code that you generate using the \\verbatim environment. Addtional guides on how to include code in Latex can be found [here](https://www.overleaf.com/learn/latex/Code_listing).\n# \n# In addition to the ease of generating equations, LaTex is preferred because it makes referencing easier too with BibTex. At the end of your document, references are included by telling LaTex the referencing style (e.g., apsrev4-2.bst for *Physical Review*) and a database of references (e.g., references.bib) through supplemental files. You must include the following for the references:\n# \n# >\\bibliographystyle{style_filename.bst}\n# \n# >\\bibliography{reference_filename.bib}\n# \n# The reference database (*.bib file) will contain entries like the following:\n# \n# ```\n# @ARTICLE{Berman1983,\n# author = \"Berman, Jr., G. P. and Izrailev, Jr., F. M.\",\n# title = \"Stability of nonlinear modes\",\n# journal = \"Physica D\",\n# volume = \"88\", \n# pages = \"445\",\n# year = \"1983\",\n# }\n# ```\n# where the `Berman1983` is a label used for the inline citation command within the body (e.g., \\cite{Berman1983}). The quotation marks for each field tell BibTex not to change the formatting (i.e., captialization). There are different types of environments that correspond to different references (e.g., ARTICLE, BOOK, INPROCEEDINGS, etc.). Remember that environments require an opening { and closing }.\n# \n# The inline citations have more variations within Astronomy because that community uses the author (year) referencing style, while Physical review uses a [number] style. In this course, you will use the latter.\n\n# ## Problems\n# - Complete the following problems in a Jupyter notebook, where you will save your results as an external file (*.png).\n# - Create a LaTex document with:\n# - an abstract summary\n# - sections for each problem that state the problem, summarize what you did, and display the results\n# - include a reference for each solution (this can be textbooks)\n# \n# 1. Graph both of the following functions on a single figure, with a usefully sized scale.\n# \n# a. $x^4e^{-2x}$\n# \n# b. $[x^2e^{-x}\\sin(x^2)]^2$\n# 2. The file Ba137.txt contains two columns. The first is counts from a Geiger counter, and the second is time in seconds.\n# \n# a. Make a useful graph of this data.\n# \n# b. If this data follows an exponential curve, then plotting the natural log of the data (or plotting the raw data on a logrithmic scale) will result in a straight line. Determine whether this is the case, and explain your conclusion with an appropriate graph.\n# 3. The data in the file Ba137.txt is actual data from a radioactive decay experiment; the first column is the number of decays $N$, the second is the time $t$ in seconds. We'd like to know the half-life $t_{1/2}$ of $^{137}$Ba. It should follow the decay equation\n# $N = N_oe^{-\\lambda t}$\n# where $\\lambda = \\log(2)/\\log(t_{1/2})$. Using the techniques you've learned in this notebook, load the data from file Ba137.txt into appropriately-named variables. Experiment with different values of $N_o$ and $\\lambda$ to create a plot of the resulting equation on top of the data. What is your best estimate for $t_{1/2}$?\n# 4. The normal modes and angular frequencies of those modes for a linear system of four coupled oscillators of mass m, separated by springs of equal strength k, are given by the eigenvectors and eigenvalues of M, shown below. Find the eigenfrequencies (Try [linalg.eig](https://numpy.org/doc/stable/reference/generated/numpy.linalg.eig.html#numpy.linalg.eig) from numpy).\n# \n# ![Coupled_Oscillator](Coupled_Oscillator_matrix.png)\n# 5. Create a single plot that shows separate graphs of position, velocity, and acceleration for an object in free-fall. Your plot should have a single horizontal time axis and separate stacked graphs showing position, velocity, and acceleration each on their own vertical axis. The online matplotlib gallery will probably be helpful! Print the graph, with your name in the title.\n", "meta": {"hexsha": "fb330716d007bad618fdc9ff326d080020599c09", "size": 36452, "ext": "py", "lang": "Python", "max_stars_repo_path": "_build/jupyter_execute/courseware/Chapter_1/Gentle_Introduction.py", "max_stars_repo_name": "saturnaxis/PHYS3820_Book", "max_stars_repo_head_hexsha": "e6ead8c5353c7cfacba58376d259f6c3a11b0b3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_build/jupyter_execute/courseware/Chapter_1/Gentle_Introduction.py", "max_issues_repo_name": "saturnaxis/PHYS3820_Book", "max_issues_repo_head_hexsha": "e6ead8c5353c7cfacba58376d259f6c3a11b0b3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_build/jupyter_execute/courseware/Chapter_1/Gentle_Introduction.py", "max_forks_repo_name": "saturnaxis/PHYS3820_Book", "max_forks_repo_head_hexsha": "e6ead8c5353c7cfacba58376d259f6c3a11b0b3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-17T23:19:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T23:19:38.000Z", "avg_line_length": 69.4323809524, "max_line_length": 946, "alphanum_fraction": 0.7368319982, "include": true, "reason": "import numpy,from numpy", "num_tokens": 9104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864514886966624, "lm_q2_score": 0.2200070997458932, "lm_q1q2_score": 0.07670440804329044}} {"text": "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.11.3\n# kernelspec:\n# display_name: Python 3\n# name: python3\n# ---\n\n# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"POrA585UFLms\"\n#\n#\n# ![GitHub](https://img.shields.io/github/license/probml/pyprobml)\n#\n# Colab authors: Kevin P. Murphy (murphyk@gmail.com) and Mahmoud Soliman (mjs@aucegypt.edu)\n#\n#\n\n# + id=\"I3CEU8u0FQR0\"\n# Attribution \n# This notebook is based on the following: \n# https://github.com/mjsML/VizDoom-Keras-RL\n# https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/rl/ipynb/actor_critic_cartpole.ipynb\n\n# + id=\"qEYlbLuzFh_b\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b0661fbe-0e44-4a7a-ae7b-d5c081893257\"\n# Imports\nfrom tensorflow.python.client import device_lib\nfrom psutil import virtual_memory\nimport cv2\nfrom google.colab.patches import cv2_imshow\n# %tensorflow_version 2.x\nimport tensorflow as tf\nimport os\n\n\nfrom sklearn.neighbors import KNeighborsClassifier as KNN\nfrom sklearn.model_selection import cross_val_score\n\n\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom IPython import display\nfrom matplotlib import pyplot as plt\n\nimport numpy as np\n\nimport pathlib\nimport shutil\nimport tempfile\n\nfrom tqdm import tqdm\n\n# + id=\"X_8KoI6UFkRo\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"0055b9e3-d953-4304-830f-ad9fdd54c2e0\"\n#title Hardware check \n\n\n\ndef find_accelerator():\n \n mem = virtual_memory()\n devices=device_lib.list_local_devices()\n RAM=\"Physical RAM: {:.2f} GB\".format(mem.total/(1024*1024*1024))\n try:\n tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n device=[\"TPU at \"+str(tpu.cluster_spec().as_dict()['worker'])] \n except ValueError:\n device =[d.physical_device_desc for d in devices if d.device_type==\"GPU\"]\n if not device:\n return None, RAM\n return device , RAM \n\na,r=find_accelerator()\nprint(\"Please make sure that the statement below says Accelerator found\")\nprint(\"Accelerator found:\",a,r)\n\n\n\n# + id=\"w3V-stpMFlJN\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"5f55dbeb-d950-4b08-b707-018a03c05f3a\"\n#title Install the extra required packages if any\n# Installation of libs as per \n# https://stackoverflow.com/questions/50667565/how-to-install-vizdoom-using-google-colab\n\n# %%bash\n# Install deps from \n# https://github.com/mwydmuch/ViZDoom/blob/master/doc/Building.md#-linux\n\napt-get install build-essential zlib1g-dev libsdl2-dev libjpeg-dev \\\nnasm tar libbz2-dev libgtk2.0-dev cmake git libfluidsynth-dev libgme-dev \\\nlibopenal-dev timidity libwildmidi-dev unzip\napt-get install libboost-all-dev\napt-get install liblua5.1-dev\n\n# + [markdown] id=\"M5vmaF61ZvV5\"\n# #Partially observed Markov decision processes (POMDPs) \n# We will start by exploring POMDPs , the states of the environment, $z_{t}$ , are hidden from the agent. The agent gets to see partial observations derived from the hidden state, which we denote by\n# $s_{t} \\in \\mathcal{S}$ these are sampled from the observation model, $p(s_{t}|z_{t})$.\n#\n# In this example we will work with ViZDoom and Deep Recurrent Q Network.\n#\n# Note that this is a quick overview example, the details will be discussed later.\n\n# + [markdown] id=\"JBTCb79f72TU\"\n# ## Deep Recurrent Q Network\n\n# + id=\"Q0npOg2hPfrF\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"70d73c24-44f4-466b-ed6b-a338474c9b2c\"\n#title Install ViZDoom... takes few mins\n\n# !pip install vizdoom\n\n\n# + id=\"5HSk5mAdPbIv\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"8480df6f-678c-46fd-c051-309b828bc49a\"\n#title Clone ViZDoom-Keras-RL repo and imports\n# Clone VizDoom-Keras-RL\n# !git clone https://github.com/mjsML/VizDoom-Keras-RL.git\n# %cd /content/VizDoom-Keras-RL\nfrom __future__ import print_function\n\nimport skimage as skimage\nfrom skimage import transform, color, exposure\nfrom skimage.viewer import ImageViewer\nimport random\nfrom random import choice\nimport numpy as np\nfrom collections import deque\nimport time\n\nimport json\nfrom keras.models import model_from_json\nfrom keras.models import Sequential, load_model, Model\nfrom keras.layers.wrappers import TimeDistributed\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten, RepeatVector, Masking\nfrom keras.layers import Convolution2D, Dense, Flatten, MaxPooling2D, Input, AveragePooling2D, Lambda, Activation, Embedding\n#tf.keras.layers.Concatenate(axis=1)([x, y])\nfrom keras.layers.recurrent import LSTM, GRU\n#from keras.optimizers import SGD, Adam, rmsprop\nfrom keras.optimizers import SGD, Adam\nfrom keras import backend as K\n\nfrom vizdoom import DoomGame, ScreenResolution\nfrom vizdoom import *\nimport itertools as it\nfrom time import sleep\nimport tensorflow as tf\n\nfrom networks import Networks\n\n\n# + id=\"7Pqux1c-Trj4\"\n#title Setup ViZDoom with defend the center scenario\n\n#TF2 TF1 compatibility \nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.compat.v1.Session(config=config)\ntf.compat.v1.keras.backend.set_session(sess)\n\nfrom drqn import ReplayMemory,DoubleDQNAgent,preprocessImg\n\ngame = DoomGame()\ngame.load_config(\"/content/VizDoom-Keras-RL/defend_the_center.cfg\")\ngame.set_sound_enabled(True)\ngame.set_screen_resolution(ScreenResolution.RES_640X480)\ngame.set_window_visible(False)\ngame.init()\n\ngame.new_episode()\ngame_state = game.get_state()\n\nmisc = game_state.game_variables # [KILLCOUNT, AMMO, HEALTH]\nprev_misc = misc\n\naction_size = game.get_available_buttons_size()\n\nimg_rows, img_cols = 64, 64\nimg_channels = 3 # Color channel\ntrace_length = 4 # Temporal Dimension\n\nstate_size = (trace_length, img_rows, img_cols, img_channels)\nagent = DoubleDQNAgent(state_size, action_size, trace_length)\n\nagent.model = Networks.drqn(state_size, action_size, agent.learning_rate)\nagent.target_model = Networks.drqn(\n state_size, action_size, agent.learning_rate)\n\ns_t = game_state.screen_buffer # 480 x 640\ns_t = preprocessImg(s_t, size=(img_rows, img_cols))\n\nis_terminated = game.is_episode_finished()\n\n# + id=\"KEOjhw2tR1zl\"\n#title Start training DRQN Agent\nepsilon = agent.initial_epsilon\nGAME = 0\nt = 0\nmax_life = 0 # Maximum episode life (Proxy for agent performance)\nlife = 0\nepisode_buf = [] # Save entire episode\n\n# Buffer to compute rolling statistics\nlife_buffer, ammo_buffer, kills_buffer = [], [], []\n\nwhile not game.is_episode_finished():\n\n loss = 0\n Q_max = 0\n r_t = 0\n a_t = np.zeros([action_size])\n\n # Epsilon Greedy\n if len(episode_buf) > agent.trace_length:\n # 1x8x64x64x3\n state_series = np.array(\n [trace[-1] for trace in episode_buf[-agent.trace_length:]])\n state_series = np.expand_dims(state_series, axis=0)\n action_idx = agent.get_action(state_series)\n else:\n action_idx = random.randrange(agent.action_size)\n a_t[action_idx] = 1\n\n a_t = a_t.astype(int)\n game.set_action(a_t.tolist())\n skiprate = agent.frame_per_action\n game.advance_action(skiprate)\n\n game_state = game.get_state() # Observe again after we take the action\n is_terminated = game.is_episode_finished()\n\n # each frame we get reward of 0.1, so 4 frames will be 0.4\n r_t = game.get_last_reward()\n\n if (is_terminated):\n if (life > max_life):\n max_life = life\n GAME += 1\n life_buffer.append(life)\n ammo_buffer.append(misc[1])\n kills_buffer.append(misc[0])\n print(\"Episode Finish \", misc)\n game.new_episode()\n game_state = game.get_state()\n misc = game_state.game_variables\n s_t1 = game_state.screen_buffer\n\n s_t1 = game_state.screen_buffer\n misc = game_state.game_variables\n s_t1 = preprocessImg(s_t1, size=(img_rows, img_cols))\n\n r_t = agent.shape_reward(r_t, misc, prev_misc, t)\n\n if (is_terminated):\n life = 0\n else:\n life += 1\n\n # update the cache\n prev_misc = misc\n\n # Update epsilon\n if agent.epsilon > agent.final_epsilon and t > agent.observe:\n agent.epsilon -= (agent.initial_epsilon -\n agent.final_epsilon) / agent.explore\n\n # Do the training\n if t > agent.observe:\n Q_max, loss = agent.train_replay()\n\n # save the sample to episode buffer\n episode_buf.append([s_t, action_idx, r_t, s_t1])\n\n if (is_terminated):\n agent.memory.add(episode_buf)\n episode_buf = [] # Reset Episode Buf\n\n s_t = s_t1\n t += 1\n\n # save progress every 10000 iterations\n if t % 10000 == 0:\n print(\"Now we save model\")\n agent.model.save_weights(\"./models/drqn.h5\", overwrite=True)\n\n # print info\n state = \"\"\n if t <= agent.observe:\n state = \"observe\"\n elif t > agent.observe and t <= agent.observe + agent.explore:\n state = \"explore\"\n else:\n state = \"train\"\n\n if (is_terminated):\n print(\"TIME\", t, \"/ GAME\", GAME, \"/ STATE\", state,\n \"/ EPSILON\", agent.epsilon, \"/ ACTION\", action_idx, \"/ REWARD\", r_t,\n \"/ Q_MAX %e\" % np.max(Q_max), \"/ LIFE\", max_life, \"/ LOSS\", loss)\n\n # Save Agent's Performance Statistics\n if GAME % agent.stats_window_size == 0 and t > agent.observe:\n print(\"Update Rolling Statistics\")\n agent.mavg_score.append(np.mean(np.array(life_buffer)))\n agent.var_score.append(np.var(np.array(life_buffer)))\n agent.mavg_ammo_left.append(np.mean(np.array(ammo_buffer)))\n agent.mavg_kill_counts.append(np.mean(np.array(kills_buffer)))\n\n # Reset rolling stats buffer\n life_buffer, ammo_buffer, kills_buffer = [], [], []\n\n # Write Rolling Statistics to file\n with open(\"statistics/drqn_stats.txt\", \"w\") as stats_file:\n stats_file.write('Game: ' + str(GAME) + '\\n')\n stats_file.write('Max Score: ' + str(max_life) + '\\n')\n stats_file.write('mavg_score: ' +\n str(agent.mavg_score) + '\\n')\n stats_file.write(\n 'var_score: ' + str(agent.var_score) + '\\n')\n stats_file.write('mavg_ammo_left: ' +\n str(agent.mavg_ammo_left) + '\\n')\n stats_file.write('mavg_kill_counts: ' +\n str(agent.mavg_kill_counts) + '\\n')\n\n\n# + [markdown] id=\"EFHwTMtjtrpI\"\n# # Fully observed Markov decision processes (MDPs)\n# Now we explore fully observed Markov decision process.\n#\n# In a fully observable problem the observed state is equal to the hidden state (i.e., $s_{t}=z_{t}$). \n#\n# In this case, the POMDP reduces to a simpler model known as a Markov decision process or MDP\n#\n\n# + [markdown] id=\"PnFH2ojv7X6i\"\n#\n# ## Actor Critic Method\n# As an agent takes actions and moves through an environment, it learns to map the observed state of the environment to two possible outputs:\n#\n# **Recommended action:** \n#\n# A probabiltiy value for each action in the action space. The part of the agent responsible for this output is called the actor.\n#\n#\n# **Estimated rewards in the future:** \n#\n# Sum of all rewards it expects to receive in the future. The part of the agent responsible for this output is the critic.\n#\n# Agent and Critic learn to perform their tasks, such that the recommended actions from the actor maximize the rewards.\n#\n#\n# **CartPole-V0**\n#\n# A pole is attached to a cart placed on a frictionless track. The agent has to apply force to move the cart. It is rewarded for every time step the pole remains upright. The agent, therefore, must learn to keep the pole from falling over.\n\n# + id=\"6UfvC4ni0Zan\"\n#@title Imports\nimport gym\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n# Configuration parameters for the whole setup\nseed = 42\ngamma = 0.99 # Discount factor for past rewards\nmax_steps_per_episode = 10000\nenv = gym.make(\"CartPole-v0\") # Create the environment\nenv.seed(seed)\neps = np.finfo(np.float32).eps.item() # Smallest number such that 1.0 + eps != 1.0\n\n# + id=\"ay_fSFKW0oxp\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 223} outputId=\"ff37bd81-65b4-4a63-91c5-c17ef635107a\"\n#@title Define Model\nnum_inputs = 4\nnum_actions = 2\nnum_hidden = 128\n\ninputs = layers.Input(shape=(num_inputs,))\ncommon = layers.Dense(num_hidden, activation=\"relu\")(inputs)\naction = layers.Dense(num_actions, activation=\"softmax\")(common)\ncritic = layers.Dense(1)(common)\n\nmodel = keras.Model(inputs=inputs, outputs=[action, critic])\n\n# + id=\"uHyJ3w6n6Fdn\" cellView=\"form\"\n#@title Train model\noptimizer = keras.optimizers.Adam(learning_rate=0.01)\nhuber_loss = keras.losses.Huber()\naction_probs_history = []\ncritic_value_history = []\nrewards_history = []\nrunning_reward = 0\nepisode_count = 0\n\nwhile True: # Run until solved\n state = env.reset()\n episode_reward = 0\n with tf.GradientTape() as tape:\n for timestep in range(1, max_steps_per_episode):\n # env.render(); Adding this line would show the attempts\n # of the agent in a pop up window.\n\n state = tf.convert_to_tensor(state)\n state = tf.expand_dims(state, 0)\n\n # Predict action probabilities and estimated future rewards\n # from environment state\n action_probs, critic_value = model(state)\n critic_value_history.append(critic_value[0, 0])\n\n # Sample action from action probability distribution\n action = np.random.choice(num_actions, p=np.squeeze(action_probs))\n action_probs_history.append(tf.math.log(action_probs[0, action]))\n\n # Apply the sampled action in our environment\n state, reward, done, _ = env.step(action)\n rewards_history.append(reward)\n episode_reward += reward\n\n if done:\n break\n\n # Update running reward to check condition for solving\n running_reward = 0.05 * episode_reward + (1 - 0.05) * running_reward\n\n # Calculate expected value from rewards\n # - At each timestep what was the total reward received after that timestep\n # - Rewards in the past are discounted by multiplying them with gamma\n # - These are the labels for our critic\n returns = []\n discounted_sum = 0\n for r in rewards_history[::-1]:\n discounted_sum = r + gamma * discounted_sum\n returns.insert(0, discounted_sum)\n\n # Normalize\n returns = np.array(returns)\n returns = (returns - np.mean(returns)) / (np.std(returns) + eps)\n returns = returns.tolist()\n\n # Calculating loss values to update our network\n history = zip(action_probs_history, critic_value_history, returns)\n actor_losses = []\n critic_losses = []\n for log_prob, value, ret in history:\n # At this point in history, the critic estimated that we would get a\n # total reward = `value` in the future. We took an action with log probability\n # of `log_prob` and ended up recieving a total reward = `ret`.\n # The actor must be updated so that it predicts an action that leads to\n # high rewards (compared to critic's estimate) with high probability.\n diff = ret - value\n actor_losses.append(-log_prob * diff) # actor loss\n\n # The critic must be updated so that it predicts a better estimate of\n # the future rewards.\n critic_losses.append(\n huber_loss(tf.expand_dims(value, 0), tf.expand_dims(ret, 0))\n )\n\n # Backpropagation\n loss_value = sum(actor_losses) + sum(critic_losses)\n grads = tape.gradient(loss_value, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n # Clear the loss and reward history\n action_probs_history.clear()\n critic_value_history.clear()\n rewards_history.clear()\n\n # Log details\n episode_count += 1\n if episode_count % 10 == 0:\n template = \"running reward: {:.2f} at episode {}\"\n print(template.format(running_reward, episode_count))\n\n if running_reward > 195: # Condition to consider the task solved\n print(\"Solved at episode {}!\".format(episode_count))\n break\n\n\n# + [markdown] id=\"H0hXYOtJ6NbJ\"\n# ### Visualizations\n#\n#\n# In early stages of training:\n#\n#\n# ![Imgur](https://i.imgur.com/5gCs5kH.gif)\n#\n#\n# In later stages of training:\n#\n#\n# ![Imgur](https://i.imgur.com/5ziiZUD.gif)\n", "meta": {"hexsha": "bb55659da7bd8c6d1013a8e7170fc2282eb5f0e7", "size": 16821, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks-text-format/rl_demos.py", "max_stars_repo_name": "arpitvaghela/probml-notebooks", "max_stars_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 166, "max_stars_repo_stars_event_min_datetime": "2021-07-16T17:33:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:35:34.000Z", "max_issues_repo_path": "notebooks-text-format/rl_demos.py", "max_issues_repo_name": "arpitvaghela/probml-notebooks", "max_issues_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2021-07-21T16:31:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:13.000Z", "max_forks_repo_path": "notebooks-text-format/rl_demos.py", "max_forks_repo_name": "arpitvaghela/probml-notebooks", "max_forks_repo_head_hexsha": "32ecb309dd474b989fd1c6ce4ad6dab7a25bbead", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48, "max_forks_repo_forks_event_min_datetime": "2021-07-17T08:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:36:18.000Z", "avg_line_length": 33.9133064516, "max_line_length": 239, "alphanum_fraction": 0.6881873848, "include": true, "reason": "import numpy", "num_tokens": 4366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.17328821233352104, "lm_q1q2_score": 0.0765367230405394}} {"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\n# \n# Roulette - Klasse von zufall \n# \n \n#\n# This file is part of zufall\n#\n#\n# Copyright (c) 2019 Holger Böttcher hbomat@posteo.de\n#\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\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\nfrom sympy import Rational, Integer, nsimplify\nfrom sympy.core.compatibility import iterable\nfrom sympy.printing.latex import latex\n\nfrom zufall.lib.objekte.basis import ZufallsObjekt\nfrom zufall.lib.objekte.gleich_verteilung import GleichVerteilung\nfrom zufall.lib.objekte.datenreihe import DatenReihe\nfrom zufall.lib.funktionen.graf_funktionen import verlauf as verlauf_grafik\n\nfrom zufall.lib.objekte.ausnahmen import ZufallError\n\n\n\n# Roulette - Klasse \n# -----------------\n\t\nclass Roulette(ZufallsObjekt): \n \"\"\"\n\t\nRoulette - Spiel\n\t\n**Erzeugung** \n\n Roulette( ) \n \t\t \n \"\"\"\t\t\t\n\t\t\t\n def __new__(cls, *args, **kwargs): \n\t\t\t\n if kwargs.get(\"h\") in (1, 2, 3, 4): \n roulette_hilfe(kwargs[\"h\"])\t\t\n return\n \n cls.colonne1 = {1,4,7,10,13,16,19,22,25,28,31,34} \n cls.colonne2 = {2,5,8,11,14,17,20,23,26,29,32,35} \t\t\t \n cls.colonne3 = {3,6,9,12,15,18,21,24,27,30,33,36}\t\t\t\n cls.douze_premier = set(range(1, 13))\t\t\t \n cls.douze_milieu = set(range(13, 25))\t\t\t\n cls.douze_dernier = set(range(25, 37))\t\t\t \n cls.pair = set(range(2, 37, 2)) \n cls.impair = set(range(1, 36, 2))\t\t\t\n cls.rouge = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36}\t\t\t\n cls.noir = set(range(1, 37)).difference(cls.rouge)\t\t\n cls.manque = set(range(1, 19))\t\t\t\n cls.passe = set(range(19, 37))\t\t\t\n\t\t\n return ZufallsObjekt.__new__(cls)\n\t\t\t\t\t\n\t\t\t\n def __str__(self): \n return \"Roulette\"\n\t\t\n\t\t\n\t\t\n# Eigenschaften + Methoden\n# ------------------------\n\n @property\n def omega(self):\n \"\"\"Ergebnismenge\"\"\"\t\n return set(range(37))\n\t\t\n @property\n def regeln(self):\n \"\"\"Regeln für Roulettespiel\"\"\"\t\n\t\t\n print(\"\\nRoulette - Glücksspiel\\n\")\n print(\"Eine Kugel wird in eine sich drehende Scheibe geworfen. Sie landet in \") \n print(\"einem der Felder 0 bis 36, die auf der Scheibe in bunter Reihenfolge\")\n print(\"angeordnet sind (Gewinnfeld)\\n\")\n print(\"Auf dem Spielbrett setzt man Spielmarken (Chips) und gewinnt, wenn die \") \n print(\"Vorhersage eintrifft, das heißt, wenn das Gewinnfeld durch die getrof-\")\n print(\"fene Wahl erfaßt wird; zu den Setzmöglichkeiten siehe Hilfeseite\\n\")\n print(\"Wenn die Vorhersage nicht eintrifft, ist der gesetzte Chip verloren \") \n print(\"Das entspricht einer Gewinnquote von -1 : 1\\n\")\n return\t\t\n\t\t\n @property\n def brett(self):\n \"\"\"Spielbrett / -tisch (Abbildung)\"\"\"\t\t\t\n\t\t\n def pline(x, y):\n return plt.plot(x, y, color=(0,0,0), lw=0.8)\n\n def prot(x, y, t):\n return ax.text(x, y, t, fontsize=9, horizontalalignment='center', \n verticalalignment='center', color=(1,0,0), \n fontname='Times New Roman')\n\n def pblack(x, y, t):\n return ax.text(x, y, t, fontsize=9, horizontalalignment='center', \n verticalalignment='center', color=(0,0,0),\n fontname='Times New Roman')\n\n def punt(x, y):\n ax.text(x, y, '12', fontsize=6, horizontalalignment='center', \n verticalalignment='center', color=(0,0,0),\n fontname='Times New Roman')\n\n dx, dy = 1.5, 1.5\n fig = plt.figure(figsize=(3, 4))\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['top'].set_visible(False)\t\t\n ax.spines['bottom'].set_visible(False)\t\t\n ax.spines['right'].set_visible(False)\t\t\n ax.spines['left'].set_visible(False)\t\t\n ax.set_xticks([])\n plt.axes().xaxis.set_ticks_position('none')\n ax.set_yticks([])\n plt.axes().yaxis.set_ticks_position('none')\n plt.xlim(0, 10*dx)\n plt.ylim(-0.1, 15*dy)\n pline([3*dx, 6*dx, 6*dx, 3*dx, 3*dx], [0, 0, 14*dy, 14*dy, 0])\n pline([4*dx, 4*dx], [dy, 13*dy])\n pline([5*dx, 5*dx], [dy, 13*dy])\n for i in range(1, 14):\n pline([3*dx, 6*dx], [i*dy, i*dy])\n pline([0, 0], [2*dy, 12*dy])\n pline([9*dx, 9*dx], [2*dy, 12*dy])\n pline([3*dx, 0], [dy, 2*dy])\n pline([3*dx, 0], [2*dy, 3*dy])\n pline([6*dx, 9*dx], [dy, 2*dy])\n pline([6*dx, 9*dx], [2*dy, 3*dy])\n pline([0, 3*dx], [12*dy, 13*dy])\n pline([9*dx, 6*dx], [12*dy, 13*dy])\n pline([0, 9*dx], [5*dy, 5*dy])\n pline([0, 9*dx], [9*dy, 9*dy])\n pline([2*dx, 2*dx], [1.35*dy, 2.3*dy])\n pline([7*dx, 7*dx], [1.35*dy, 2.3*dy])\n pline([dx, dx], [1.7*dy, 2.65*dy])\n pline([8*dx, 8*dx], [1.7*dy, 2.65*dy])\n ax.add_patch(patches.RegularPolygon(\n (1.7*dx, 3.7*dy), 4, 0.6*dx, color=(0,0,0)))\n ax.add_patch(patches.RegularPolygon(\n (7.4*dx, 3.7*dy), 4, 0.6*dx, facecolor=(1,0,0)))\n ax.text(4.5*dx, 13.4*dy, '0', fontsize=9, horizontalalignment='center', \\\n verticalalignment='center', color=(0,1,0))\n prot(3.5*dx, 12.4*dy, '1')\n pblack(4.5*dx, 12.4*dy, '2')\n prot(5.5*dx, 12.4*dy, '3')\n pblack(3.5*dx, 11.4*dy, '4')\n prot(4.5*dx, 11.4*dy, '5')\n pblack(5.5*dx, 11.4*dy, '6')\n prot(3.5*dx, 10.4*dy, '7')\n pblack(4.5*dx, 10.4*dy, '8')\n prot(5.5*dx, 10.4*dy, '9')\n pblack(3.5*dx, 9.4*dy, '10')\n pblack(4.5*dx, 9.4*dy, '11')\n prot(5.5*dx, 9.4*dy, '12')\n pblack(3.5*dx, 8.4*dy, '13')\n prot(4.5*dx, 8.4*dy, '14')\n pblack(5.5*dx, 8.4*dy, '15')\n prot(3.5*dx, 7.4*dy, '16')\n pblack(4.5*dx, 7.4*dy, '17')\n prot(5.5*dx, 7.4*dy, '18')\n prot(3.5*dx, 6.4*dy, '19')\n pblack(4.5*dx, 6.4*dy, '20')\n prot(5.5*dx, 6.4*dy, '21')\n pblack(3.5*dx, 5.4*dy, '22')\n prot(4.5*dx, 5.4*dy, '23')\n pblack(5.5*dx, 5.4*dy, '24')\n prot(3.5*dx, 4.4*dy, '25')\n pblack(4.5*dx, 4.4*dy, '26')\n prot(5.5*dx, 4.4*dy, '27')\n pblack(3.5*dx, 3.4*dy, '28')\n pblack(4.5*dx, 3.4*dy, '29')\n prot(5.5*dx, 3.4*dy, '30')\n pblack(3.5*dx, 2.4*dy, '31')\n prot(4.5*dx, 2.4*dy, '32')\n pblack(5.5*dx, 2.4*dy, '33') \n prot(3.5*dx, 1.4*dy, '34')\n pblack(4.5*dx, 1.4*dy, '35')\n prot(5.5*dx, 1.4*dy, '36') \n pblack(0.5*dx, 2.4*dy, 'P') \n pblack(8.5*dx, 2.4*dy, 'P') \n punt(0.7*dx, 2.13*dy)\n punt(8.7*dx, 2.13*dy)\n pblack(1.35*dx, 2.07*dy, 'M') \n pblack(7.35*dx, 2.07*dy, 'M') \n punt(1.72*dx, 1.85*dy)\n punt(7.72*dx, 1.85*dy) \n pblack(2.45*dx, 1.75*dy, 'D') \n pblack(6.45*dx, 1.75*dy, 'D') \n punt(2.75*dx, 1.48*dy)\n punt(6.75*dx, 1.48*dy) \n pblack(1.5*dx, 10.5*dy, 'Passe')\n pblack(7.5*dx, 10.5*dy, 'Manque')\n pblack(1.5*dx, 7*dy, 'Pair')\n pblack(7.5*dx, 7*dy, 'Impair')\n \n plt.show()\n\n tisch = brett\n\t\n @property\n def formeln(self):\n \"\"\"Berechnungsformeln\"\"\"\t\n\t\n def dm(x):\n return display(Math(x))\t\t\n\t\t\n print(' ')\t\t\n dm('\\mathrm{Gewinnerwartung\\;beim\\; Roulette - Spiel}')\n print(' ')\t\n dm('\\mathrm{Gewinnerwartung\\; bei\\; einer\\; Setzmöglichkeit\\; (Chance):}')\n dm('\\\\qquad GewinnQuote \\cdot GewinnWahrscheinlichkeit\\, + \\, (-1) \\cdot VerlustWahrscheinlichkeit')\n dm('\\\\qquad \\mathrm{(\\,-1 = Verlustquote\\;[gesetzter\\;Chip]\\,)}')\n dm('\\mathrm{Die\\; Wahrscheinlichkeiten\\; der\\; Chancen\\; werden\\; so\\; berechnet:}')\t\t\n dm('\\qquad P( Chance ) = (Anzahl\\; der\\; Zahlen\\; in\\; der\\; Chance)\\; / \\;37')\t\n print(' ')\t\t\n dm('\\mathrm{ Erwartung\\; bei\\; den\\; einzelnen\\; Chancen: \\\\qquad (s.a.\\; Hilfeseite)}')\n dm('\\mathrm{ Chance \\\\qquad\\\\qquad\\;\\; Anzahl \\\\qquad Erwartung \\;\\\\qquad\\\\qquad\\\\quad\t\\, in\\; \\% \\;zum}')\n dm('\\mathrm{\\\\qquad\\\\qquad\\\\qquad\\\\quad\\, Zahlen\t\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\\\\qquad\tEinsatz}')\t\n dm('\\mathrm{plein} \\;\\,\\\\qquad\\\\qquad\\\\quad\\\\quad\\\\quad 1 \\\\quad\\\\quad\t35 \\\\cdot \\\\frac{1}{37} - \\\\frac{36}{37} = -\\\\frac{1}{37} \\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{a\\; cheval} \\;\\\\qquad\\\\qquad\\\\quad\\\\quad 2 \\\\quad\\\\quad\t17 \\\\cdot \\\\frac{2}{37} - \\\\frac{35}{37} = -\\\\frac{1}{37} \\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{transversale\\; plein} \\\\quad\\\\qquad 3 \\\\quad\\\\quad\t11 \\\\cdot \\\\frac{3}{37} - \\\\frac{34}{37} = -\\\\frac{1}{37} \\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{carre} \\;\\,\\\\qquad\\\\qquad\\\\quad\\\\quad\\\\quad 4 \\\\quad\\\\quad\t8 \\\\cdot \\\\frac{4}{37} - \\\\frac{33}{37} = -\\\\frac{1}{37} \\;\\,\\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{transversale\\; simple} \\,\\;\\\\qquad 6 \\\\quad\\\\quad\t5 \\\\cdot \\\\frac{6}{37} - \\\\frac{31}{37} = -\\\\frac{1}{37} \\;\\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{Kolonne,\\; Dutzend} \\,\\,\\\\qquad 12 \\\\quad\\\\quad\t2 \\\\cdot \\\\frac{12}{37} - \\\\frac{25}{37} = -\\\\frac{1}{37} \\;\\\\quad\\\\quad -2.7 \\%')\t\t\n dm('\\mathrm{einfache\\; Chancen} \\;\\;\\\\qquad 18 \\\\quad\\\\quad\t1 \\\\cdot \\\\frac{18}{37} - \\\\frac{19}{37} = -\\\\frac{1}{37} \\;\\\\quad\\\\quad -2.7 \\%')\t\t\n print(' ')\t\t\n\t\t\n\t\t\n def P(self, *args, **kwargs):\n \"\"\"Wahrscheinlichkeit eines Ereignisses\"\"\"\n\t\t\n if kwargs.get('h'):\n print(\"\\nWahrscheinlichkeit eines Ereignisses\\n\")\n print(\"Aufruf r . P( e )\\n\")\t\t \n print(\" r Roulette-Objekt\")\n print(\" e Zahl aus {0,...,36} | Menge/Liste/Tupel von Zahlen |\")\n print(\" Chance beim einmaligen Spielen (s. Hilfeseite)\\n\")\n print(\" oder r . P( e, e1 )\\n\")\t\t \n print(\"Bei der Angabe von zwei Ereignissen wird die bedingte Wahrscheinlich-\")\n print(\"keit P( e | e1 ) berechnet\\n\")\n print(\"Beispiele\")\n print(\"r.P( 4 ) r.P( {12} ) r.P( r.colonne1 )\")\n print(\"r.P( { 28, 29, 30 } ) r.P( [28, 29, 30] )\") \n print(\"r.P( 'r.rouge und r.pair' )\") \n print(\"r.P( 12, r.rouge ) (bedingte Wahrscheinlichkeit)\\n\")\t\t\t\n return\t\t\t\n\t\t\t\n if len(args) not in (1, 2):\n print('zufall: ein oder zwei Ereignisse angeben')\n return\t\n\n def teil(x):\n if isinstance(x, set):\n return all([y in omega for y in x])\n else:\n if x in omega:\n return True\n return False\n\t\t\t \n omega = self.omega\t\t\n\t\t\t\t \n if len(args) == 1:\n e = args[0]\n if e == 0:\n pp = Rational(1, 37)\t\t\t\n elif not e:\n pp = 0\t\t\t\n elif not iterable(e) and e in omega:\t\t\t\t\t\n pp = Rational(1, 37)\n elif iterable(e):\n if not all([x in omega for x in e]):\n print('zufall: Elemente der Ergebnismenge angeben')\n return\n if not len(e) in (1, 2, 3, 4, 6, 12, 18):\t\t\t\t\t\n print('zufall: 1,2,3,4 oder 6 Zahlen oder benannte Chance angeben')\n return\n if len(e) == 2:\n if not set(e) in _a_cheval:\n print('zufall: keine a_cheval-Chance')\n return\n elif len(e) == 3:\n if not set(e) in _transversale_plein:\n print('zufall: keine transversale_plein-Chance')\n return\n elif len(e) == 4:\n if not set(e) in _carre:\n print('zufall: keine carre-Chance')\n return\n elif len(e) == 6:\n if not set(e) in _transversale_simple:\n print('zufall: keine transversale_simple-Chance')\n return\n elif len(e) == 12:\n if not set(e) in [self.colonne1, self.colonne2, self.colonne3, self.douze_premier, \\\n\t\t\t\t self.douze_milieu, self.douze_dernier]:\n print('zufall: keine Chance mit 12 Zahlen')\n return\n elif len(e) == 18:\n if not set(e) in [self.pair, self.impair, self.rouge, self.noir, self.manque, \\\n self.passe]:\n print('zufall: keine Chance mit 18 Zahlen')\n return\n pp = Rational(len(e), 37)\t\t\t\t\t\n elif isinstance(e, str):\n uu, oo, nn = e.find('und'), e.find('oder'), e.find('nicht')\t\t\t\n try:\n if uu >= 0:\n a, b = e[:uu].strip(), e[uu+3:].strip() \t\t\t\t\t \n ia, ib = a.find('.'), b.find('.')\n a, b = a[ia+1:], b[ib+1:]\n a, b = 'self.' + a, 'self.' + b\t\t\t\t\t\t\n a, b = eval(a), eval(b)\n if not (teil(a) and teil(b)):\n print('zufall: Ereignisse bei Roulette angeben')\n return\n if isinstance(a, set):\t\t\t\t\t\t\t\n if isinstance(b, set):\t\t\t\t\t\t\t\n ee = a.intersection(b)\n else:\t\t\t\t\t\t\t\t\n ee = a.intersection(set([b]))\n else:\t\n if isinstance(b, set):\t\t\t\t\t\t\t\n ee = set([a]).intersection(b)\n else:\t\t\t\t\t\t\t\t\n ee = set([a]).intersection(set([b]))\t\t\t\t\t\t\n pp = Rational(len(ee), 37)\t\t\t\t\t\t\t\t\t\t\t\n elif oo > 0:\n a, b = e[:oo].strip(), e[oo+3:].strip()\t\t\t\t\t \n ia, ib = a.find('.'), b.find('.')\n a, b = a[ia+1:], b[ib+1:]\n a, b = 'self.' + a, 'self.' + b\t\t\t\t\t\t\n a, b = eval(a), eval(b)\n if not (teil(a) and teil(b)):\n print('zufall: Ereignisse bei Roulette angeben')\n return\n if isinstance(a, set):\t\t\t\t\t\t\t\n if isinstance(b, set):\t\t\t\t\t\t\t\n ee = a.union(b)\n else:\t\t\t\t\t\t\t\t\n ee = a.union(set([b]))\n else:\t\n if isinstance(b, set):\n ee = set([a]).union(b)\n else:\t\t\t\t\t\t\t\t\n ee = set([a]).union(set([b]))\t\t\t\t\t\t\n pp = Rational(len(ee), 37)\t\t\t\t\t\t\t\t\t\t\t\n elif nn >= 0:\n a = e[nn+5:].strip()\t\t\t\t \n ia = a.find('.')\n a = a[ia+1:]\n a = 'self.' + a\t\t\t\t\t\t\n a = eval(a)\n if not teil(a):\n print('zufall: Ereignis bei Roulette angeben')\n return\n if isinstance(a, set):\t\t\t\t\t\t\t\n ee = omega.difference(a)\n else:\n ee = omega.difference(set([a]))\t\t\t\t\t\t\n pp = Rational(len(ee), 37)\t\t\t\t\t\t\t\t\t\t\t\n else:\n ee = eval(e)\n pp = Rational(len(ee), 37)\t\t\t\t\t\t\t\t\t\t\t\n except:\n print('zufall:', 'Ausdruck überprüfen')\n return\t\t\t\n else:\n print('zufall: Ereignis bei Roulette angeben')\n return\n\t\t\t\t\t\t\t\n elif len(args) == 2: \n e1, e2 = args\t\n if iterable(e1):\n e1 = set(e1)\t\t\t\n if iterable(e2):\n e2 = set(e2)\n try:\t\t\t\n if isinstance(e1, set):\n if isinstance(e2, set):\n ee = e1.intersection(e2)\n else:\n ee = e1.intersection(set([e2]))\n else:\n if isinstance(e2, set):\n ee = set([e1]).intersection(e2)\n else:\n ee = set([e1]).intersection(set([e2]))\n pp1, pp2 = self.P(ee), self.P(e2)\n pp = nsimplify(pp1 / pp2, rational=True)\n except:\n print('zufall: die Angaben bitte überprüfen')\t\n return\n \t\t\t\n return pp\t\n\t\t\n\t\t\n def spiel(self, *args, **kwargs):\n \"\"\"Spiel\"\"\"\n\t\t\n if kwargs.get('h'):\n print(\"\\nSpiel ( Roulette )\\n\")\n print(\"Aufruf r . spiel( chance /[, m ] )\\n\")\t\t \n print(\" r Roulette-Objekt\")\n print(\" chance gesetzte Chance - einzelne Zahl oder Menge von \")\n print(\" 1-6 Zahlen aus {0,1,...,36} | r.colonne1 |\") \n print(\" r.colonne2 | r.colonne3 | r.douze_premier |\")\n print(\" r.douze_milieu | r.douze_dernier | r.pair |\") \n print(\" r.impair | r.rouge | r.noir | r.manque |\") \n print(\" r.passe\")\t\t\t\n print(\" m Anzahl Spiele; Standard=1\\n\")\t\t\t\n print(\"Zusatz g=ja Grafik des Gewinn-Verlaufes\")\n print(\" m=ja Grafik des Verlaufes des mittleren Gewinns\")\n print(\" d=ja Bei Angabe von m > 1 Rückgabe einer DatenReihe mit dem\") \n print(\" Gewinn/Verlust je Spiel\")\n print(\" gd=ja Gewinnverlauf + DatenReihe\")\n print(\" md=ja Mittlerer Gewinn + DatenReihe\\n\")\n return\t\t\t\n\n try:\t \n if len(args) not in (1, 2):\n raise ZufallError(\"ein oder zwei Argumente angeben\")\n chance = args[0]\t\t\t\n if not (iterable(chance) or isinstance(chance, (int, Integer))):\n raise ZufallError(\"einzelne Zahl oder Menge von Zahlen angeben\")\t\t\t\t\t\n if isinstance(chance, (int, Integer)):\n if chance not in self.omega:\n raise ZufallError(\"Element der Ergebnismenge angeben\")\t\t\t\t\t\n chance = set([chance])\t\n else:\n chance = set(chance)\n if not all([x in self.omega for x in chance]):\n raise ZufallError(\"Element der Ergebnismenge angeben\")\t\t\t\t\t\n if len(chance) == 1:\n if list(chance)[0] not in self.omega:\t\t\t\n raise ZufallError(\"keine gültige Chance\")\t\t\t\t\t\n elif len(chance) == 2:\n if chance not in _a_cheval:\t\t\t\n raise ZufallError(\"keine gültige a_cheval-Chance\")\t\t\t\t\t\n elif len(chance) == 3:\n if chance not in _transversale_plein:\t\t\t\n raise ZufallError(\"keine gültige transversale_plein-Chance\")\t\t\t\t\t\t\t\t\t\t\t\n elif len(chance) == 4:\n if chance not in _carre:\t\t\t\n raise ZufallError(\"keine gültige carre-Chance\")\t\t\t\t\t\n elif len(chance) == 6:\n if chance not in _transversale_simple:\t\t\t\n raise ZufallError(\"keine gültige transversale_simple-Chance\")\t\t\t\t\t\t\t\t\n elif len(chance) == 12:\n if chance not in [self.colonne1, self.colonne2, self.colonne3,\n self.douze_premier, self.douze_milieu, self.douze_dernier]:\t\t\t\n raise ZufallError(\"keine gültige Chance\")\t\t\t\t\t\n elif len(chance) == 18:\n if chance not in [self.pair, self.impair, self.rouge, self.noir,\n self.manque, self.passe]:\t\t\t\n raise ZufallError(\"keine gültige Chance\")\t\t\t\t\t\n else:\n raise ZufallError(\"keine gültige Chance\")\n\t\t\t\t\t\n m = 1\t\t\t\n if len(args) == 2:\n m = args[1]\t\t\t\n if not (isinstance(m, (int, Integer)) and m > 0):\t\t\t\n raise ZufallError(\"für m ganze Zahl > 0 angebem\")\t\t\t\t\t\n\t\t\n except ZufallError as e:\n print('zufall:', str(e))\n return\n\t\t\t\n def dm(x):\n return display(Math(x))\n \t\t\t\n vv = GleichVerteilung(37) \n if len(args) == 1 or len(args) == 2 and m == 1:\t\t\n erg = vv.versuch - 1 # die Gleichverteilung ist auf {1,2,...,37} definiert\t\n print(' ')\t\t\t\n dm('\\mathrm{Gesetzt\\;\\, :\\;\\; }' + latex(chance))\t\t\n dm('\\mathrm{Ergebnis:\\;\\; }' + str(erg))\n txt = '\\mathrm{Spiel\\;gewonnen}' if erg in chance else '\\mathrm{Spiel\\;verloren}'\t\t\t\n dm(txt)\t\t\n print(' ')\n return\t\t\t\n else:\n gewinn = dict([(1, 35), (2, 17), (3, 11), (4, 8), (6, 5), (12, 2), (18, 1)])\t\t\n sp = vv.stich_probe(m)\n sp = [x-1 for x in sp]\t\t\t\n dr = [ (gewinn[len(chance)] if x in chance else -1) for x in sp]\n\n if kwargs.get('g') or kwargs.get('gd'):\n print(' ')\t\t\t\n dm('\\\\qquad\\mathrm{Verlauf\\;des\\;Gewinns,\\;aktueller\\;Gewinn}')\t\t\t\n verlauf_grafik(dr, art='summe', xlabel='Anzahl Spiele')\n elif kwargs.get('m') or kwargs.get('md'):\t\n pass\n print(' ')\t\t\t\n dm('\\\\qquad\\mathrm{Verlauf\\;des\\; mittleren\\;Spielgewinnes}') \n dm('\\\\qquad\\mathrm{grün-theoretischer\\; Erwartungswert\\;bei\\;einem\\;Spiel\\; (-1/37)}')\t\t\t\n verlauf_grafik(dr, art='mittel', vergl=float(-1/37), xlabel='Anzahl Spiele')\n\t\t\t\n if not kwargs:\t\t\t\n L = len(dr)\t\t\t\n G = dr.count(1)\t\n V = L - G\n p = float((G-V)/L * 100)\n print(' ')\t\t\t\n dm('\\mathrm{Gesetzt\\;\\,\\; : \\;\\; }' + latex(chance))\t\t\n dm('\\mathrm{Gewonnen\\;(1): \\;\\; }' + str(G))\n dm('\\mathrm{Verloren\\;(-1):\\;\\; }' + str(V))\n dm('\\mathrm{Gesamt\\;\\\\quad\\\\quad\\,:\\; }' + str(G-V) + '=' + '{0:.2f}'.format(p) + '\\%')\n if kwargs.get('d') or kwargs.get('gd') or kwargs.get('md'):\t\t\t\n dm('\\mathrm{Rückgabe\\; einer\\; DatenReihe\\; mit \\;dem\\;Gewinn\\,/\\,Verlust\\;je\\;Spiel}')\n print(' ')\t\t\t\n return DatenReihe(dr)\t\t\t\t\n print(' ')\t\t\t\n \n\t\t\t\n @property\t\t\n def hilfe(self): \n \"\"\"Bezeichner der Eigenschaften und Methoden\"\"\"\n roulette_hilfe(3)\t\n\t\t\n h = hilfe\t\t\t\t\t\n\t\t\t\n\t\t\n\t\t\n# Benutzerhilfe für Roulette\n# --------------------------\n\ndef roulette_hilfe(h):\n \n if h == 1:\n print(\"h=2 - Erzeugung\")\n print(\"h=3 - Eigenschaften und Methoden\")\n print(\"h=4 - Ereignisse\")\n return\n\t\t \n if h == 2:\n print(\"\"\" \\\n\t\t\nRoulette - Objekt\n\t\nErzeugung Roulette( )\n\t\t\t\t \nZuweisung r = Roulette() (r - freier Bezeichner)\n\t \"\"\")\n return \n\t\t\n if h == 3: \n print(\"\"\" \\\n\t\t\nEigenschaften und Methoden (M) für Roulette\n \t\nr.hilfe Bezeichner der Eigenschaften und Methoden\nr.brett Spielbrett (Abbildung)\nr.formeln Berechnungsformeln\nr.omega Ergebnismenge\nr.P(...) M Wahrscheinlichkeiten beim einmaligen Spielen\nr.regeln Spielregeln\nr.spiel(...) M Spiel\nr.tisch = s.brett\n\nSynonymer Bezeichner\n\nhilfe h\n\"\"\")\n return \n\t\t\n if h == 4: \n print(\"\"\" \\\n\t\t\nEreignisse (Setzmöglichkeiten, Chancen) beim einmaligen Roulette-\nSpiel\n\n(Unbenannte) Ereignisse, die über die Menge der Zahlen angegeben \nwerden:\n Anzahl Gewinn-\nName Beschreibung Zahlen quote \n \nplein einzelne Zahl z.B. 3 bzw. {3} 1 35 : 1\na_cheval zwei angrenzende Zahlen z.B. {13,16} 2 17 : 1\ntransversale_plein Querreihe von drei Zahlen z.B. {28,29,30} 3 11 : 1\ncarre vier Zahlen, deren Felder z.B. {14,15,17,18} 4 8 : 1\n in einem Punkt zusammensto- \n ßen bzw. die ersten vier \n Zahlen \t\t\t\ntransversale_simple zwei benachbarte Querreihen z.B. {7,8 9,10,11,12} 6 5 : 1\n\nKolonne und Dutzend:\nr.colonne1 die linke Reihe {1,4,7,..,34} 12 2 : 1\nr.colonne2 die mittlere Reihe {2,5,8,..,35} \t\t\t \nr.colonne3 die rechte Reihe {3,6,9,..,36}\t\t\t\nr.douze_premier das erste Dutzend {1,2,..,12}\t\t\t \nr.douze_milieu das mittlere Dutzend {13,14,..,24}\t\t\t\nr.douze_dernier das letzte Dutzend {25,26,..,36}\n\t\t\t \nEinfache Chancen:\nr.pair die geraden Zahlen außer 0 {2,4,6,..,36} 18 1 : 1\nr.impair die ungeraden Zahlen {1,3,5,..,35}\t\t\t\nr.rouge die roten Zahlen {1,3,7,..36}\t\t\t\nr.noir die schwarzen Zahlen {2,4,6,..35}\t\t\t\nr.manque die erste Hälfte {1,2,..,18}\t\t\t\nr.passe die zweite Hälfte {19,20,..,36}\t\t\t\n\t\"\"\")\n return \n\n\t\t\n\t\t\n# 'Unbenannte' Chancen außer plein\t\t\n# --------------------------------\t\t\n_a_cheval = [{0, 1}, {0, 2}, {0, 3}, {1, 2}, {2, 3}, {1, 4}, {2, 5}, {4, 5}, {3, 6}, \\\n {5, 6}, {4, 7}, {5, 8}, {6, 9}, {7, 8}, {8, 9}, {7, 10}, {8, 11}, {10, 11}, \\\n {9, 12}, {11, 12}, {10, 13}, {11, 14}, {12, 15}, {13, 14}, {13, 16}, \\\n {14, 15}, {14, 17}, {15, 18}, {16, 17}, {17, 18}, {16, 19}, {17, 20}, \\\n {19, 20}, {18, 21}, {19, 22}, {20, 21}, {20, 23}, {22, 23}, {21, 24}, \\\n {22, 25}, {23, 24}, {23, 26}, {25, 26}, {24, 27}, {25, 28}, {26, 27}, \\\n {26, 29}, {28, 29}, {27, 30}, {28, 31}, {29, 30}, {29, 32}, {30, 33}, \\\n {31, 32}, {32, 33}, {31, 34}, {32, 35}, {33, 36}, {34, 35}, {35, 36}]\t\t\n_transversale_plein = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14, 15}, \\\n {16, 17, 18}, {19, 20, 21}, {22, 23, 24}, {25, 26, 27}, {28, 29, 30}, \\\n {31, 32, 33}, {34, 35, 36}]\t\n_carre = [{1, 2, 3, 4}, {1, 2, 4, 5}, {2, 3, 5, 6}, {4, 5, 7, 8}, {5, 6, 8, 9}, \\\n {7, 8, 10, 11}, {8, 9, 11, 12}, {10, 11, 13, 14}, {11, 12, 14, 15}, \\\n {13, 14, 16, 17}, {14, 15, 17, 18}, {16, 17, 19, 20}, {17, 18, 20, 21}, \n {19, 20, 22, 23}, {20, 21, 23, 24}, {22, 23, 25, 26}, {23, 24, 26, 27}, \\\n {25, 26, 28, 29}, {26, 27, 29, 30}, {28, 29, 31, 32}, {29, 30, 32, 33}, \\\n {31, 32, 34, 35}, {32, 33, 35, 36}]\t\t\t\t \n_transversale_simple = [{1, 2, 3, 4, 5, 6}, {4, 5, 6, 7, 8, 9}, {7, 8, 9, 10, 11, 12}, \\\n {10, 11, 12, 13, 14, 15}, {13, 14, 15, 16, 17, 18}, {16, 17, 18, 19, 20, 21}, \\\n {19, 20, 21, 22, 23, 24}, {22, 23, 24, 25, 26, 27}, {25, 26, 27, 28, 29, 30}, \\\n {28, 29, 30, 31, 32, 33}, {31, 32, 33, 34, 35, 36}]\t\t\t\t \n\t\t\n\t\n", "meta": {"hexsha": "f344e1cda96fa9a3929a1b64d05a5eaed2c2607c", "size": 28515, "ext": "py", "lang": "Python", "max_stars_repo_path": "zufall/lib/objekte/roulette.py", "max_stars_repo_name": "HBOMAT/AglaUndZufall", "max_stars_repo_head_hexsha": "3976fecf024a5e4e771d37a6b8056ca4f7eb0da1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zufall/lib/objekte/roulette.py", "max_issues_repo_name": "HBOMAT/AglaUndZufall", "max_issues_repo_head_hexsha": "3976fecf024a5e4e771d37a6b8056ca4f7eb0da1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zufall/lib/objekte/roulette.py", "max_forks_repo_name": "HBOMAT/AglaUndZufall", "max_forks_repo_head_hexsha": "3976fecf024a5e4e771d37a6b8056ca4f7eb0da1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.139183056, "max_line_length": 164, "alphanum_fraction": 0.4418376293, "include": true, "reason": "from sympy", "num_tokens": 8876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.15203224354320868, "lm_q1q2_score": 0.07601612177160434}} {"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport os\nfrom sympy import *\nimport pandas as pd\nimport numpy as np\nimport scipy.fftpack\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn-paper\")\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n\n\n# ## Canvas palette\n\n# In[6]:\n\n\n#Canvas for single plot\nx = np.linspace(0,10,100)\ny = np.sin(x)\nplt.figure(figsize=[14,6])\nplt.grid(True)\nplt.title(\"Change-me!\",fontsize=20)\nplt.plot(x,y,label=\"testvalue\")\nplt.legend(fontsize=16)\nplt.xlabel(\"XLABEL (unit)\",fontsize=18)\nplt.ylabel(\"YLABEL (unit)\",fontsize=18)\nplt.show()\n\n\n# In[7]:\n\n\n#Canvas for side by side\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,6))\nfig.suptitle(\"test\",y=1.05,fontsize=20)\n\naxes[0].grid(True)\naxes[0].plot(x,y,label=\"testvalue\")\naxes[0].legend(fontsize=16)\naxes[0].set_title(\"TESTTITLE\",fontsize=18)\naxes[0].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0].legend(fontsize=16)\naxes[0].tick_params(axis='both', which='major', labelsize=15)\n\n\naxes[1].grid(True)\naxes[1].plot(x,y,label=\"testvalue\")\naxes[1].legend(fontsize=16)\naxes[1].set_title(\"TESTTITLE\",fontsize=18)\naxes[1].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[1].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[1].legend(fontsize=16)\naxes[1].tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.show()\n\n\n# In[8]:\n\n\n#Canvas for side by side\nfig, axes = plt.subplots(nrows=2, ncols=4, figsize=(14,6))\nfig.suptitle(\"test\",y=1.05,fontsize=20)\n\naxes[0,0].grid(True)\naxes[0,0].plot(x,y,label=\"testvalue\")\naxes[0,0].legend(fontsize=16)\naxes[0,0].set_title(\"TESTTITLE\",fontsize=18)\naxes[0,0].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0,0].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0,0].legend(fontsize=16)\naxes[0,0].tick_params(axis='both', which='major', labelsize=15)\n\n\naxes[0,1].grid(True)\naxes[0,1].plot(x,y,label=\"testvalue\")\naxes[0,1].legend(fontsize=16)\naxes[0,1].set_title(\"TESTTITLE\",fontsize=18)\naxes[0,1].set_xlabel(\"XLABEL (unit)\",fontsize=18)\naxes[0,1].set_ylabel(\"YLABEL (unit)\",fontsize=18)\naxes[0,1].legend(fontsize=16)\naxes[0,1].tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.show()\n\n\n# ## Read data\n\n# In[11]:\n\n\n#Folder and paths definitions\nmain_path = os.getcwd()\ndatafolder_path = main_path+\"/results\"\nresults_dir = \"/output_py\" \noutput_dir = main_path+results_dir\ntry:\n os.mkdir(output_dir)\nexcept OSError:\n print (\"Creation of the directory %s failed\" % results_dir)\nelse:\n print (\"Successfully created the directory %s \" % results_dir)\n\n\n# In[ ]:\n\n\n\n\n\n# In[81]:\n\n\n#Simulation parameters\nN = 1000\nT = 10000\nn_runs = 10\ndt = .01\nfreq = \"ufreq\"\nfixed_plot = False #--> fixed phase and variable freqs, False viceversa\ngamma = .5\nMF = \"MF\"\n\nif(freq ==\"gfreq\"):\n freq_plot=\"$\\\\vec{\\\\omega_{0}} = \\\\mathcal{N}(0,1)$\"\nelse:\n freq_plot=\"$\\\\vec{\\\\omega_{0}} = U(-%.1f,%.1f)$\"%(gamma,gamma)\nif(MF ==\"MF\"):\n MF_plot=\"MeanField\"\nelse:\n MF_plot=\"non-meanField\"\n\nif(fixed_plot==True):\n fixed_plot = \"FixedPhase\"\nelse:\n fixed_plot = \"FixedFreq\"\n\n\n# In[82]:\n\n\n#OutputFileNames\n#S/N --> |r(t)|/sigma(r(t))\nsn_name = \"S_N\"\n#(Mod&Phase)(t)\nmodphase_name = \"ModPhase_t\"\n#(Mod)(t)\nmod_name = \"Mod_t\"\n#Spectrum\nspectrum_name = \"Spectrum\"\n#r_inf\nrinf_name = \"r_inf\"\n#Configuration-specific name\nif(freq!=\"gfreq\"):\n config_name= \"/N%d_nruns%d_freq=%s_gamma=%.2f\"%(N,n_runs,freq,gamma)\nelse:\n config_name= \"/N%d_nruns%d_freq=%s_\"%(N,n_runs,freq)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[84]:\n\n\n#Create dataframe dictionary. For each entry, first value is the K of the dataframe (second value)\ndata = []\nfor i in range(0,n_runs):\n filename = datafolder_path + \"/PART2_ufreq_uphase_N1000_NOMF_T10000_dt0.0100_nruns10_K1.000_NO_Fphase_Ffreq_RUN%d.tsv\"%(i)\n #cols refers to timestep, mod, phase, (of order parameter)\n df = pd.read_csv(filename,sep=\"\\t\",header=None)\n data.append([\"n_run=%d\"%(i),df])\n \n\n\n# In[ ]:\n\n\n\n\n\n# ## Plots\n\n# In[ ]:\n\n\n\n\n\n# In[85]:\n\n\n#Plot settings\nalph = 1\ntmax = 100\n\n\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(14,6))\n\nfig.suptitle(\"N = %d, dt = %.3f, %s, K=1\"%(N,dt,freq_plot),y=.95,fontsize=20)\n\nplt.grid(True)\n\n#for i in range(0,2):\nfor i in range(0,n_runs):\n plt.plot(data[i][1][0],data[i][1][1],ls='--',linewidth=.8,markersize=.05,label=\"n_run=%d\"%(i+1),alpha=alph)\n\nplt.title(\"Re[r(t)], fixed $\\\\vec{\\\\omega}(0)$\",fontsize=18)\nplt.xlabel(\"t\",fontsize=18)\nplt.ylabel(\"\",fontsize=18)\nplt.legend(fontsize=16,ncol=2)\nplt.xlim(0,tmax)\nplt.tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.xlim(0,20)\nplt.subplots_adjust(top=.825)\nplt.savefig(output_dir+config_name+mod_name+fixed_plot+\"real.png\")\nplt.show()\n\n\n# In[86]:\n\n\n#Plot settings\nalph = 1\ntmax = 100\n\n\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(14,6))\n\nfig.suptitle(\"N = %d, dt = %.3f, %s, K=1\"%(N,dt,freq_plot),y=.95,fontsize=20)\n\nplt.grid(True)\n\n#for i in range(0,2):\nfor i in range(0,n_runs):\n plt.plot(data[i][1][0],data[i][1][2],ls='--',linewidth=.8,markersize=.05,label=\"n_run=%d\"%(i+1),alpha=alph)\n\nplt.title(\"Im[r(t)], fixed $\\\\vec{\\\\omega}(0)$\",fontsize=18)\nplt.xlabel(\"t\",fontsize=18)\nplt.ylabel(\"\",fontsize=18)\nplt.legend(fontsize=16,ncol=2)\nplt.xlim(0,tmax)\nplt.tick_params(axis='both', which='major', labelsize=15)\n\nfig.tight_layout()\nplt.xlim(0,20)\nplt.subplots_adjust(top=.825)\nplt.savefig(output_dir+config_name+mod_name+fixed_plot+\"imag.png\")\nplt.show()\n\n\n# In[70]:\n\n\n\nfig, axes = plt.subplots(nrows=2, ncols=5, figsize=(14,6))\nfig.suptitle(\"$\\\\mathcal{F} (r(t))$\\nN = %d, dt = %.3f, %s, n_runs = %d\"%(N,dt,freq_plot, n_runs),y=1,fontsize=20)\ncounter1 = 0\ncounter2 = 0\n#for i in range(0,2):\nfor i in range(0,n_runs):\n if(counter1